// File Path: monorepo/web/frontend/src/pages/Admin/Division/Detail/More/Delete/Page.jsx

import React, { useState, useEffect, memo, useCallback } from "react";
import { useNavigate, useParams } from "react-router";
import { useDivisionManager } from "../../../../../../services/Services";
import {
  UIXThemeProvider,
  Breadcrumb,
  Alert,
  DeleteConfirmationCard,
  DetailPageIcon,
  useUIXTheme,
} from "../../../../../../components/UIX";
import {
  BuildingOffice2Icon,
  TrashIcon,
  ChartBarIcon,
  InformationCircleIcon,
  ArrowLeftIcon,
  HomeIcon,
  EllipsisHorizontalIcon,
  UserGroupIcon,
  DocumentTextIcon,
  CalendarIcon,
  TagIcon,
} from "@heroicons/react/24/outline";
import { DIVISION_STATUS_ARCHIVED } from "../../../../../../constants/Division";

function AdminDivisionDetailMoreDeletePage() {
  return (
    <UIXThemeProvider>
      <AdminDivisionDetailMoreDeletePageContent />
    </UIXThemeProvider>
  );
}

const AdminDivisionDetailMoreDeletePageContent = memo(
  function AdminDivisionDetailMoreDeletePageContent() {
    const navigate = useNavigate();
    const { id } = useParams();
    const divisionManager = useDivisionManager();
    const { getThemeClasses } = useUIXTheme();

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

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

    // Fetch division details
    const fetchDivisionDetail = useCallback(async () => {
      try {
        setIsLoading(true);
        setError(null);

        const divisionData = await divisionManager.getDivisionDetail(
          id,
          onUnauthorized,
        );

        // Check if division can be deleted (must be archived first)
        if (divisionData.status !== DIVISION_STATUS_ARCHIVED) {
          setError(
            "This division cannot be deleted. Only archived divisions can be permanently deleted. Please archive the division first.",
          );
        }

        setDivision(divisionData);
      } catch (err) {
        if (process.env.NODE_ENV === 'development') {
          console.error("Failed to fetch division:", err);
        }
        setError(err.message || "Failed to load division details");
      } finally {
        setIsLoading(false);
      }
    }, [id, divisionManager, onUnauthorized]);

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

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

      // Check if division is archived
      if (division.status !== DIVISION_STATUS_ARCHIVED) {
        setError("Only archived divisions can be deleted");
        return;
      }

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

        await divisionManager.deleteDivision(division.id, onUnauthorized);

        setSuccessMessage("Division deleted successfully!");

        // Navigate to list page with success message
        setTimeout(() => {
          navigate("/admin/divisions", {
            state: {
              successMessage: "Division deleted successfully",
            },
          });
        }, 1500);
      } catch (err) {
        if (process.env.NODE_ENV === 'development') {
          console.error("Failed to delete division:", err);
        }
        setError(err.message || "Failed to delete division");
        setIsDeleting(false);
      }
    }, [division, confirmText, divisionManager, onUnauthorized, navigate]);

    // Handle cancel
    const handleCancel = useCallback(() => {
      navigate(`/admin/division/${id}/more`);
    }, [id, navigate]);

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

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

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

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

    // Error state
    if (error && !division) {
      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>
            <button
              onClick={() => navigate("/admin/divisions")}
              className={`inline-flex items-center ${getThemeClasses("text-error")} ${getThemeClasses("hover:text-error-dark")}`}
            >
              <ArrowLeftIcon className="w-4 h-4 mr-2" />
              Back to Divisions
            </button>
          </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: "Divisions",
                to: "/admin/divisions",
                icon: BuildingOffice2Icon,
              },
              {
                label: division?.divisionName || "Division",
                to: `/admin/division/${id}`,
                icon: InformationCircleIcon,
              },
              {
                label: "More",
                to: `/admin/division/${id}/more`,
                icon: EllipsisHorizontalIcon,
              },
              {
                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 */}
          <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 ${getThemeClasses("text-primary")} leading-tight`}
                      >
                        Delete Division
                      </h1>
                      <p
                        className={`mt-2 text-base sm:text-lg lg:text-xl ${getThemeClasses("text-error")} 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 ${getThemeClasses("border-secondary")} rounded-xl shadow-sm text-sm sm:text-base font-medium ${getThemeClasses("text-secondary")} ${getThemeClasses("bg-card")} ${getThemeClasses("hover:bg-hover")} hover:shadow-md focus:outline-none focus:ring-2 focus:ring-offset-2 ${getThemeClasses("focus-ring")} transition-all duration-200`}
                >
                  <ArrowLeftIcon className="h-4 w-4 sm:h-5 sm:w-5 mr-2" />
                  Back to More Options
                </button>
              </div>
            </div>
          </div>

          {/* Delete Confirmation Card */}
          <DeleteConfirmationCard
            item={{
              ...division,
              name: division?.divisionName,
            }}
            itemType="Division"
            isDeleting={isDeleting}
            error={error}
            confirmText={confirmText}
            onConfirmTextChange={setConfirmText}
            onDelete={handleDelete}
            onCancel={handleCancel}
            onErrorClear={() => setError(null)}
            detailRoute={`/admin/division/${id}`}
            editRoute={`/admin/division/${id}/edit`}
            customFields={
              division?.organizationName
                ? [
                    {
                      label: "Parent Organization",
                      value: division.organizationName,
                      icon: BuildingOffice2Icon,
                      className: "font-medium text-gray-700",
                    },
                  ]
                : []
            }
            impactWarnings={[
              {
                icon: UserGroupIcon,
                text: "All contacts associated with this division",
              },
              {
                icon: DocumentTextIcon,
                text: "All comments and attachments related to this division",
              },
              {
                icon: CalendarIcon,
                text: "All event associations and historical event data",
              },
              {
                icon: TagIcon,
                text: "All custom configurations, settings, and metadata",
              },
              {
                icon: DocumentTextIcon,
                text: "Historical records and audit logs for this division",
              },
            ]}
            alternativeText="Consider archiving the division instead of deleting it to preserve historical data and maintain referential integrity."
            systemInfo={true}
          />
        </div>
      </div>
    );
  },
);

export default AdminDivisionDetailMoreDeletePage;
