// File Path: monorepo/web/frontend/src/pages/Admin/Speaker/Detail/More/Avatar/Page.jsx

import React, {
  useState,
  useEffect,
  useCallback,
  useMemo,
  useRef,
} from "react";
import { useNavigate, useParams } from "react-router";
import {
  CameraIcon,
  ExclamationTriangleIcon,
  CheckCircleIcon,
  TrashIcon,
  ArrowUpTrayIcon,
  UserCircleIcon,
  ArrowLeftIcon,
  UsersIcon,
} from "@heroicons/react/24/outline";
import {
  useSpeakerManager,
  useAuthManager,
} from "../../../../../../services/Services";
import {
  Breadcrumb,
  PageHeader,
  FormCard,
  Alert,
  Button,
  Badge,
  Loading,
  UIXThemeProvider,
  useUIXTheme,
} from "../../../../../../components/UIX";
import { SPEAKER_STATUS_ARCHIVED } from "../../../../../../constants/Speaker";
import {
  ALLOWED_IMAGE_MIME_TYPES,
  ALLOWED_IMAGE_EXTENSIONS,
  MAX_AVATAR_FILE_SIZE_BYTES,
  MAX_AVATAR_FILE_SIZE_MB,
  FILE_UPLOAD_ERRORS,
  BYTES_PER_MB,
} from "../../../../../../constants/FileUpload";
import { SUCCESS_MESSAGE_REDIRECT_DELAY } from "../../../../../../constants/UI";

function AdminSpeakerDetailMoreAvatarPage() {
  // URL Parameters
  const { aid } = useParams();

  // Navigation
  const navigate = useNavigate();

  // Services
  const speakerManager = useSpeakerManager();
  const authManager = useAuthManager();

  // Theme
  const { getThemeClasses } = useUIXTheme();

  // Refs
  const fileInputRef = useRef(null);

  // Breadcrumb items
  const breadcrumbItems = useMemo(
    () => [
      { label: "Dashboard", to: "/admin/dashboard" },
      { label: "Speakers", to: "/admin/speakers" },
      { label: "Detail", to: `/admin/speaker/${aid}` },
      { label: "More", to: `/admin/speaker/${aid}/more` },
      { label: "Avatar" },
    ],
    [aid],
  );

  // Component states
  const [errors, setErrors] = useState({});
  const [isFetching, setFetching] = useState(false);
  const [speaker, setSpeaker] = useState(null);
  const [selectedFile, setSelectedFile] = useState(null);
  const [successMessage, setSuccessMessage] = useState("");
  const [isUploading, setIsUploading] = useState(false);

  // Unauthorized callback
  const onUnauthorized = useCallback(() => {
    navigate("/login?unauthorized=true");
  }, [navigate]);

  // Load speaker details
  useEffect(() => {
    let mounted = true;

    const fetchSpeaker = async () => {
      if (!authManager.isAuthenticated()) {
        navigate("/login");
        return;
      }

      setFetching(true);
      setErrors({});

      try {
        const data = await speakerManager.getSpeakerDetail(aid, onUnauthorized);
        if (mounted) {
          setSpeaker(data);
        }
      } catch (error) {
        if (mounted) {
          if (import.meta.env.DEV) {
            console.error("Failed to fetch speaker:", error);
          }
          setErrors(error);
        }
      } finally {
        if (mounted) {
          setFetching(false);
        }
      }
    };

    if (aid) {
      fetchSpeaker();
    } else {
      setErrors({ general: "Speaker ID is required" });
      setFetching(false);
    }

    return () => {
      mounted = false;
    };
  }, [aid, speakerManager, authManager, navigate, onUnauthorized]);

  // Handle file selection
  const handleFileChange = useCallback((event) => {
    const file = event.target.files[0];

    // Validate file
    if (file) {
      // Check file type
      if (!ALLOWED_IMAGE_MIME_TYPES.includes(file.type)) {
        setErrors({ file: FILE_UPLOAD_ERRORS.INVALID_TYPE });
        setSelectedFile(null);
        event.target.value = null; // Reset file input
        return;
      }

      // Check file size
      if (file.size > MAX_AVATAR_FILE_SIZE_BYTES) {
        setErrors({ file: FILE_UPLOAD_ERRORS.FILE_TOO_LARGE });
        setSelectedFile(null);
        event.target.value = null; // Reset file input
        return;
      }

      // File is valid
      setErrors({});
      setSelectedFile(file);
    } else {
      setSelectedFile(null);
    }
  }, []);

  // Handle form submission
  const handleSubmit = useCallback(async () => {
    if (!selectedFile) {
      setErrors({ file: FILE_UPLOAD_ERRORS.NO_FILE_SELECTED });
      return;
    }

    setErrors({});
    setIsUploading(true);

    try {
      // Create FormData
      const formData = new FormData();
      formData.append("speaker_id", aid);
      formData.append("file", selectedFile);

      // Upload avatar
      await speakerManager.uploadSpeakerAvatar(formData, onUnauthorized);

      // Set success message
      setSuccessMessage("Photo has been successfully updated");

      // Navigate back after a short delay
      setTimeout(() => {
        navigate(`/admin/speaker/${aid}/more`);
      }, SUCCESS_MESSAGE_REDIRECT_DELAY);
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("Failed to upload avatar:", error);
      }
      setErrors(error);
      setIsUploading(false);
    }
  }, [aid, speakerManager, navigate, onUnauthorized, selectedFile]);

  // Handle file removal
  const handleRemoveFile = useCallback(() => {
    setSelectedFile(null);
    setErrors({});
    // Reset the file input using ref
    if (fileInputRef.current) {
      fileInputRef.current.value = null;
    }
  }, []);

  // Memoize file size display
  const fileSizeMB = useMemo(() => {
    if (!selectedFile) return null;
    return (selectedFile.size / BYTES_PER_MB).toFixed(2);
  }, [selectedFile]);

  // Memoize speaker name
  const speakerName = useMemo(() => {
    if (!speaker) return "";
    return `${speaker.firstName} ${speaker.lastName}`;
  }, [speaker]);

  // Render loading state
  if (isFetching && !speaker) {
    return (
      <UIXThemeProvider>
        <div className="min-h-screen bg-gray-50">
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
            <div className="flex items-center justify-center py-12">
              <Loading message="Loading speaker details..." />
            </div>
          </div>
        </div>
      </UIXThemeProvider>
    );
  }

  return (
    <UIXThemeProvider>
      <div className="min-h-screen bg-gray-50">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
          {/* Breadcrumb */}
          {breadcrumbItems && (
            <Breadcrumb items={breadcrumbItems} className="mb-6" />
          )}

          {/* Page Header */}
          <div className="mb-8">
            <PageHeader
              title="Change Photo"
              subtitle={speakerName}
              icon={CameraIcon}
            >
              <div className="flex items-center gap-2">
                {speaker?.status === SPEAKER_STATUS_ARCHIVED && (
                  <Badge variant="secondary">Archived</Badge>
                )}
              </div>
            </PageHeader>
          </div>

          {/* Success Message */}
          {successMessage && (
            <Alert
              type="success"
              message={successMessage}
              icon={CheckCircleIcon}
              className="mb-6"
            />
          )}

          {/* Error Messages */}
          {errors && Object.keys(errors).length > 0 && (
            <Alert
              type="error"
              message={
                errors.file ||
                errors.message ||
                errors.detail ||
                errors.general ||
                "An error occurred. Please try again."
              }
              className="mb-6"
              onDismiss={() => setErrors({})}
            />
          )}

          {/* Main Content Card */}
          <FormCard
            title="Upload Photo"
            icon={ArrowUpTrayIcon}
            description="Change the speaker's profile photo"
            maxWidth="4xl"
          >
            {/* Warning Message */}
            <Alert
              type="warning"
              icon={ExclamationTriangleIcon}
              className="mb-6"
            >
              <div className="space-y-2">
                <p className="font-semibold">Warning</p>
                <p className="text-sm">
                  Uploading a new photo will replace the existing one. The
                  previous photo cannot be recovered.
                </p>
              </div>
            </Alert>

            {/* File Upload Section */}
            <div className="mb-6">
              {selectedFile ? (
                <Alert type="success" className="mb-0">
                  <div className="flex justify-between items-start w-full">
                    <div className="flex-1">
                      <div className="flex items-center mb-2">
                        <CheckCircleIcon className="w-5 h-5 mr-2" />
                        <span className="font-medium">
                          File ready to upload
                        </span>
                      </div>
                      <div className="text-sm space-y-1">
                        <p>
                          <span className="font-medium">File name:</span>{" "}
                          {selectedFile.name}
                        </p>
                        <p>
                          <span className="font-medium">File size:</span>{" "}
                          {fileSizeMB} MB
                        </p>
                      </div>
                    </div>
                    <Button
                      variant="danger"
                      size="sm"
                      onClick={handleRemoveFile}
                      disabled={isUploading}
                      icon={TrashIcon}
                    >
                      Remove
                    </Button>
                  </div>
                </Alert>
              ) : (
                <div>
                  <label
                    className={`block text-sm font-medium ${getThemeClasses("text-secondary")} mb-2`}
                  >
                    Select Photo File
                  </label>
                  <input
                    ref={fileInputRef}
                    id="avatar-file-input"
                    name="file"
                    type="file"
                    accept={ALLOWED_IMAGE_MIME_TYPES.join(",")}
                    onChange={handleFileChange}
                    disabled={isUploading}
                    className={`block w-full text-sm ${getThemeClasses("text-primary")} border ${getThemeClasses("input-border")} rounded-lg cursor-pointer ${getThemeClasses("bg-card")} focus:outline-none ${getThemeClasses("input-focus-ring")} ${getThemeClasses("focus-border")} disabled:opacity-50 disabled:cursor-not-allowed file:mr-4 file:py-2 file:px-4 file:border-0 file:text-sm file:font-medium ${getThemeClasses("alert-info-bg")} ${getThemeClasses("alert-info-text")} ${getThemeClasses("alert-info-hover")}`}
                  />
                  <p
                    className={`mt-2 text-xs ${getThemeClasses("text-muted")}`}
                  >
                    Accepted formats: {ALLOWED_IMAGE_EXTENSIONS.join(", ")}.
                    Maximum size: {MAX_AVATAR_FILE_SIZE_MB} MB.
                  </p>
                </div>
              )}
            </div>

            {/* Speaker Information */}
            {speaker && (
              <div
                className={`${getThemeClasses("bg-disabled")} rounded-lg p-4 mb-6`}
              >
                <h3
                  className={`text-sm font-medium ${getThemeClasses("text-secondary")} mb-3 flex items-center`}
                >
                  <UserCircleIcon className="w-4 h-4 mr-2" />
                  Current Speaker Information
                </h3>
                <div className="space-y-2 text-sm">
                  <div>
                    <span
                      className={`font-medium ${getThemeClasses("text-secondary")}`}
                    >
                      Name:
                    </span>{" "}
                    <span className={getThemeClasses("text-primary")}>
                      {speakerName}
                    </span>
                  </div>
                  <div>
                    <span
                      className={`font-medium ${getThemeClasses("text-secondary")}`}
                    >
                      Email:
                    </span>{" "}
                    <span className={getThemeClasses("text-primary")}>
                      {speaker.email}
                    </span>
                  </div>
                  {speaker.avatarObjectUrl && (
                    <div>
                      <span
                        className={`font-medium ${getThemeClasses("text-secondary")}`}
                      >
                        Current Photo:
                      </span>{" "}
                      <span className={getThemeClasses("text-primary")}>
                        Photo exists (will be replaced)
                      </span>
                    </div>
                  )}
                </div>
              </div>
            )}

            {/* Action Buttons */}
            <div
              className={`flex flex-col sm:flex-row gap-3 mt-6 pt-6 border-t ${getThemeClasses("border-secondary")}`}
            >
              <Button
                type="button"
                onClick={() => navigate(`/admin/speaker/${aid}/more`)}
                variant="outline"
                icon={ArrowLeftIcon}
                disabled={isUploading}
                className="flex-1"
              >
                Back to More
              </Button>
              <Button
                type="button"
                onClick={handleSubmit}
                variant="primary"
                icon={CheckCircleIcon}
                disabled={!selectedFile || isUploading}
                loading={isUploading}
                className="flex-1"
              >
                {isUploading ? "Uploading..." : "Save Photo"}
              </Button>
            </div>
          </FormCard>
        </div>
      </div>
    </UIXThemeProvider>
  );
}

export default AdminSpeakerDetailMoreAvatarPage;
