import React, { useEffect, useRef } from 'react';
import clsx from 'clsx';
import { X } from 'lucide-react';

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

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

export function Modal({
  open,
  onClose,
  title,
  children,
  size = 'md',
  closeOnBackdrop = true,
  closeOnEscape = true,
  showCloseButton = true,
  fullScreenMobile = false,
}: ModalProps) {
  const dialogRef = useRef<HTMLDivElement>(null);
  const previouslyFocused = useRef<HTMLElement | null>(null);

  useEffect(() => {
    if (open) {
      previouslyFocused.current = document.activeElement as HTMLElement;
      const focusable = dialogRef.current?.querySelector<HTMLElement>(
        'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
      );
      focusable?.focus();
    } else {
      previouslyFocused.current?.focus();
    }
  }, [open]);

  useEffect(() => {
    if (!open || !closeOnEscape) return;
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        e.stopPropagation();
        onClose();
      }
    };
    document.addEventListener('keydown', handleKeyDown);
    return () => document.removeEventListener('keydown', handleKeyDown);
  }, [open, closeOnEscape, onClose]);

  if (!open) return null;

  return (
    <div
      className={clsx(
        'fixed inset-0 z-50 flex items-center justify-center',
        fullScreenMobile ? 'p-0 md:p-4' : 'p-4'
      )}
      role="dialog"
      aria-modal="true"
      aria-labelledby={title ? 'modal-title' : undefined}
    >
      <div
        className="absolute inset-0 bg-secondary-900/50 motion-safe:animate-opacity"
        onClick={closeOnBackdrop ? onClose : undefined}
        aria-hidden="true"
        data-testid="modal-backdrop"
      />
      <div
        ref={dialogRef}
        className={clsx(
          'relative bg-white rounded-lg shadow-xl w-full',
          'motion-safe:animate-scale',
          fullScreenMobile && 'h-full md:h-auto md:max-h-[85vh]',
          fullScreenMobile ? 'rounded-none md:rounded-lg' : '',
          sizeClasses[size]
        )}
      >
        {title && (
          <div className="px-4 py-3 md:px-6 md:py-4 border-b border-secondary-200">
            <h2 id="modal-title" className="text-base md:text-lg font-semibold text-secondary-900">
              {title}
            </h2>
          </div>
        )}
        {showCloseButton && (
          <button
            onClick={onClose}
            className="absolute top-3 right-3 md:top-4 md:right-4 text-secondary-400 hover:text-secondary-600 min-h-touch min-w-touch flex items-center justify-center rounded-md focus:outline-none focus-visible:ring-2 focus-visible:ring-primary-500"
            aria-label="Close dialog"
          >
            <X className="h-5 w-5" aria-hidden="true" />
          </button>
        )}
        <div className={clsx(
          'px-4 py-4 md:px-6 overflow-y-auto',
          fullScreenMobile ? 'max-h-none md:max-h-[70vh] h-full md:h-auto' : 'max-h-[70vh]'
        )}>
          {children}
        </div>
      </div>
    </div>
  );
}
