import { type FormEvent, type ReactNode, useState, useEffect } from 'react'

interface FormModalProps {
  title: string
  onClose: () => void
  onSubmit: (e: FormEvent) => void
  children: ReactNode
  submitLabel?: string | undefined
  isSubmitting?: boolean | undefined
  onDelete?: (() => void) | undefined
  isDeleting?: boolean | undefined
  headerExtra?: ReactNode | undefined
}

export function FormModal({
  title,
  onClose,
  onSubmit,
  children,
  submitLabel = 'Save',
  isSubmitting,
  onDelete,
  isDeleting,
  headerExtra,
}: FormModalProps) {
  const [confirmingDelete, setConfirmingDelete] = useState(false)

  // Reset confirm state when modal closes/reopens
  useEffect(() => {
    setConfirmingDelete(false)
  }, [onDelete])

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center">
      <div className="fixed inset-0 bg-black/50" onClick={onClose} />
      <div className="relative bg-surface-1 rounded-lg shadow-xl max-w-lg w-full mx-4 max-h-[90vh] overflow-y-auto">
        <div className="px-6 py-4 border-b border-border-default">
          <h2 className="text-lg font-semibold">{title}</h2>
          {headerExtra}
        </div>
        <form onSubmit={onSubmit}>
          <div className="px-6 py-4 space-y-4">{children}</div>
          <div className="px-6 py-4 border-t border-border-default flex items-center gap-3">
            {onDelete && (
              <button
                type="button"
                disabled={isDeleting}
                onClick={() => {
                  if (confirmingDelete) {
                    onDelete()
                  } else {
                    setConfirmingDelete(true)
                  }
                }}
                onBlur={() => setConfirmingDelete(false)}
                className="px-4 py-2 text-sm font-medium rounded-md text-status-failed border border-red-600 hover:bg-red-900/20 disabled:opacity-50"
              >
                {isDeleting ? 'Deleting...' : confirmingDelete ? 'Confirm?' : 'Delete'}
              </button>
            )}
            <div className="flex-1" />
            <button
              type="button"
              onClick={onClose}
              className="px-4 py-2 text-sm font-medium rounded-md border border-border-default hover:bg-surface-2"
            >
              Cancel
            </button>
            <button
              type="submit"
              disabled={isSubmitting}
              className="px-4 py-2 text-sm font-medium rounded-md bg-accent-600 text-white hover:bg-accent-500 disabled:opacity-50"
            >
              {isSubmitting ? 'Saving...' : submitLabel}
            </button>
          </div>
        </form>
      </div>
    </div>
  )
}
