import { Input, Modal, message as antdMessage } from 'antd'
import type { ModalFuncProps } from 'antd'
import { createElement } from 'react'

type MessageOptions = {
  duration?: number
}

type PromptResult = {
  value: string
}

export function showSuccess(message: string, options: MessageOptions = {}) {
  return antdMessage.success({
    content: message,
    duration: options.duration,
  })
}

export function showError(message: string, options: MessageOptions = {}) {
  return antdMessage.error({
    content: message,
    duration: options.duration,
  })
}

export function showConfirm(message: string, title = '确认操作', options: ModalFuncProps = {}) {
  return new Promise<void>((resolve, reject) => {
    Modal.confirm({
      title,
      content: message,
      okText: '继续执行',
      cancelText: '取消',
      centered: true,
      ...options,
      onOk: () => {
        options.onOk?.()
        resolve()
      },
      onCancel: () => {
        options.onCancel?.()
        reject('cancel')
      },
    })
  })
}

export function showPrompt(message: string, title: string, options: ModalFuncProps = {}) {
  let value = ''

  return new Promise<PromptResult>((resolve, reject) => {
    Modal.confirm({
      title,
      content: createElement('div', { className: 'feedback-prompt' }, [
        createElement('p', { key: 'message' }, message),
        createElement(Input, {
          key: 'input',
          autoFocus: true,
          onChange: (event) => {
            value = event.target.value
          },
        }),
      ]),
      okText: '提交',
      cancelText: '取消',
      centered: true,
      ...options,
      onOk: () => {
        options.onOk?.()
        resolve({ value })
      },
      onCancel: () => {
        options.onCancel?.()
        reject('cancel')
      },
    })
  })
}

export function isFeedbackDismissed(error: unknown) {
  return error === 'cancel' || error === 'close'
}
