// File Path: web/frontend/src/components/UI/Modal.jsx

import React, { useEffect, useCallback, useRef } from "react";
import { XMarkIcon } from "@heroicons/react/24/outline";
import { useUIXTheme } from "../themes/useUIXTheme.jsx";

// Track active modals globally to handle body overflow correctly
let activeModalsCount = 0;
let originalBodyOverflow = null;

function Modal({ isOpen, onClose, title, children, footer }) {
  const { getThemeClasses } = useUIXTheme();
  const modalIdRef = useRef(null);
  const previousIsOpenRef = useRef(false);

  // Handle backdrop click
  const handleBackdropClick = useCallback(
    (e) => {
      // Only close if clicking directly on backdrop, not its children
      if (e.target === e.currentTarget) {
        onClose();
      }
    },
    [onClose],
  );

  // Handle ESC key press
  const handleEscKey = useCallback(
    (e) => {
      // Check for ESC key (27 or 'Escape')
      if (e.key === "Escape" || e.keyCode === 27) {
        e.stopPropagation(); // Prevent event bubbling to other modals
        onClose();
      }
    },
    [onClose],
  );

  useEffect(() => {
    // Track previous state to detect transitions
    const wasOpen = previousIsOpenRef.current;
    previousIsOpenRef.current = isOpen;

    if (isOpen && !wasOpen) {
      // Modal is opening
      modalIdRef.current = Date.now() + Math.random(); // Unique ID for this modal instance

      // Handle body overflow
      if (activeModalsCount === 0) {
        // First modal being opened - store original overflow
        originalBodyOverflow = document.body.style.overflow;
        document.body.style.overflow = "hidden";
      }
      activeModalsCount++;

      // Add ESC key listener with capture phase to ensure it fires first
      document.addEventListener("keydown", handleEscKey, true);
    } else if (!isOpen && wasOpen) {
      // Modal is closing
      activeModalsCount = Math.max(0, activeModalsCount - 1);

      // Restore body overflow only when last modal closes
      if (activeModalsCount === 0 && originalBodyOverflow !== null) {
        document.body.style.overflow = originalBodyOverflow;
        originalBodyOverflow = null;
      }

      // Remove ESC key listener
      document.removeEventListener("keydown", handleEscKey, true);
    }

    // Cleanup function
    return () => {
      // Only cleanup if this modal is currently open
      if (isOpen) {
        activeModalsCount = Math.max(0, activeModalsCount - 1);

        // Restore body overflow if this was the last modal
        if (activeModalsCount === 0 && originalBodyOverflow !== null) {
          document.body.style.overflow = originalBodyOverflow;
          originalBodyOverflow = null;
        }

        // Remove event listener
        document.removeEventListener("keydown", handleEscKey, true);
      }
    };
  }, [isOpen, handleEscKey]);

  // Portal cleanup on unmount
  useEffect(() => {
    return () => {
      // Emergency cleanup if component unmounts while open
      if (previousIsOpenRef.current) {
        activeModalsCount = Math.max(0, activeModalsCount - 1);
        if (activeModalsCount === 0 && originalBodyOverflow !== null) {
          document.body.style.overflow = originalBodyOverflow;
          originalBodyOverflow = null;
        }
      }
    };
  }, []);

  if (!isOpen) return null;

  return (
    <div
      className="fixed inset-0 z-[9999] overflow-y-auto"
      role="dialog"
      aria-modal="true"
      aria-labelledby={title ? "modal-title" : undefined}
    >
      <div className="flex min-h-screen items-center justify-center p-4">
        {/* Backdrop */}
        <div
          className="fixed inset-0 bg-black/50 transition-opacity"
          onClick={handleBackdropClick}
          aria-hidden="true"
        />

        {/* Modal Panel */}
        <div
          className="relative transform overflow-hidden rounded-lg bg-white shadow-xl transition-all w-full max-w-lg border border-gray-200"
          role="document"
        >
          {/* Header */}
          {title && (
            <div
              className="px-6 py-4 border-b border-gray-200 bg-gray-50"
            >
              <div className="flex items-center justify-between">
                <h3
                  id="modal-title"
                  className="text-lg font-semibold text-gray-900"
                >
                  {title}
                </h3>
                <button
                  type="button"
                  onClick={onClose}
                  className="rounded-md bg-white text-gray-400 hover:text-gray-500 focus:outline-none focus:ring-2 focus:ring-indigo-500 p-1"
                  aria-label="Close modal"
                >
                  <XMarkIcon
                    className="h-6 w-6"
                  />
                </button>
              </div>
            </div>
          )}

          {/* Body */}
          <div className="bg-white text-gray-700 px-6 py-4">
            {children}
          </div>

          {/* Footer */}
          {footer && (
            <div
              className="bg-gray-50 px-6 py-3 border-t border-gray-200"
            >
              {footer}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

// Reset function for development/debugging
if (typeof window !== "undefined" && process.env.NODE_ENV === "development") {
  window.__resetModalState = () => {
    activeModalsCount = 0;
    if (originalBodyOverflow !== null) {
      document.body.style.overflow = originalBodyOverflow;
      originalBodyOverflow = null;
    }
  };
}

export default Modal;
