import { useEffect } from 'react'
import { X } from 'lucide-react'
import Button from './Button'

// General-purpose modal — replaces ConfirmModal and can wrap any content.
//
// Usage (confirm pattern):
//   <Modal title="Διαγραφή" onClose={onCancel}>
//     <p>Θέλετε σίγουρα να διαγράψετε αυτό το στοιχείο;</p>
//     <Modal.Footer>
//       <Button variant="secondary" onClick={onCancel}>Ακύρωση</Button>
//       <Button variant="danger" onClick={onConfirm}>Διαγραφή</Button>
//     </Modal.Footer>
//   </Modal>

export default function Modal({ title, onClose, children, maxWidth = 'max-w-sm', className = '' }) {
  // Close on Escape
  useEffect(() => {
    function handler(e) {
      if (e.key === 'Escape') onClose?.()
    }
    document.addEventListener('keydown', handler)
    return () => document.removeEventListener('keydown', handler)
  }, [onClose])

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4"
      onMouseDown={(e) => { if (e.target === e.currentTarget) onClose?.() }}
    >
      <div className={`relative w-full ${maxWidth} rounded-xl border border-slate-200 bg-white shadow-xl ${className}`}>
        {/* Header */}
        {title && (
          <div className="flex items-center justify-between border-b border-slate-100 px-5 py-4">
            <h2 className="text-[15px] font-semibold text-slate-900">{title}</h2>
            {onClose && (
              <button
                onClick={onClose}
                className="rounded-md p-1 text-slate-400 transition hover:bg-slate-100 hover:text-slate-600"
              >
                <X className="h-4 w-4" />
              </button>
            )}
          </div>
        )}

        {/* Body */}
        <div className="px-5 py-4 space-y-3 text-[13px] text-slate-700">
          {children}
        </div>
      </div>
    </div>
  )
}

// Footer helper — renders a right-aligned row of action buttons
function ModalFooter({ children }) {
  return (
    <div className="flex items-center justify-end gap-2 border-t border-slate-100 pt-4 mt-2">
      {children}
    </div>
  )
}

Modal.Footer = ModalFooter

// Convenience: ConfirmModal wrapping Modal for the most common pattern
export function ConfirmModal({
  title,
  message,
  confirmLabel = 'Επιβεβαίωση',
  confirmVariant = 'danger',
  onConfirm,
  onCancel,
}) {
  return (
    <Modal title={title} onClose={onCancel}>
      {message && <p className="text-[13px] text-slate-600">{message}</p>}
      <Modal.Footer>
        <Button variant="secondary" onClick={onCancel}>Ακύρωση</Button>
        <Button variant={confirmVariant} onClick={onConfirm}>{confirmLabel}</Button>
      </Modal.Footer>
    </Modal>
  )
}
