import React from "react"
import ReactDOM from "react-dom"
import ConfirmModal from "./confirm-modal"
import Action from "./action"

/**
 * == Example
 *
 * const result = await confirm("Are you sure?", { confirm: "Yes", cancel: "No"})
 *
 * @param {string} label message to display in the body of the modal.
 * @param options
 * @param {string} options.message longer message for the body of the modal
 * @param {string} options.confirm text in the confirm button
 * @param {string} options.cancel text in the cancel button
 * @param {boolean} options.dismissable close when background is clicked
 */
async function confirm(
  label,
  { confirm = "Yes", cancel = "No", message, dismissable = true } = {}
) {
  return new Promise(function (resolve) {
    const container = document.createElement("div")

    const close = (result) => {
      ReactDOM.unmountComponentAtNode(container)
      container.remove()
      resolve(result)
    }

    const handleCancel = () => {
      close(false)
    }

    const handleConfirm = () => {
      close(true)
    }

    const dialog = (
      <ConfirmModal
        onClose={handleCancel}
        label={label}
        dismissable={dismissable}
      >
        {message}
        <Action is="primary" onClick={handleConfirm}>
          {confirm}
        </Action>
        <Action is="secondary" onClick={handleCancel}>
          {cancel}
        </Action>
      </ConfirmModal>
    )

    ReactDOM.render(dialog, container)

    document.body.appendChild(container)
  })
}

export default confirm
