import { useEffect, useRef } from 'react';
import { createPortal } from 'react-dom';
import { FocusTrap } from './focus-trap';
import { X } from 'lucide-react';
import { Button } from './button';
import { cn } from '@/lib/utils';

export interface ModalProps {
  open: boolean;
  onClose: () => void;
  children: React.ReactNode;
  title?: string;
  closeOnOverlayClick?: boolean;
  closeOnEscape?: boolean;
  size?: 'sm' | 'md' | 'lg' | 'xl' | 'full';
  className?: string;
  footer?: React.ReactNode;
}

const sizeClasses = {
  sm: 'max-w-sm',
  md: 'max-w-md',
  lg: 'max-w-2xl',
  xl: 'max-w-4xl',
  full: 'max-w-full m-4 h-[calc(100vh-2rem)]',
};

/**
 * Composant Modal avec design Kodo
 */
export function Modal({
  open,
  onClose,
  children,
  title,
  closeOnOverlayClick = true,
  closeOnEscape = true,
  size = 'md',
  className,
  footer,
}: ModalProps) {
  const modalRef = useRef<HTMLDivElement>(null);

  // Empêcher le scroll du body quand le modal est ouvert
  useEffect(() => {
    if (open) {
      document.body.style.overflow = 'hidden';
      return () => {
        document.body.style.overflow = '';
      };
    }
    return undefined;
  }, [open]);

  // Gestion de la touche Escape
  useEffect(() => {
    if (!closeOnEscape || !open) return;

    const handleEscape = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        onClose();
      }
    };

    document.addEventListener('keydown', handleEscape);
    return () => document.removeEventListener('keydown', handleEscape);
  }, [open, closeOnEscape, onClose]);

  if (!open) return null;

  const handleOverlayClick = (e: React.MouseEvent) => {
    if (closeOnOverlayClick && e.target === e.currentTarget) {
      onClose();
    }
  };

  return createPortal(
    <div
      className="fixed inset-0 z-[100] flex items-center justify-center p-4"
      onClick={handleOverlayClick}
    >
      {/* Backdrop */}
      <div className="absolute inset-0 bg-kodo-void/90 backdrop-blur-sm animate-fadeIn" />

      {/* Modal Content */}
      <FocusTrap>
        <div
          ref={modalRef}
          className={cn(
            'relative w-full bg-kodo-graphite border border-kodo-steel rounded-xl shadow-2xl flex flex-col overflow-hidden animate-scaleIn',
            sizeClasses[size],
            className,
          )}
          onClick={(e) => e.stopPropagation()}
        >
          {/* Header */}
          {title && (
            <div className="p-4 border-b border-kodo-steel bg-kodo-ink flex justify-between items-center shrink-0">
              <h3 className="font-bold text-white text-lg font-display">
                {title}
              </h3>
              <Button
                variant="ghost"
                size="icon"
                onClick={onClose}
                className="ml-auto"
              >
                <X className="w-5 h-5" />
              </Button>
            </div>
          )}

          {/* Body */}
          <div className="p-6 overflow-y-auto custom-scrollbar flex-1">
            {children}
          </div>

          {/* Footer */}
          {footer && (
            <div className="p-4 border-t border-kodo-steel bg-kodo-ink shrink-0 flex justify-end gap-3">
              {footer}
            </div>
          )}
        </div>
      </FocusTrap>
    </div>,
    document.body,
  );
}
