import { useDialog } from 'naive-ui'

export function useConfirm() {
  let dialog: ReturnType<typeof useDialog> | undefined
  try {
    dialog = useDialog()
  } catch {
    // No outer <n-dialog-provider />, fall back to window.confirm in browser.
  }

  return (content: string, title = '确认') => {
    if (!dialog) {
      if (typeof window !== 'undefined') {
        return Promise.resolve(window.confirm(content))
      }
      return Promise.resolve(false)
    }
    return new Promise<boolean>((resolve) => {
      dialog!.warning({
        title,
        content,
        positiveText: '确认',
        negativeText: '取消',
        onPositiveClick: () => resolve(true),
        onNegativeClick: () => resolve(false),
        onClose: () => resolve(false),
      })
    })
  }
}
