// File Path: monorepo/web/frontend/src/pages/Admin/Event/Virtual/Detail/Attachment/Delete/Page.jsx

import React, { useState, useEffect, useMemo, useCallback, memo, useRef } from "react";
import { useNavigate, useParams } from "react-router";
import {
  useAttachmentManager,
  useEventManager,
  useAuthManager,
} from "../../../../../../../services/Services";
import {
  UIXThemeProvider,
  Breadcrumb,
  DeleteConfirmationCard,
  Alert,
  useUIXTheme,
} from "../../../../../../../components/UIX";
import {
  HomeIcon,
  VideoCameraIcon,
  PaperClipIcon,
  DocumentTextIcon,
  TrashIcon,
} from "@heroicons/react/24/outline";

// Development-only logging
const DEBUG = process.env.NODE_ENV === 'development';
const log = (...args) => DEBUG && console.log(...args);
const error = (...args) => console.error(...args);

const AdminVirtualDetailAttachmentDeletePageContent = memo(function AdminVirtualDetailAttachmentDeletePageContent() {
  const navigate = useNavigate();
  const { vid, atid } = useParams();
  const attachmentManager = useAttachmentManager();
  const eventManager = useEventManager();
  const authManager = useAuthManager();
  const { getThemeClasses } = useUIXTheme();

  // State management
  const [isLoading, setIsLoading] = useState(true);
  const [isDeleting, setIsDeleting] = useState(false);
  const [errorState, setErrorState] = useState(null);
  const [successMessage, setSuccessMessage] = useState("");
  const [attachment, setAttachment] = useState(null);
  const [event, setEvent] = useState(null);
  const [confirmText, setConfirmText] = useState("");

  // Use refs to track component lifecycle
  const isMounted = useRef(true);
  const isFetchingRef = useRef(false);
  const abortControllerRef = useRef(null);

  // Reset isMounted on every render (handles React Strict Mode remounts)
  isMounted.current = true;

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

  // Cleanup on unmount
  useEffect(() => {
    return () => {
      isMounted.current = false;
      if (abortControllerRef.current) {
        abortControllerRef.current.abort();
      }
    };
  }, []);

  // Memoize theme classes
  const themeClasses = useMemo(() => ({
    borderPrimary: getThemeClasses('border-primary'),
    textSecondary: getThemeClasses('text-secondary'),
  }), [getThemeClasses]);

  // Fetch attachment and event details
  const fetchData = useCallback(async () => {
    // Cancel any ongoing request
    if (abortControllerRef.current) {
      abortControllerRef.current.abort();
    }
    abortControllerRef.current = new AbortController();

    try {
      setIsLoading(true);
      setErrorState(null);

      // Check authentication
      if (!authManager.isAuthenticated()) {
        navigate("/login");
        return;
      }

      // Fetch both attachment and event data
      const [attachmentData, eventData] = await Promise.all([
        attachmentManager.getAttachmentDetail(atid, onUnauthorized),
        eventManager.getEventDetail(vid, onUnauthorized),
      ]);

      if (isMounted.current) {
        setAttachment(attachmentData);
        setEvent(eventData);
      }
    } catch (err) {
      // Don't treat abort as an error
      if (err.name === "AbortError") {
        log("Request aborted");
        return;
      }

      error("Failed to fetch data:", err);
      if (isMounted.current) {
        setErrorState(err.message || "Failed to load attachment details");
      }
    } finally {
      if (isMounted.current) {
        setIsLoading(false);
      }
    }
  }, [vid, atid, attachmentManager, eventManager, authManager, onUnauthorized, navigate]);

  // Initial load effect
  useEffect(() => {
    // Skip if no IDs
    if (!vid || !atid) {
      log("No vid or atid, skipping load");
      return;
    }

    // Skip if currently fetching (prevents double-fetch in React Strict Mode)
    if (isFetchingRef.current) {
      log("Already fetching (ref check), skipping");
      return;
    }

    const loadInitialData = async () => {
      try {
        // Set ref immediately to prevent double-fetch
        isFetchingRef.current = true;

        await fetchData();
      } catch (err) {
        error("Error loading initial data:", err);
      } finally {
        if (isMounted.current) {
          isFetchingRef.current = false;
        }
      }
    };

    loadInitialData();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [vid, atid]);

  // Handle delete confirmation
  const handleDelete = useCallback(async () => {
    const expectedName = attachment?.title || attachment?.name || "Untitled Attachment";
    if (!attachment || confirmText !== expectedName) {
      setErrorState(`Please type '${expectedName}' to confirm deletion`);
      return;
    }

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

      await attachmentManager.deleteAttachment(atid, onUnauthorized);

      if (isMounted.current) {
        setSuccessMessage("Attachment deleted successfully");
      }

      // Redirect after short delay
      setTimeout(() => {
        if (isMounted.current) {
          navigate(`/admin/event/virtual/${vid}/attachments`);
        }
      }, 1500);
    } catch (err) {
      error("Failed to delete attachment:", err);
      if (isMounted.current) {
        setErrorState(err.message || "Failed to delete attachment. Please try again.");
      }
    } finally {
      if (isMounted.current) {
        setIsDeleting(false);
      }
    }
  }, [attachment, confirmText, atid, onUnauthorized, attachmentManager, navigate, vid]);

  const handleCancel = useCallback(() => {
    navigate(`/admin/event/virtual/${vid}/attachment/${atid}`);
  }, [navigate, vid, atid]);

  if (!authManager.isAuthenticated()) {
    return (
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <div className="flex items-center justify-center min-h-[400px]">
          <div className="text-center">
            <div className={`animate-spin rounded-full h-12 w-12 border-b-2 ${themeClasses.borderPrimary} mx-auto`}></div>
            <p className={`mt-4 ${themeClasses.textSecondary}`}>Checking authentication...</p>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      {/* Breadcrumb */}
      <Breadcrumb
        items={[
          {
            label: "Dashboard",
            to: "/admin/dashboard",
            icon: HomeIcon,
          },
          {
            label: "Events",
            to: "/admin/events",
            icon: VideoCameraIcon,
          },
          {
            label: "Virtual",
            to: "/admin/event/virtuals",
            icon: VideoCameraIcon,
          },
          {
            label: event ? `${event.title} (Attachments)` : "Detail (Attachments)",
            to: `/admin/event/virtual/${vid}/attachments`,
            icon: PaperClipIcon,
          },
          {
            label: attachment ? attachment.title || "Attachment" : "Attachment",
            to: `/admin/event/virtual/${vid}/attachment/${atid}`,
            icon: DocumentTextIcon,
          },
          {
            label: "Delete",
            icon: TrashIcon,
            isActive: true,
          },
        ]}
      />

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

      {/* Error Message */}
      {errorState && (
        <Alert
          type="error"
          message={errorState}
          onDismiss={() => setErrorState(null)}
          className="mb-6"
        />
      )}

      {/* Loading State */}
      {isLoading ? (
        <div className="flex items-center justify-center py-12">
          <div className="text-center">
            <div className={`animate-spin rounded-full h-10 w-10 border-b-2 ${themeClasses.borderPrimary} mx-auto`}></div>
            <p className={`mt-4 ${themeClasses.textSecondary}`}>Loading attachment details...</p>
          </div>
        </div>
      ) : attachment ? (
        <DeleteConfirmationCard
          item={{
            ...attachment,
            name: attachment.title || attachment.name || "Untitled Attachment"
          }}
          itemType="Attachment"
          isDeleting={isDeleting}
          error={errorState}
          confirmText={confirmText}
          onConfirmTextChange={setConfirmText}
          onDelete={handleDelete}
          onCancel={handleCancel}
          onErrorClear={() => setErrorState(null)}
        />
      ) : (
        <Alert
          type="error"
          message="Attachment not found"
          className="mb-6"
        />
      )}
    </div>
  );
});

function AdminVirtualDetailAttachmentDeletePage() {
  return (
    <UIXThemeProvider>
      <AdminVirtualDetailAttachmentDeletePageContent />
    </UIXThemeProvider>
  );
}

export default AdminVirtualDetailAttachmentDeletePage;
