import { Dialog, DialogProps, DialogRef } from './Dialog'
import { imperative } from '../../utils'

export const show = (props: DialogProps) => {
  imperative<DialogProps, DialogRef>(({ ref, unmount, container }) => ({
    component: Dialog,
    props: {
      ...props,
      popupProps: {
        ...props.popupProps,
        container,
        onExited: () => {
          props.popupProps?.onExited?.()
          unmount()
        },
      },
      onCancel: () => {
        ref.current?.$$setProps({
          visible: false,
        })
        props.onCancel?.()
      },
      onConfirm: () => {
        ref.current?.$$setProps({
          visible: false,
        })
        props.onConfirm?.()
      },
      beforeClose(done, type) {
        if (props.beforeClose) {
          ref.current?.$$setProps({
            confirmProps: {
              loading: true,
              disabled: true,
            },
          })
          props.beforeClose(done, type)
        } else {
          done()
        }
      },
      onDone() {
        ref.current?.$$setProps({
          confirmProps: {
            loading: false,
            disabled: false,
          },
        })
      },
    },
    afterRender() {
      ref.current?.$$setProps({
        visible: true,
      })
    },
  }))
}

export const alert = (props: DialogProps) => {
  show({ ...props, showCancel: false })
}

export const confirm = (props: DialogProps) => {
  show({ ...props, showCancel: true })
}
