'use client';

import { useEffect, useRef } from 'react';
import { X } from 'lucide-react';
import { cn } from '@/lib/utils';

interface ModalProps {
  isOpen: boolean;
  onClose: () => void;
  title: string;
  children: React.ReactNode;
  size?: 'sm' | 'md' | 'lg' | 'xl';
}

const sizeClasses = {
  sm: 'max-w-md',
  md: 'max-w-lg',
  lg: 'max-w-2xl',
  xl: 'max-w-4xl',
};

export default function Modal({
  isOpen,
  onClose,
  title,
  children,
  size = 'md',
}: ModalProps) {
  const overlayRef = useRef<HTMLDivElement>(null);

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

    if (isOpen) {
      document.addEventListener('keydown', handleEscape);
      document.body.style.overflow = 'hidden';
    }

    return () => {
      document.removeEventListener('keydown', handleEscape);
      document.body.style.overflow = '';
    };
  }, [isOpen, onClose]);

  if (!isOpen) return null;

  return (
    <div
      ref={overlayRef}
      className="fixed inset-0 z-50 flex items-end sm:items-center justify-center p-0 sm:p-4"
      onClick={(e) => {
        if (e.target === overlayRef.current) onClose();
      }}
    >
      {/* Backdrop */}
      <div className="fixed inset-0 bg-brand-900/40 backdrop-blur-sm animate-fade-in" />

      {/* Modal content */}
      <div
        className={cn(
          'relative w-full bg-white shadow-elevated animate-slide-up-modal',
          'rounded-t-2xl sm:rounded-2xl',
          'max-h-[90dvh] sm:max-h-[85vh]',
          sizeClasses[size]
        )}
        style={{ boxShadow: 'var(--shadow-elevated)' }}
      >
        {/* Mobile drag handle */}
        <div className="sm:hidden pt-2 pb-1">
          <div className="drag-handle" />
        </div>

        {/* Header */}
        <div className="flex items-center justify-between border-b border-border px-5 sm:px-6 py-3.5 sm:py-4">
          <h2 className="text-base sm:text-lg font-semibold text-brand-700 font-heading">
            {title}
          </h2>
          <button
            onClick={onClose}
            className="flex h-8 w-8 items-center justify-center rounded-xl text-brand-400 hover:bg-brand-50 hover:text-brand-700 transition-colors cursor-pointer"
          >
            <X className="h-4 w-4" />
          </button>
        </div>

        {/* Body */}
        <div className="px-5 sm:px-6 py-4 overflow-y-auto" style={{ maxHeight: 'calc(90dvh - 120px)' }}>
          {children}
        </div>
      </div>
    </div>
  );
}
