import { useCallback, useState } from 'react'
import type { ReactNode } from 'react'

/**
 * Хук-обёртка над <ConfirmDialog>: переписывает `if (confirm('...'))` на
 * `await confirm({ title, description, ... })`. Возвращает true если
 * пользователь подтвердил, false если отмёл (Esc, бэкграунд клик, Cancel).
 *
 * Пример:
 *   const { confirm, dialogProps } = useConfirm()
 *   ...
 *   if (await confirm({ title: 'Удалить товар?', description: name, confirmLabel: 'Удалить' })) {
 *     remove.mutate()
 *   }
 *   ...
 *   <ConfirmDialog {...dialogProps} />
 */
export interface ConfirmRequest {
  title: string
  description?: ReactNode
  confirmLabel?: string
  cancelLabel?: string
  tone?: 'danger' | 'warning'
}

export function useConfirm() {
  const [state, setState] = useState<{
    req: ConfirmRequest
    resolve: (v: boolean) => void
  } | null>(null)

  const confirm = useCallback((req: ConfirmRequest): Promise<boolean> => {
    return new Promise<boolean>((resolve) => setState({ req, resolve }))
  }, [])

  const onCancel = useCallback(() => {
    state?.resolve(false)
    setState(null)
  }, [state])

  const onConfirm = useCallback(() => {
    state?.resolve(true)
    setState(null)
  }, [state])

  return {
    confirm,
    dialogProps: {
      open: !!state,
      title: state?.req.title ?? '',
      description: state?.req.description,
      confirmLabel: state?.req.confirmLabel,
      cancelLabel: state?.req.cancelLabel,
      tone: state?.req.tone,
      onCancel,
      onConfirm,
    },
  }
}
