import { useState, useEffect, useCallback, useRef, 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
}

const FOCUSABLE_SELECTOR =
  'button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"]):not([disabled])'

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 modalRef = useRef<HTMLDivElement>(null)
  const previousFocusRef = useRef<HTMLElement | null>(null)

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

  // Body overflow lock + keyboard listener
  useEffect(() => {
    if (isOpen) {
      previousFocusRef.current = document.activeElement as HTMLElement
      document.addEventListener('keydown', handleKeyDown)
      document.body.style.overflow = 'hidden'
    }
    return () => {
      document.removeEventListener('keydown', handleKeyDown)
      document.body.style.overflow = ''
    }
  }, [isOpen, handleKeyDown])

  // Focus trap: keep focus inside the modal
  useEffect(() => {
    if (!isOpen) {
      // Restore focus when modal closes
      previousFocusRef.current?.focus()
      return
    }

    const modal = modalRef.current
    if (!modal) return

    // Auto-focus first focusable element
    const timer = setTimeout(() => {
      const focusable = modal.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR)
      if (focusable.length > 0) {
        focusable[0].focus()
      }
    }, 50)

    const trapFocus = (e: KeyboardEvent) => {
      if (e.key !== 'Tab') return

      const focusable = modal.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR)
      if (focusable.length === 0) return

      const first = focusable[0]
      const last = focusable[focusable.length - 1]

      if (e.shiftKey && document.activeElement === first) {
        e.preventDefault()
        last.focus()
      } else if (!e.shiftKey && document.activeElement === last) {
        e.preventDefault()
        first.focus()
      }
    }

    modal.addEventListener('keydown', trapFocus)
    return () => {
      clearTimeout(timer)
      modal.removeEventListener('keydown', trapFocus)
    }
  }, [isOpen])

  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-xs"
        onClick={onClose}
        aria-hidden="true"
      />

      {/* Modal Content */}
      <div
        ref={modalRef}
        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-screen rounded-t-2xl sm:max-h-[85vh] sm:rounded-2xl',
                sizeClasses[size]
              )
        )}
      >
        {/* Header - Fixed at top */}
        <div className="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-hidden 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="shrink-0 border-t border-border px-4 py-3 sm:px-6 sm:py-4">
            {footer}
          </div>
        )}
      </div>
    </div>
  )
}

export default Modal
