// File Path: monorepo/web/frontend/src/pages/Admin/Setting/Bulletin/Delete/Page.jsx

import React, { useState, useEffect, useMemo, useCallback, memo } from "react";
import { Link, useNavigate, useParams } from "react-router";
import { useBulletinManager } from "../../../../../services/Services";
import {
  Breadcrumb,
  DeleteConfirmationCard,
  Alert,
  DetailPageIcon,
  UIXThemeProvider,
  useUIXTheme,
} from "../../../../../components/UIX";
import {
  NewspaperIcon,
  ChevronRightIcon,
  XMarkIcon,
  TrashIcon,
  ExclamationTriangleIcon,
  PencilSquareIcon,
  Cog6ToothIcon,
  ChartBarIcon,
  ClipboardDocumentIcon,
  InformationCircleIcon,
  ArrowLeftIcon,
  LockClosedIcon,
  ShieldExclamationIcon,
  DocumentTextIcon,
  ClockIcon,
  UserIcon,
  HomeIcon,
} from "@heroicons/react/24/outline";

// Move static configuration outside component to prevent recreation
const IMPACT_WARNINGS = [
  {
    icon: NewspaperIcon,
    text: "Any users who have access to this bulletin will no longer see it",
  },
  {
    icon: DocumentTextIcon,
    text: "Historical records referencing this bulletin will still exist but may show as 'Deleted'",
  },
  {
    icon: InformationCircleIcon,
    text: "You will not be able to recover this bulletin once deleted",
  },
];

function SettingBulletinDeletePage() {
  return (
    <UIXThemeProvider>
      <SettingBulletinDeletePageContent />
    </UIXThemeProvider>
  );
}

const SettingBulletinDeletePageContent = memo(
  function SettingBulletinDeletePageContent() {
    const { getThemeClasses } = useUIXTheme();
    const { id } = useParams();
    const bulletinManager = useBulletinManager();
    const navigate = useNavigate();

    const [errors, setErrors] = useState({});
    const [isLoading, setIsLoading] = useState(false);
    const [isFetching, setIsFetching] = useState(false);
    const [bulletin, setBulletin] = useState(null);
    const [confirmText, setConfirmText] = useState("");

    // Memoize theme classes
    const themeClasses = useMemo(
      () => ({
        bgGradientPrimary: getThemeClasses("bg-gradient-primary"),
        loadingSpinner: getThemeClasses("loading-spinner"),
        focusRing: getThemeClasses("focus-ring"),
        textMuted: getThemeClasses("text-muted"),
        errorText: getThemeClasses("text-error"),
        errorBg: getThemeClasses("bg-error-light"),
        errorBorder: getThemeClasses("border-error"),
      }),
      [getThemeClasses],
    );

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

    const fetchBulletinDetail = useCallback(
      async (bulletinId) => {
        setIsFetching(true);
        setErrors({});

        try {
          const bulletinData = await bulletinManager.getBulletinDetail(
            bulletinId,
            onUnauthorized,
          );

          setBulletin(bulletinData);

          if (import.meta.env.DEV) {
          console.log(
            "BulletinDeletePage: Bulletin detail loaded for deletion:",
            {
              id: bulletinData.id,
              text: bulletinData.text,
            },
          );
          }
        } catch (error) {
          if (import.meta.env.DEV) {
          console.error(
            "BulletinDeletePage: Failed to fetch bulletin detail:",
            error,
          );
          }
          setErrors({
            fetch: error.message || "Failed to load bulletin details",
          });
          window.scrollTo(0, 0);
        } finally {
          setIsFetching(false);
        }
      },
      [bulletinManager, onUnauthorized],
    );

    const handleDeleteConfirm = useCallback(async () => {
      if (!bulletin) return;

      // Require confirmation text
      if (confirmText !== bulletin.text) {
        setErrors({
          confirm: `Please type "${bulletin.text}" exactly to confirm`,
        });
        return;
      }

      setIsLoading(true);
      setErrors({});

      try {
        await bulletinManager.deleteBulletin(id, onUnauthorized);

        if (import.meta.env.DEV) {
        console.log("BulletinDeletePage: Bulletin deleted successfully");

        // Redirect after successful deletion
        navigate("/admin/settings/bulletins");
        }
      } catch (error) {
        if (import.meta.env.DEV) {
        console.error("BulletinDeletePage: Failed to delete bulletin:", error);
        setErrors({ delete: error.message || "Failed to delete bulletin" });
        }
        window.scrollTo(0, 0);
      } finally {
        setIsLoading(false);
      }
    }, [bulletin, confirmText, bulletinManager, id, navigate, onUnauthorized]);

    const handleCancel = useCallback(() => {
      navigate(`/admin/settings/bulletin/${id}/detail`);
    }, [navigate, id]);

    const handleErrorClear = useCallback(() => {
      setErrors({});
    }, []);

    useEffect(() => {
      let mounted = true;

      if (mounted) {
        window.scrollTo(0, 0);

        if (!id || typeof id !== "string" || id.trim() === "") {
          setErrors({ bulletinId: "Invalid bulletin ID" });
          return;
        }

        fetchBulletinDetail(id);
      }

      return () => {
        mounted = false;
      };
    }, [id, fetchBulletinDetail]);

    if (isFetching) {
      return (
        <div
          className={`min-h-screen ${themeClasses.bgGradientPrimary} flex items-center justify-center`}
        >
          <div className="text-center">
            <div
              className={`animate-spin rounded-full h-12 w-12 border-b-2 ${themeClasses.loadingSpinner} mx-auto`}
            ></div>
            <p className={`mt-4 ${themeClasses.textMuted}`}>
              Loading Bulletin for Deletion...
            </p>
          </div>
        </div>
      );
    }

    // Error state
    if ((errors.fetch || errors.bulletinId) && !bulletin) {
      return (
        <div className={`min-h-screen ${themeClasses.bgGradientPrimary} p-8`}>
          <div className="max-w-2xl mx-auto">
            <div
              className={`${themeClasses.errorBg} border ${themeClasses.errorBorder} ${themeClasses.errorText} px-4 py-3 rounded-lg mb-4`}
            >
              {errors.fetch || errors.bulletinId}
            </div>
            <Link
              to="/admin/settings/bulletins"
              className={`inline-flex items-center ${themeClasses.errorText}`}
            >
              <ArrowLeftIcon className="w-4 h-4 mr-2" />
              Back to Bulletins
            </Link>
          </div>
        </div>
      );
    }

    return (
      <div className={`min-h-screen ${themeClasses.bgGradientPrimary}`}>
        <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: "Bulletins",
                to: "/admin/settings/bulletins",
                icon: NewspaperIcon,
              },
              {
                label: bulletin?.text || "Detail",
                to: `/admin/settings/bulletin/${id}/detail`,
                icon: ClipboardDocumentIcon,
              },
              {
                label: "Delete",
                icon: TrashIcon,
                isActive: true,
              },
            ]}
          />

          {/* 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 Bulletin
                      </h1>
                      <p
                        className={`mt-2 text-base sm:text-lg lg:text-xl ${themeClasses.errorText} 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 ${themeClasses.focusRing} 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={bulletin ? { ...bulletin, name: bulletin.text } : null}
            itemType="Bulletin"
            isDeleting={isLoading}
            error={errors.delete || errors.confirm}
            confirmText={confirmText}
            onConfirmTextChange={setConfirmText}
            onDelete={handleDeleteConfirm}
            onCancel={handleCancel}
            onErrorClear={handleErrorClear}
            detailRoute={`/admin/settings/bulletin/${id}/detail`}
            editRoute={`/admin/settings/bulletin/${id}/update`}
            impactWarnings={IMPACT_WARNINGS}
            alternativeText="Consider setting the bulletin to 'Inactive' instead of deleting it to preserve historical data."
          />

          {/* Loading Overlay */}
          {isLoading && (
            <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 ${themeClasses.loadingSpinner}`}
                  ></div>
                  <div>
                    <p className="text-lg font-medium text-gray-900">
                      Deleting Bulletin...
                    </p>
                    <p className={`text-sm ${themeClasses.textMuted}`}>
                      Please wait while we remove this item from the system.
                    </p>
                  </div>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
    );
  },
);
SettingBulletinDeletePageContent.displayName =
  "SettingBulletinDeletePageContent";

export default SettingBulletinDeletePage;
