import { Box } from '../box'
import { useVuiContext } from '../core'
import { Dialog } from '../dialog'
import { Input } from '../input'

export const useDialog = () => {
  const { setPortalSlot } = useVuiContext()

  const showConfirm = (title: string, message: string): Promise<boolean> =>
    new Promise(resolve =>
      setPortalSlot(
        <Dialog
          body={message}
          cancelButton={{
            onClick: () => {
              resolve(false)
              setPortalSlot(null)
            },
            text: 'Cancel',
          }}
          closeButton={false}
          isOpen
          submitButton={{
            onClick: () => {
              resolve(true)
              setPortalSlot(null)
            },
            text: 'Confirm',
          }}
          title={title}
        />,
      ),
    )

  const showPrompt = (title: string, value = ''): Promise<string | false> =>
    new Promise(resolve => {
      let inputValue = value
      setPortalSlot(
        <Dialog
          body={
            <Box px={3} py={2}>
              <Input onChange={e => (inputValue = e.target.value)} value={value} />
            </Box>
          }
          cancelButton={{
            onClick: () => {
              resolve(false)
              setPortalSlot(null)
            },
            text: 'Cancel',
          }}
          closeButton={false}
          isOpen
          submitButton={{
            onClick: () => {
              resolve(inputValue)
              setPortalSlot(null)
            },
            text: 'Submit',
          }}
          title={title}
        />,
      )
    })

  return { showConfirm, showPrompt }
}
