/**
 * @deprecated S1.4: Prefer using `Dialog` from `@/components/ui/dialog/` for new code.
 * This modal component is kept for backward compatibility with existing consumers.
 */

import { useEffect, useId, useRef } from 'react';
import { createPortal } from 'react-dom';
import { motion, AnimatePresence } from 'framer-motion';
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-layout-modal-full',
};

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

  // 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]);

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

  return createPortal(
    <AnimatePresence>
      {open && (
        <motion.div
          key="modal"
          className="fixed inset-0 z-[var(--sumi-z-modal)] flex items-center justify-center p-4"
          onClick={handleOverlayClick}
          exit={{ opacity: 0 }}
          transition={{ duration: 0.2 }}
        >
          {/* Backdrop */}
          <motion.div
            className="absolute inset-0 bg-black/60 backdrop-blur-sm"
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            transition={{ duration: 0.2 }}
          />

          {/* Modal Content */}
          <FocusTrap>
            <motion.div
              ref={modalRef}
              role="dialog"
              aria-modal="true"
              aria-labelledby={title ? titleId : undefined}
              initial={{ opacity: 0, scale: 0.95 }}
              animate={{ opacity: 1, scale: 1 }}
              exit={{ opacity: 0, scale: 0.95 }}
              transition={{ duration: 0.2, ease: [0.33, 1, 0.68, 1] }}
              className={cn(
                'relative w-full bg-popover border border-border rounded-xl shadow-2xl flex flex-col overflow-hidden',
                sizeClasses[size],
                className,
              )}
              onClick={(e) => e.stopPropagation()}
            >
              {/* Header */}
              {title && (
                <div className="p-4 border-b border-border bg-card flex justify-between items-center shrink-0">
                  <h3 id={titleId} className="font-bold text-foreground text-lg font-heading">
                    {title}
                  </h3>
                  <Button
                    variant="ghost"
                    size="icon"
                    onClick={onClose}
                    className="ml-auto"
                    aria-label="Fermer"
                  >
                    <X className="w-5 h-5" />
                  </Button>
                </div>
              )}

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

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