import { useState, useEffect, useCallback, type ReactNode } from 'react'
import { X, Maximize2, Minimize2 } from 'lucide-react'
import { cn } from '@/lib/utils'

interface ModalProps {
  isOpen: boolean
  onClose: () => void
  title: string
  children: ReactNode
  /** Optional footer content that stays fixed at bottom (doesn't scroll) */
  footer?: ReactNode
  size?: 'sm' | 'md' | 'lg' | 'xl'
  /** If true, a fullscreen toggle button appears in the modal header */
  allowFullScreen?: boolean
}

export function Modal({ isOpen, onClose, title, children, footer, size = 'md', allowFullScreen = false }: ModalProps) {
  const [isFullScreen, setIsFullScreen] = useState(() => {
    if (!allowFullScreen) return false
    try {
      return localStorage.getItem('rf-editor-fullscreen') === 'true'
    } catch {
      return false
    }
  })

  const toggleFullScreen = () => {
    const next = !isFullScreen
    setIsFullScreen(next)
    try {
      localStorage.setItem('rf-editor-fullscreen', String(next))
    } catch {
      // localStorage unavailable — ignore
    }
  }

  // Close on Escape key
  const handleKeyDown = useCallback(
    (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        onClose()
      }
    },
    [onClose]
  )

  useEffect(() => {
    if (isOpen) {
      document.addEventListener('keydown', handleKeyDown)
      document.body.style.overflow = 'hidden'
    }
    return () => {
      document.removeEventListener('keydown', handleKeyDown)
      document.body.style.overflow = ''
    }
  }, [isOpen, handleKeyDown])

  if (!isOpen) return null

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

  return (
    <div
      className="fixed inset-0 z-50 flex items-end justify-center p-0 sm:items-center sm:p-4"
      role="dialog"
      aria-modal="true"
      aria-labelledby="modal-title"
    >
      {/* Backdrop */}
      <div
        className="absolute inset-0 bg-black/80 backdrop-blur-sm"
        onClick={onClose}
        aria-hidden="true"
      />

      {/* Modal Content */}
      <div
        className={cn(
          'relative flex w-full flex-col border border-border bg-card shadow-lg',
          'animate-scale-in transition-all duration-200',
          isFullScreen
            ? 'fixed inset-4 max-w-none w-auto h-auto rounded-2xl'
            : cn(
                'max-h-[100vh] rounded-t-2xl sm:max-h-[85vh] sm:rounded-2xl',
                sizeClasses[size]
              )
        )}
      >
        {/* Header - Fixed at top */}
        <div className="flex flex-shrink-0 items-center justify-between border-b border-border px-4 py-3 sm:px-6 sm:py-4">
          <h2 id="modal-title" className="text-lg font-semibold text-foreground">
            {title}
          </h2>
          <div className="flex items-center gap-1">
            {allowFullScreen && (
              <button
                type="button"
                onClick={toggleFullScreen}
                className="rounded-md p-1 text-muted-foreground hover:bg-accent hover:text-foreground"
                title={isFullScreen ? 'Exit full screen' : 'Full screen'}
              >
                {isFullScreen
                  ? <Minimize2 className="h-4 w-4" />
                  : <Maximize2 className="h-4 w-4" />
                }
              </button>
            )}
            <button
              onClick={onClose}
              className={cn(
                'rounded-md p-1.5 text-muted-foreground transition-colors sm:p-1',
                'hover:bg-accent hover:text-foreground',
                'focus:outline-none focus:ring-2 focus:ring-primary/20'
              )}
              aria-label="Close modal"
            >
              <X className="h-5 w-5" />
            </button>
          </div>
        </div>

        {/* Body - Scrollable */}
        <div className="flex-1 overflow-y-auto px-4 py-4 sm:px-6">
          {children}
        </div>

        {/* Footer - Fixed at bottom */}
        {footer && (
          <div className="flex-shrink-0 border-t border-border px-4 py-3 sm:px-6 sm:py-4">
            {footer}
          </div>
        )}
      </div>
    </div>
  )
}

export default Modal
