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

const SettingSpecializationDeletePageContent = memo(
  function SettingSpecializationDeletePageContent() {
    const navigate = useNavigate();
    const { id } = useParams();
    const specializationManager = useSpecializationManager();
    const { getThemeClasses } = useUIXTheme();

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

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

    // Fetch specialization details
    const fetchSpecializationDetail = async () => {
      try {
        setIsLoading(true);
        setError(null);

        const specializationData =
          await specializationManager.getSpecializationDetail(
            id,
            onUnauthorized,
          );

        setSpecialization(specializationData);

        if (import.meta.env.DEV) {
        console.log(
          "SpecializationDeletePage: Specialization detail fetched successfully:",
          {
            id: specializationData.id,
            name: specializationData.name,
          },
        );
        }
      } catch (err) {
        if (import.meta.env.DEV) {
        console.error(
          "SpecializationDeletePage: Failed to fetch specialization detail:",
          err,
        );
        }
        setError(err.message || "Failed to load specialization details");
      } finally {
        setIsLoading(false);
      }
    };

    // Handle delete confirmation
    const handleDelete = async () => {
      if (!specialization || !specialization.id) {
        setError("No specialization selected for deletion");
        return;
      }

      // Validate confirmation text
      if (confirmText !== specialization.name) {
        setError(`Please type "${specialization.name}" exactly to confirm`);
        return;
      }

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

        await specializationManager.deleteSpecialization(
          specialization.id,
          onUnauthorized,
        );

        if (import.meta.env.DEV) {
        console.log(
          "SpecializationDeletePage: Specialization deleted successfully",
        );
        }
        setSuccessMessage("Specialization deleted successfully!");

        // Navigate to list page with success message
        setTimeout(() => {
          navigate("/admin/settings/specializations", {
            state: {
              successMessage: "Specialization deleted successfully",
            },
          });
        }, 1500);
      } catch (err) {
        if (import.meta.env.DEV) {
        console.error(
          "SpecializationDeletePage: Failed to delete specialization:",
          err,
        );
        }
        setError(err.message || "Failed to delete specialization");
        setIsDeleting(false);
      }
    };

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

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

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

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

    // Loading state
    if (isLoading && !specialization) {
      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 specialization details...
            </p>
          </div>
        </div>
      );
    }

    // Error state
    if (error && !specialization) {
      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/specializations"
              className={`inline-flex items-center ${getThemeClasses("text-error")} ${getThemeClasses("hover:text-error-dark")}`}
            >
              <ArrowLeftIcon className="w-4 h-4 mr-2" />
              Back to Specializations
            </Link>
          </div>
        </div>
      );
    }

    return (
      <div className={`min-h-screen ${getThemeClasses("bg-gradient-primary")}`}>
        <div className="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: "Specializations",
                to: "/admin/settings/specializations",
                icon: StarIcon,
              },
              {
                label: specialization?.name || "Details",
                to: `/admin/settings/specialization/${id}/detail`,
                icon: StarIcon,
              },
              {
                label: "Delete",
                icon: TrashIcon,
                isActive: true,
              },
            ]}
          />

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

          {error && (
            <Alert
              type="error"
              message={error}
              onClose={() => setError(null)}
              className="mb-6"
            />
          )}

          {/* Header Section - Enhanced with title and back button */}
          <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={TrashIcon} />
                    <div className="text-center lg:text-left">
                      <h1 className="text-2xl sm:text-3xl lg:text-4xl font-bold text-gray-800 leading-tight">
                        Delete Specialization
                      </h1>
                      <p className="mt-2 text-base sm:text-lg lg:text-xl text-red-600 font-medium">
                        Permanent deletion confirmation
                      </p>
                    </div>
                  </div>
                </div>
              </div>
              <div className="flex-shrink-0">
                <button
                  onClick={handleCancel}
                  className="inline-flex items-center px-5 py-3 border border-gray-200 rounded-xl shadow-sm text-sm sm:text-base font-medium text-gray-700 bg-white hover:bg-gray-50 hover:shadow-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 transition-all duration-200"
                >
                  <ArrowLeftIcon className="h-4 w-4 sm:h-5 sm:w-5 mr-2" />
                  Back to Detail
                </button>
              </div>
            </div>
          </div>

          {/* Delete Confirmation Card */}
          <DeleteConfirmationCard
            item={specialization}
            itemType="Specialization"
            isDeleting={isDeleting}
            error={error}
            confirmText={confirmText}
            onConfirmTextChange={setConfirmText}
            onDelete={handleDelete}
            onCancel={handleCancel}
            onErrorClear={() => setError(null)}
            detailRoute={`/admin/settings/specialization/${id}/detail`}
            editRoute={`/admin/settings/specialization/${id}/update`}
            customFields={[]}
            impactWarnings={[
              {
                icon: StarIcon,
                text: "Any facilitators currently assigned to this specialization",
              },
              {
                icon: DocumentTextIcon,
                text: "Historical records referencing this specialization will still exist but may show as 'Deleted'",
              },
              {
                icon: TagIcon,
                text: "Specialization requirements and validations that use this specialization",
              },
            ]}
            alternativeText="Consider marking the specialization as inactive instead of deleting it to preserve historical data."
          />

          {/* Loading Overlay */}
          {isDeleting && (
            <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
              <div
                className={`${getThemeClasses("bg-primary")} rounded-lg p-6 shadow-xl`}
              >
                <div className="flex items-center space-x-4">
                  <div
                    className={`animate-spin rounded-full h-8 w-8 border-b-2 ${getThemeClasses("loading-spinner")}`}
                  ></div>
                  <div>
                    <p
                      className={`text-lg font-medium ${getThemeClasses("text-primary")}`}
                    >
                      Deleting Specialization...
                    </p>
                    <p
                      className={`text-sm ${getThemeClasses("text-secondary")}`}
                    >
                      Please wait while we process your request.
                    </p>
                  </div>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
    );
  },
);

SettingSpecializationDeletePageContent.displayName =
  "SettingSpecializationDeletePageContent";

export default SettingSpecializationDeletePage;
