import React, { useEffect, useRef } from 'react'
import styles from './Modal.module.css'

export interface ModalProps {
  open: boolean
  onClose: () => void
  title?: string
  children: React.ReactNode
  footer?: React.ReactNode
  width?: 'sm' | 'md' | 'lg' | 'xl'
  closeOnOverlayClick?: boolean
}

export const Modal: React.FC<ModalProps> = ({
  open,
  onClose,
  title,
  children,
  footer,
  width = 'md',
  closeOnOverlayClick = true
}) => {
  const dialogRef = useRef<HTMLDialogElement>(null)

  useEffect(() => {
    const dialog = dialogRef.current
    if (!dialog) return

    if (open) {
      dialog.showModal()
    } else {
      dialog.close()
    }
  }, [open])

  const handleOverlayClick = (e: React.MouseEvent<HTMLDialogElement>) => {
    if (closeOnOverlayClick && e.target === dialogRef.current) {
      onClose()
    }
  }

  if (!open) return null

  return (
    <dialog
      ref={dialogRef}
      className={`${styles.modal} ${styles[`modal-${width}`]}`}
      onClick={handleOverlayClick}
    >
      <div className={styles.modalContent}>
        {/* Header */}
        {title && (
          <div className={styles.modalHeader}>
            <h3 className={styles.modalTitle}>{title}</h3>
            <button
              type="button"
              className={styles.closeButton}
              onClick={onClose}
              aria-label="Cerrar"
            >
              ×
            </button>
          </div>
        )}

        {/* Body */}
        <div className={styles.modalBody}>{children}</div>

        {/* Footer */}
        {footer && <div className={styles.modalFooter}>{footer}</div>}
      </div>
    </dialog>
  )
}

export default Modal
