// File Path: monorepo/web/frontend/src/pages/Admin/Setting/HowHearAboutUsItem/Delete/Page.jsx
import React, { useState, useEffect } from "react";
import { Link, useNavigate, useParams } from "react-router";
import { useHowHearAboutUsItemManager } from "../../../../../services/Services";
import {
  Breadcrumb,
  DeleteConfirmationCard,
  Alert,
  DetailPageIcon,
} from "../../../../../components/UIX";
import {
  MegaphoneIcon,
  TrashIcon,
  ExclamationTriangleIcon,
  Cog6ToothIcon,
  ChartBarIcon,
  ClipboardDocumentIcon,
  ArrowLeftIcon,
  DocumentTextIcon,
  HomeIcon,
} from "@heroicons/react/24/outline";

function SettingHowHearAboutUsItemDeletePage() {
  const navigate = useNavigate();
  const { id } = useParams();
  const howHearAboutUsItemManager = useHowHearAboutUsItemManager();

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

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

  // Fetch how hear about us item details
  const fetchData = async () => {
    try {
      setIsLoading(true);
      setError(null);

      const result = await howHearAboutUsItemManager.getDetail(
        id,
        onUnauthorized,
        true, // Force refresh
      );

      // Check if item is locked (Other)
      if (result.text === "Other") {
        setError("This item is system-protected and cannot be deleted.");
        setTimeout(() => {
          navigate(`/admin/settings/how-hear-about-us-item/${id}/detail`);
        }, 3000);
        return;
      }

      setData(result);
    } catch (err) {
      if (import.meta.env.DEV) {
      console.error("Failed to fetch How Hear About Us Item:", err);
      setError(err.message || "Failed to load data");
      }
    } finally {
      setIsLoading(false);
    }
  };

  // Handle delete confirmation
  const handleDelete = async () => {
    if (!data) return;

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

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

      await howHearAboutUsItemManager.delete(id, onUnauthorized);

      setSuccessMessage("How Hear About Us Item deleted successfully");

      // Navigate back to list with success message
      setTimeout(() => {
        navigate("/admin/settings/how-hear-about-us-items", {
          state: {
            successMessage: "How Hear About Us Item deleted successfully",
          },
        });
      }, 2000);
    } catch (err) {
      if (import.meta.env.DEV) {
      console.error("Failed to delete item:", err);
      setError(err.message || "Failed to delete item");
      }
      setIsDeleting(false);
    }
  };

  // Handle cancel
  const handleCancel = () => {
    navigate(`/admin/settings/how-hear-about-us-item/${id}/detail`);
  };

  // Load data on component mount
  useEffect(() => {
    if (id) {
      fetchData();
    } else {
      setError("Invalid item ID");
      setIsLoading(false);
    }
  }, [id]);

  // Auto-clear error messages
  useEffect(() => {
    if (error && data) {
      const timer = setTimeout(() => setError(null), 5000);
      return () => clearTimeout(timer);
    }
  }, [error, data]);

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

  // Error state (no data loaded)
  if (error && !data) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-gray-50 via-white to-red-50 p-8">
        <div className="max-w-2xl mx-auto">
          <div className="bg-red-50 border border-red-200 text-red-800 px-4 py-3 rounded-lg mb-4">
            <div className="flex items-center">
              <ExclamationTriangleIcon className="w-5 h-5 mr-2" />
              {error}
            </div>
          </div>
          <Link
            to="/admin/settings/how-hear-about-us-items"
            className="inline-flex items-center text-red-600 hover:text-red-800"
          >
            <ArrowLeftIcon className="w-4 h-4 mr-2" />
            Back to How Hear About Us Items
          </Link>
        </div>
      </div>
    );
  }

  // Not found state
  if (!data) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-gray-50 via-white to-red-50 p-8">
        <div className="max-w-2xl mx-auto">
          <div className="bg-amber-50 border border-amber-200 text-amber-800 px-4 py-3 rounded-lg mb-4">
            <div className="flex items-center">
              <ExclamationTriangleIcon className="w-5 h-5 mr-2" />
              How Hear About Us Item not found
            </div>
          </div>
          <Link
            to="/admin/settings/how-hear-about-us-items"
            className="inline-flex items-center text-red-600 hover:text-red-800"
          >
            <ArrowLeftIcon className="w-4 h-4 mr-2" />
            Back to How Hear About Us Items
          </Link>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-gray-50 via-white to-red-50">
      <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: "How Hear About Us Items",
              to: "/admin/settings/how-hear-about-us-items",
              icon: MegaphoneIcon,
            },
            {
              label: data?.text || "Item",
              to: `/admin/settings/how-hear-about-us-item/${id}/detail`,
              icon: ClipboardDocumentIcon,
            },
            {
              label: "Delete",
              icon: TrashIcon,
              isActive: true,
            },
          ]}
        />

        {/* Success Message */}
        {successMessage && (
          <Alert
            type="success"
            message={successMessage}
            onClose={() => setSuccessMessage("")}
            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 How Hear About Us Item
                    </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={data ? { ...data, name: data.text } : null}
          itemType="How Hear About Us Item"
          isDeleting={isDeleting}
          error={error}
          confirmText={confirmText}
          onConfirmTextChange={setConfirmText}
          onDelete={handleDelete}
          onCancel={handleCancel}
          onErrorClear={() => setError(null)}
          detailRoute={`/admin/settings/how-hear-about-us-item/${id}/detail`}
          editRoute={`/admin/settings/how-hear-about-us-item/${id}/update`}
          customFields={[
            {
              label: "Sort Number",
              value: data?.sortNumber ?? "N/A",
              className: "font-medium text-red-700",
            },
            {
              label: "Available for Roles",
              value: (() => {
                const roles = [];
                if (data?.isForFacilitator) roles.push("Facilitator");
                if (data?.isForCustomer) roles.push("Customer");
                if (data?.isForStaff) roles.push("Staff");
                return roles.length > 0 ? roles.join(", ") : "None";
              })(),
              className: "font-medium text-red-700",
            },
          ]}
          impactWarnings={[
            {
              icon: DocumentTextIcon,
              text: "Forms where this option is displayed to users",
            },
            {
              icon: ClipboardDocumentIcon,
              text: "Historical records that reference this option",
            },
            {
              icon: ChartBarIcon,
              text: "Reports and analytics that include this data",
            },
          ]}
          alternativeText="Consider updating the item 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="bg-white rounded-lg p-6 shadow-xl border-2 border-red-500">
              <div className="flex items-center space-x-4">
                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-red-600"></div>
                <div>
                  <p className="text-lg font-medium text-gray-900">
                    Deleting How Hear About Us Item...
                  </p>
                  <p className="text-sm text-gray-500">
                    Please wait while we remove this item from the system.
                  </p>
                </div>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

export default SettingHowHearAboutUsItemDeletePage;
