// File Path: monorepo/web/frontend/src/pages/Admin/Setting/SkillCategory/Delete/Page.jsx
import React, { useState, useEffect } from "react";
import { Link, useNavigate, useParams } from "react-router";
import { useSkillCategoryManager } from "../../../../../services/Services";
import {
  UIXThemeProvider,
  Breadcrumb,
  Alert,
  Button,
  DeleteConfirmationCard,
  DetailPageIcon,
  useUIXTheme,
} from "../../../../../components/UIX";
import {
  AcademicCapIcon,
  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 SettingSkillCategoryDeletePage() {
  return (
    <UIXThemeProvider>
      <SettingSkillCategoryDeletePageContent />
    </UIXThemeProvider>
  );
}

function SettingSkillCategoryDeletePageContent() {
  const { getThemeClasses } = useUIXTheme();
  const navigate = useNavigate();
  const { id } = useParams();
  const skillCategoryManager = useSkillCategoryManager();

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

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

  // Fetch skill category details using real API
  const fetchSkillCategoryDetail = async () => {
    try {
      setIsLoading(true);
      setError(null);

      if (import.meta.env.DEV) {
        console.log(
          "SkillCategoryDeletePage: Fetching skill category detail for ID:",
          id,
        );
      }

      // Call the API via SkillCategoryManager
      const data = await skillCategoryManager.getSkillCategoryDetail(
        id,
        onUnauthorized,
      );

      if (import.meta.env.DEV) {
        console.log("SkillCategoryDeletePage: API response:", data);
      }

      if (data && data.id) {
        setSkillCategory(data);
        if (import.meta.env.DEV) {
          console.log(
            "SkillCategoryDeletePage: Skill category detail fetched successfully",
          );
        }
      } else {
        if (import.meta.env.DEV) {
          console.warn(
            "SkillCategoryDeletePage: Invalid response structure:",
            data,
          );
        }
        setError("Skill category not found");
      }
    } catch (err) {
      if (import.meta.env.DEV) {
        console.error(
          "SkillCategoryDeletePage: Failed to fetch skill category detail:",
          err,
        );
      }
      setError(err.message || "Failed to load skill category details");
    } finally {
      setIsLoading(false);
    }
  };

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

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

      if (import.meta.env.DEV) {
        console.log(
          "SkillCategoryDeletePage: Deleting skill category:",
          skillCategory.id,
        );
      }

      // Delete via SkillCategoryManager
      await skillCategoryManager.deleteSkillCategory(
        skillCategory.id,
        onUnauthorized,
      );

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

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

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

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

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

  // Load data on component mount
  useEffect(() => {
    window.scrollTo(0, 0);

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

  // Auto-clear success message
  useEffect(() => {
    if (successMessage) {
      const timer = setTimeout(() => setSuccessMessage(""), 5000);
      return () => clearTimeout(timer);
    }
  }, [successMessage]);

  // Loading state
  if (isLoading && !skillCategory) {
    return (
      <div
        className={`min-h-screen ${getThemeClasses("bg-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 skill category details...
          </p>
        </div>
      </div>
    );
  }

  // Error state
  if (error && !skillCategory) {
    return (
      <div className={`min-h-screen ${getThemeClasses("bg-primary")} p-8`}>
        <div className="max-w-2xl mx-auto">
          <div
            className={`${getThemeClasses("bg-error")} ${getThemeClasses("border-error")} ${getThemeClasses("text-error")} px-4 py-3 rounded-lg mb-4`}
          >
            {error}
          </div>
          <Link
            to="/admin/settings/skill-categories"
            className={`inline-flex items-center ${getThemeClasses("text-primary")} ${getThemeClasses("hover:text-primary-dark")}`}
          >
            <ArrowLeftIcon className="w-4 h-4 mr-2" />
            Back to Skill Categories
          </Link>
        </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: "Skill Categories",
              to: "/admin/settings/skill-categories",
              icon: AcademicCapIcon,
            },
            {
              label: skillCategory?.name || "Details",
              to: `/admin/settings/skill-category/${id}/detail`,
              icon: AcademicCapIcon,
            },
            {
              label: "Delete",
              icon: TrashIcon,
              isActive: true,
            },
          ]}
        />

        {/* Success Messages */}
        {successMessage && (
          <Alert
            type="success"
            message={successMessage}
            onClose={() => setSuccessMessage("")}
            className="mb-6"
          />
        )}

        {/* DeleteConfirmationCard */}
        <DeleteConfirmationCard
          item={skillCategory}
          itemType="Skill Category"
          isDeleting={isDeleting}
          error={error}
          confirmText={confirmText}
          onConfirmTextChange={handleConfirmTextChange}
          onDelete={handleDeleteConfirm}
          onCancel={handleCancel}
          onErrorClear={handleErrorClear}
          detailRoute={`/admin/settings/skill-category/${id}/detail`}
          editRoute={`/admin/settings/skill-category/${id}/update`}
          impactWarnings={[
            {
              text: "Remove any associations with skills or other entities that reference this category",
              icon: InformationCircleIcon,
            },
            {
              text: "Make this category unavailable for future use",
              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 data"
          systemInfo={true}
          className="mb-8"
        />
      </div>
    </div>
  );
}

export default SettingSkillCategoryDeletePage;
