"use client";

import { useEffect, useRef, type ReactNode } from "react";
import { createPortal } from "react-dom";
import { X } from "lucide-react";

interface AppModalProps {
  isOpen: boolean;
  onClose: () => void;
  children: ReactNode;
  zIndexClassName?: string;
  panelClassName?: string;
  closeOnOverlay?: boolean;
  lockBodyScroll?: boolean;
}

export function AppModal({
  isOpen,
  onClose,
  children,
  zIndexClassName = "z-[220]",
  panelClassName = "w-full max-w-2xl rounded-2xl border border-white/10 bg-[#171821]/95 shadow-[0_24px_80px_rgba(0,0,0,0.55)] overflow-hidden",
  closeOnOverlay = true,
  lockBodyScroll = true,
}: AppModalProps) {
  const containerRef = useRef<HTMLDivElement | null>(null);

  useEffect(() => {
    if (!isOpen) return;

    const handleEsc = (event: KeyboardEvent) => {
      if (event.key === "Escape") onClose();
    };

    const previousActiveElement = document.activeElement as HTMLElement | null;

    if (lockBodyScroll) {
      const openCount = Number(document.body.dataset.appModalOpenCount ?? "0");
      if (openCount === 0) {
        document.body.dataset.appModalPrevOverflow = document.body.style.overflow;
        document.body.style.overflow = "hidden";
      }
      document.body.dataset.appModalOpenCount = String(openCount + 1);
    }

    document.addEventListener("keydown", handleEsc);
    requestAnimationFrame(() => containerRef.current?.focus());

    return () => {
      document.removeEventListener("keydown", handleEsc);

      if (lockBodyScroll) {
        const openCount = Number(document.body.dataset.appModalOpenCount ?? "0");
        const nextCount = Math.max(0, openCount - 1);

        if (nextCount === 0) {
          document.body.style.overflow = document.body.dataset.appModalPrevOverflow ?? "";
          delete document.body.dataset.appModalPrevOverflow;
          delete document.body.dataset.appModalOpenCount;
        } else {
          document.body.dataset.appModalOpenCount = String(nextCount);
        }
      }

      previousActiveElement?.focus?.();
    };
  }, [isOpen, lockBodyScroll, onClose]);

  if (!isOpen || typeof document === "undefined") return null;

  return createPortal(
    <div
      ref={containerRef}
      role="dialog"
      aria-modal="true"
      tabIndex={-1}
      className={`fixed inset-0 ${zIndexClassName} flex items-center justify-center bg-black/80 backdrop-blur-sm p-4 animate-in fade-in duration-200`}
      onClick={closeOnOverlay ? onClose : undefined}
    >
      <div className={panelClassName} onClick={(event) => event.stopPropagation()}>
        {children}
      </div>
    </div>,
    document.body
  );
}

interface AppModalHeaderProps {
  title: ReactNode;
  subtitle?: ReactNode;
  icon?: ReactNode;
  onClose?: () => void;
  actions?: ReactNode;
}

export function AppModalHeader({
  title,
  subtitle,
  icon,
  onClose,
  actions,
}: AppModalHeaderProps) {
  return (
    <div className="flex items-center justify-between gap-3 border-b border-white/10 bg-gradient-to-r from-white/[0.08] via-white/[0.03] to-white/[0.08] px-4 py-3">
      <div className="min-w-0 flex items-center gap-3">
        {icon ? (
          <div className="h-9 w-9 rounded-lg bg-white/10 text-white flex items-center justify-center">
            {icon}
          </div>
        ) : null}
        <div className="min-w-0">
          <h3 className="truncate text-base font-semibold text-white">{title}</h3>
          {subtitle ? <p className="mt-0.5 text-xs text-gray-400">{subtitle}</p> : null}
        </div>
      </div>

      <div className="flex items-center gap-2">
        {actions}
        {onClose ? (
          <button
            type="button"
            onClick={onClose}
            aria-label="关闭弹窗"
            className="p-2 text-gray-400 hover:text-white hover:bg-white/10 rounded-lg transition-colors"
          >
            <X className="h-5 w-5" />
          </button>
        ) : null}
      </div>
    </div>
  );
}
