'use client'

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

interface ModalProps {
  isOpen: boolean
  onClose: () => void
  title?: string
  children: React.ReactNode
  className?: string
}

export default function Modal({ isOpen, onClose, title, children, className }: ModalProps) {
  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

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm">
      <div
        className={cn(
          "bg-white rounded-xl shadow-2xl max-w-md w-full mx-4 p-6 relative",
          className
        )}
        role="dialog"
        aria-modal="true"
      >
        <button
          onClick={onClose}
          className="absolute top-3 right-3 p-1 rounded-md text-[#1B3A1F]/60 hover:text-[#1B3A1F] hover:bg-[#2E7D32]/10 transition-colors focus:outline-none focus:ring-2 focus:ring-[#2E7D32]/50"
          aria-label="Close modal"
        >
          <X className="h-5 w-5" />
        </button>
        {title && (
          <h3 className="text-lg font-semibold text-[#1B3A1F] pr-8 mb-4">{title}</h3>
        )}
        <div>{children}</div>
      </div>
    </div>
  )
}