// File Path: monorepo/web/frontend/src/pages/Admin/Setting/EventCategory/Detail/Page.jsx
import React, { useState, useEffect } from "react";
import { Link, useNavigate, useParams, useLocation } from "react-router";
import { useEventCategoryManager } from "../../../../../services/Services";
import {
  UIXThemeProvider,
  useUIXTheme,
  Breadcrumb,
  Alert,
  Button,
  InfoField,
  SystemInfo,
  BackToListButton,
  EditButton,
  DeleteButton,
  DetailPageIcon,
  DetailCard,
} from "../../../../../components/UIX";
import {
  CalendarDaysIcon,
  ChevronRightIcon,
  XMarkIcon,
  TrashIcon,
  PencilSquareIcon,
  ExclamationTriangleIcon,
  Cog6ToothIcon,
  ChartBarIcon,
  ClipboardDocumentIcon,
  InformationCircleIcon,
  ArrowLeftIcon,
  CheckCircleIcon,
  ClockIcon,
  UserIcon,
  GlobeAltIcon,
  DocumentTextIcon,
  TagIcon,
  HashtagIcon,
  CalendarIcon,
  HomeIcon,
} from "@heroicons/react/24/outline";

function SettingEventCategoryDetailPage() {
  return (
    <UIXThemeProvider>
      <SettingEventCategoryDetailPageContent />
    </UIXThemeProvider>
  );
}

function SettingEventCategoryDetailPageContent() {
  const { getThemeClasses } = useUIXTheme();
  const navigate = useNavigate();
  const { id } = useParams();
  const location = useLocation();
  const eventCategoryManager = useEventCategoryManager();

  // State management
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);
  const [successMessage, setSuccessMessage] = useState("");
  const [eventCategory, setEventCategory] = useState(null);

  const onUnauthorized = () => {
    navigate("/login?unauthorized=true");
  };

  // Fetch event category details
  const fetchEventCategoryDetail = async () => {
    try {
      setIsLoading(true);
      setError(null);

      const eventCategoryData =
        await eventCategoryManager.getEventCategoryDetail(id, onUnauthorized);

      setEventCategory(eventCategoryData);

      if (import.meta.env.DEV) {
      console.log(
        "EventCategoryDetailPage: Event category detail fetched successfully:",
        {
          id: eventCategoryData.id,
          name: eventCategoryData.name,
        },
      );
      }
    } catch (err) {
      if (import.meta.env.DEV) {
      console.error(
        "EventCategoryDetailPage: Failed to fetch event category detail:",
        err,
      );
      }
      setError(err.message || "Failed to load event category details");
    } finally {
      setIsLoading(false);
    }
  };

  // Handle delete
  const handleDelete = () => {
    navigate(`/admin/settings/event-categories/${id}/delete`);
  };

  // Load data on component mount
  useEffect(() => {
    // Explicitly scroll to top when component mounts
    window.scrollTo(0, 0);

    if (id && typeof id === "string" && id.trim() !== "") {
      fetchEventCategoryDetail();
    } else {
      setError("Invalid event category ID");
      setIsLoading(false);
    }
  }, [id]);

  // Handle success message from navigation state
  useEffect(() => {
    if (location.state?.successMessage) {
      setSuccessMessage(location.state.successMessage);
      // Clear the state
      window.history.replaceState({}, document.title);
      // Clear success message after 3 seconds
      setTimeout(() => setSuccessMessage(""), 3000);
    }
  }, [location]);

  // Clear success message after 3 seconds
  useEffect(() => {
    if (successMessage) {
      const timer = setTimeout(() => setSuccessMessage(""), 3000);
      return () => clearTimeout(timer);
    }
  }, [successMessage]);

  // Loading state
  if (isLoading) {
    return (
      <div
        className={`min-h-screen bg-gradient-to-br from-gray-50 via-white ${getThemeClasses("bg-gradient-primary")} flex items-center justify-center`}
      >
        <div className="text-center">
          <div
            className={`animate-spin rounded-full h-12 w-12 border-b-2 ${getThemeClasses("border-primary")} mx-auto`}
          ></div>
          <p className="mt-4 text-gray-600">
            Loading event category details...
          </p>
        </div>
      </div>
    );
  }

  // Error state (no data loaded)
  if (error && !eventCategory) {
    return (
      <div
        className={`min-h-screen bg-gradient-to-br from-gray-50 via-white ${getThemeClasses("bg-gradient-primary")} p-8`}
      >
        <div className="max-w-2xl mx-auto">
          <Alert type="error" message={error} className="mb-6" />
          <div className="text-center">
            <Button
              variant="secondary"
              onClick={() => navigate("/admin/settings/event-categories")}
              icon={ArrowLeftIcon}
            >
              Back to Event Categories
            </Button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div
      className={`min-h-screen bg-gradient-to-br from-gray-50 via-white ${getThemeClasses("bg-gradient-primary")}`}
    >
      <div className="relative max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-6 sm:py-8 lg:py-12">
        {/* Breadcrumb */}
        <Breadcrumb
          items={[
            {
              label: "Dashboard",
              to: "/admin/dashboard",
              icon: HomeIcon,
            },
            {
              label: "Settings",
              to: "/admin/settings",
              icon: Cog6ToothIcon,
            },
            {
              label: "Event Categories",
              to: "/admin/settings/event-categories",
              icon: CalendarDaysIcon,
            },
            {
              label: "Event Category Details",
              icon: InformationCircleIcon,
              isActive: true,
            },
          ]}
        />

        {/* Header Section */}
        <div className="mb-8 sm:mb-10 max-w-4xl mx-auto">
          <div className="flex flex-col space-y-4 lg:flex-row lg:items-start lg:justify-between lg:space-y-0">
            <div className="flex-1 min-w-0">
              <div className="flex items-center justify-center lg:justify-start">
                <div className="flex items-start">
                  <DetailPageIcon icon={CalendarDaysIcon} />
                  <div className="text-center lg:text-left">
                    <h1 className="text-2xl sm:text-3xl lg:text-4xl font-bold text-gray-800 leading-tight">
                      {eventCategory?.name || "Event Category Details"}
                    </h1>
                    <p className="mt-2 text-base sm:text-lg text-gray-600 max-w-2xl">
                      Event category information and configuration details
                    </p>
                  </div>
                </div>
              </div>
            </div>
            <div className="flex-shrink-0 flex space-x-3">
              <BackToListButton
                onClick={() => navigate("/admin/settings/event-categories")}
              />
              <EditButton
                onClick={() =>
                  navigate(`/admin/settings/event-categories/${id}/update`)
                }
              />
              <DeleteButton onClick={handleDelete} />
            </div>
          </div>
        </div>

        {/* Success/Error Messages */}
        {successMessage && (
          <Alert
            type="success"
            message={successMessage}
            onClose={() => setSuccessMessage("")}
            className="mb-6 max-w-4xl mx-auto"
          />
        )}

        {error && (
          <Alert
            type="error"
            message={error}
            onClose={() => setError(null)}
            className="mb-6 max-w-4xl mx-auto"
          />
        )}

        {/* Main Content */}
        {eventCategory && (
          <div className="max-w-4xl mx-auto space-y-6">
            {/* Basic Information */}
            <DetailCard title="Basic Information" icon={InformationCircleIcon}>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <InfoField
                  label="Name"
                  value={eventCategory.name}
                  icon={TagIcon}
                />
                <InfoField
                  label="Status"
                  value={eventCategory.status === 1 ? "Active" : "Inactive"}
                  icon={CheckCircleIcon}
                  badge={true}
                  badgeColor={eventCategory.status === 1 ? "green" : "red"}
                />
                <InfoField
                  label="Description"
                  value={eventCategory.description || "No description provided"}
                  icon={DocumentTextIcon}
                  className="md:col-span-2"
                />
              </div>
            </DetailCard>

            {/* System Information */}
            <SystemInfo
              createdAt={eventCategory.createdAt}
              createdByUserName={eventCategory.createdByUserName}
              createdFromIpAddress={eventCategory.createdFromIpAddress}
              modifiedAt={eventCategory.modifiedAt}
              modifiedByUserName={eventCategory.modifiedByUserName}
              modifiedFromIpAddress={eventCategory.modifiedFromIpAddress}
            />
          </div>
        )}
      </div>
    </div>
  );
}

export default SettingEventCategoryDetailPage;
