import { ReactNode, useEffect } from 'react';
import { createPortal } from 'react-dom';
import { X, LucideIcon, Sparkles } from 'lucide-react';

interface ModalProps {
  open: boolean;
  onClose: () => void;
  title: string;
  subtitle?: string;
  icon?: LucideIcon;
  watermarkIcon?: LucideIcon;
  children: ReactNode;
  footer?: ReactNode;
  maxWidth?: string;
  /** z-index override; default 150 per modals.md blueprint */
  zIndex?: number;
  bodyClassName?: string;
  contentClassName?: string;
  backdropClassName?: string;
}

export function Modal({
  open,
  onClose,
  title,
  subtitle,
  icon: Icon,
  watermarkIcon,
  children,
  footer,
  maxWidth = 'max-w-xl',
  zIndex = 150,
  bodyClassName,
  contentClassName = '',
  backdropClassName = '',
}: ModalProps) {
  useEffect(() => {
    if (!open) return;
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose();
    };
    window.addEventListener('keydown', onKey);
    // Lock background scroll while modal is open
    const prevOverflow = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => {
      window.removeEventListener('keydown', onKey);
      document.body.style.overflow = prevOverflow;
    };
  }, [open, onClose]);

  if (!open) return null;

  return createPortal(
    <div
      className={`fixed inset-0 bg-[#002147]/60 backdrop-blur-sm flex items-center justify-center p-4 sm:p-6 transition-all duration-200 ${backdropClassName}`}
      style={{ zIndex }}
      onClick={(e) => {
        if (e.target === e.currentTarget) onClose();
      }}
    >
      <div
        className={`bg-card rounded-[2.5rem] border border-border shadow-2xl w-full ${maxWidth} max-h-[90vh] flex flex-col overflow-hidden animate-in zoom-in-95 duration-200 ${contentClassName}`}
        role="dialog"
        aria-modal="true"
        aria-label={title}
      >
        <ModalHeader
          title={title}
          subtitle={subtitle}
          icon={Icon}
          watermarkIcon={watermarkIcon}
          onClose={onClose}
        />
        {bodyClassName !== undefined ? (
          <div className={`flex-1 min-h-0 overflow-y-auto ${bodyClassName}`}>{children}</div>
        ) : (
          <ModalBody>{children}</ModalBody>
        )}
        {footer && <ModalFooter>{footer}</ModalFooter>}
      </div>
    </div>,
    document.body
  );
}

interface ModalHeaderProps {
  title: string;
  icon?: LucideIcon;
  watermarkIcon?: LucideIcon;
  onClose: () => void;
  subtitle?: string;
}

export function ModalHeader({ title, icon: Icon, watermarkIcon: WatermarkIcon, onClose, subtitle }: ModalHeaderProps) {
  const DisplayWatermark = WatermarkIcon || Icon || Sparkles;

  return (
    <div className="px-8 sm:px-10 py-6 sm:py-8 bg-muted/50 border-b border-border flex justify-between items-center relative overflow-hidden flex-shrink-0">
      {/* Background Watermark Icon */}
      {DisplayWatermark && (
        <div className="absolute right-[-20px] top-[-20px] opacity-[0.03] rotate-12 pointer-events-none text-foreground select-none">
          <DisplayWatermark size={180} />
        </div>
      )}

      {/* Header Title & Subtitle */}
      <div className="flex items-center gap-3.5 min-w-0 relative z-10">
        {Icon && (
          <div className="flex-shrink-0 w-11 h-11 rounded-2xl bg-primary/10 text-primary border border-primary/20 flex items-center justify-center shadow-sm">
            <Icon className="w-5 h-5" />
          </div>
        )}
        <div className="min-w-0">
          <h2 className="text-xl sm:text-2xl font-black text-foreground tracking-tight font-heading break-words leading-tight">{title}</h2>
          {subtitle && (
            <p className="text-xs font-bold text-muted-foreground uppercase tracking-widest mt-1 break-words">{subtitle}</p>
          )}
        </div>
      </div>

      {/* Standardized Close Button */}
      <button
        type="button"
        onClick={onClose}
        className="relative z-10 w-10 h-10 flex-shrink-0 flex items-center justify-center rounded-xl bg-card border border-border text-muted-foreground hover:text-rose-500 hover:border-rose-500/20 hover:bg-rose-50/5 transition-all"
        aria-label="Close"
      >
        <X className="w-5 h-5" />
      </button>
    </div>
  );
}

export function ModalBody({ children, className = '' }: { children: ReactNode; className?: string }) {
  return <div className={`p-8 sm:p-10 space-y-6 overflow-y-auto flex-1 min-h-0 ${className}`}>{children}</div>;
}

export function ModalFooter({ children }: { children: ReactNode }) {
  return (
    <div className="px-8 sm:px-10 py-6 border-t border-border bg-muted/50 flex flex-wrap items-center justify-end gap-3 flex-shrink-0">
      {children}
    </div>
  );
}

export default Modal;
