// File Path: monorepo/web/frontend/src/pages/Admin/Setting/EventCategory/Delete/Page.jsx
import React, { useState, useEffect } from "react";
import { Link, useNavigate, useParams } from "react-router";
import { useEventCategoryManager } from "../../../../../services/Services";
import {
  UIXThemeProvider,
  Breadcrumb,
  Alert,
  Button,
  DeleteConfirmationCard,
  useUIXTheme,
} from "../../../../../components/UIX";
import {
  CalendarDaysIcon,
  TrashIcon,
  ExclamationTriangleIcon,
  ArrowLeftIcon,
  Cog6ToothIcon,
  HomeIcon,
  InformationCircleIcon,
  ClockIcon,
} from "@heroicons/react/24/outline";

function SettingEventCategoryDeletePage() {
  return (
    <UIXThemeProvider>
      <SettingEventCategoryDeletePageContent />
    </UIXThemeProvider>
  );
}

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

  // State management
  const [isLoading, setIsLoading] = useState(true);
  const [isDeleting, setIsDeleting] = useState(false);
  const [error, setError] = useState(null);
  const [eventCategory, setEventCategory] = useState(null);
  const [confirmText, setConfirmText] = useState("");

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

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

      if (import.meta.env.DEV) {
        console.log("EventCategoryDeletePage: Starting fetch for ID:", id);
      }

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

      if (import.meta.env.DEV) {
        console.log(
          "EventCategoryDeletePage: Raw API response:",
          eventCategoryData,
        );
      }

      setEventCategory(eventCategoryData);

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

  // Handle delete confirmation
  const handleDeleteConfirm = async () => {
    if (!eventCategory) return;

    try {
      setIsDeleting(true);
      setError(null);

      await eventCategoryManager.deleteEventCategory(
        eventCategory.id,
        onUnauthorized,
      );

      if (import.meta.env.DEV) {
        console.log(
          "EventCategoryDeletePage: Event category deleted successfully",
        );
      }

      // Navigate to list with success message
      navigate("/admin/settings/event-categories?success=deleted");
    } catch (err) {
      if (import.meta.env.DEV) {
        console.error(
          "EventCategoryDeletePage: Failed to delete event category:",
          err,
        );
      }
      setError(err.message || "Failed to delete event category");
    } finally {
      setIsDeleting(false);
    }
  };

  // Handle cancel
  const handleCancel = () => {
    navigate(`/admin/settings/event-categories/${id}/detail`);
  };

  // Handle error clearing
  const handleErrorClear = () => {
    setError(null);
  };

  // Handle confirm text change
  const handleConfirmTextChange = (value) => {
    setConfirmText(value);
  };

  // Effects
  useEffect(() => {
    window.scrollTo(0, 0);

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

  // Loading state
  if (isLoading) {
    return (
      <div
        className={`min-h-screen ${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("loading-spinner")} mx-auto`}
          ></div>
          <p className={`mt-4 ${getThemeClasses("text-secondary")}`}>
            Loading event category details...
          </p>
        </div>
      </div>
    );
  }

  // Error state (no data loaded)
  if (error && !eventCategory) {
    return (
      <div
        className={`min-h-screen ${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 ${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: "Delete Event Category",
              icon: TrashIcon,
              isActive: true,
            },
          ]}
        />

        {/* DeleteConfirmationCard */}
        {eventCategory ? (
          <DeleteConfirmationCard
            item={eventCategory}
            itemType="Event Category"
            isDeleting={isDeleting}
            error={error}
            confirmText={confirmText}
            onConfirmTextChange={handleConfirmTextChange}
            onDelete={handleDeleteConfirm}
            onCancel={handleCancel}
            onErrorClear={handleErrorClear}
            detailRoute={`/admin/settings/event-categories/${id}/detail`}
            editRoute={`/admin/settings/event-categories/${id}/update`}
            impactWarnings={[
              {
                text: "Remove any associations with events that use this category",
                icon: InformationCircleIcon,
              },
              {
                text: "Make this category unavailable for future event classification",
                icon: ExclamationTriangleIcon,
              },
              {
                text: "All historical references to this category will be lost",
                icon: ClockIcon,
              },
            ]}
            alternativeText="Consider deactivating this category instead of deleting it to preserve historical event data"
            systemInfo={true}
            className="mb-8"
          />
        ) : (
          !isLoading && (
            <div className="max-w-2xl mx-auto">
              <div className="bg-white shadow-xl rounded-2xl p-8 text-center">
                <h3 className="text-lg font-medium text-gray-900 mb-2">
                  Event Category Not Found
                </h3>
                <p className="text-sm text-gray-500 mb-6">
                  The requested event category could not be found or loaded.
                </p>
                <Button
                  variant="secondary"
                  onClick={() => navigate("/admin/settings/event-categories")}
                  icon={ArrowLeftIcon}
                >
                  Back to Event Categories
                </Button>
              </div>
            </div>
          )
        )}
      </div>
    </div>
  );
}

export default SettingEventCategoryDeletePage;
