import { useState } from 'react'

/**
 * useDialog — Promise-based hook for confirm and alert dialogs.
 *
 * Usage:
 *   const { dialogProps, openConfirm, openAlert } = useDialog()
 *
 *   // In JSX: <Dialog {...dialogProps} />
 *
 *   // Confirm (returns true/false):
 *   const ok = await openConfirm('Delete this item?', { title: 'Delete', confirmLabel: 'Delete', danger: true })
 *   if (!ok) return
 *
 *   // Alert (acknowledgement only):
 *   await openAlert('Something went wrong.')
 */
export function useDialog() {
  const [dialog, setDialog] = useState(null)

  const openConfirm = (message, { title, confirmLabel = 'Confirm', cancelLabel = 'Cancel', danger = false } = {}) =>
    new Promise(resolve => {
      setDialog({ message, title, confirmLabel, cancelLabel, danger, resolve })
    })

  const openAlert = (message, { title } = {}) =>
    new Promise(resolve => {
      setDialog({ message, title, confirmLabel: 'OK', cancelLabel: null, danger: false, resolve })
    })

  const close = (result) => {
    setDialog(d => { d?.resolve(result); return null })
  }

  const dialogProps = dialog
    ? {
        open: true,
        title: dialog.title,
        message: dialog.message,
        confirmLabel: dialog.confirmLabel,
        cancelLabel: dialog.cancelLabel,
        danger: dialog.danger,
        onConfirm: () => close(true),
        onCancel: () => close(false),
      }
    : { open: false }

  return { dialogProps, openConfirm, openAlert }
}
