import styled from "@emotion/styled"
import { useCallback, useRef, useState } from "react"
import { useTranslation } from "react-i18next"
import { css } from "@emotion/css"
import Icon from "@aet/icons/macro"
import { Mutex } from "async-mutex"
import { useEvent } from "@aet/hooks"
import { Modal } from "~/vendor/react-responsive-modal"
import { Pill, PrimaryPill } from "~/shared/styled"

export const enum ConfirmResult {
  Cancel,
  Save,
  Discard,
}

const mutex = new Mutex()

export let confirmClose: (fileName: string) => Promise<ConfirmResult> = () => null!

export function ConfirmClose() {
  const [fileName, setFileName] = useState<string | null>()

  const { t } = useTranslation()
  const defer = useRef<(value: ConfirmResult) => void>()

  const onHide = useCallback(() => setFileName(null), [])

  const onSave = useEvent(() => {
    defer.current!(ConfirmResult.Save)
    mutex.release()
    setFileName(null)
  })

  const onDiscard = useEvent(() => {
    defer.current!(ConfirmResult.Discard)
    mutex.release()
    setFileName(null)
  })

  const onCancel = useEvent(() => {
    defer.current!(ConfirmResult.Cancel)
    mutex.release()
    setFileName(null)
  })

  confirmClose = useEvent(async (fileName: string) => {
    await mutex.acquire()
    setFileName(fileName)

    return new Promise<ConfirmResult>(resolve => {
      defer.current = resolve
    })
  })

  return (
    <Modal
      open={fileName != null}
      onClose={onHide}
      center
      showCloseIcon={false}
      classNames={{
        modal: css`
          max-width: 310px;
          line-height: 1.45em;
        `,
      }}
    >
      <div>
        <div
          className={css`
            color: #ecc11e;
            text-align: center;
            font-size: 5em;
            margin-bottom: 10px;
          `}
        >
          <Icon icon="IoWarning" />
        </div>
        <Header>{t("editor.closeUnsavedQuestion", { name: fileName })}</Header>
        <Description>{t("editor.closeUnsavedDescription")}</Description>

        <PrimaryButton tabIndex={0} onClick={onSave}>
          {t("editor.verbSave")}
        </PrimaryButton>
        <Button tabIndex={0} onClick={onDiscard}>
          {t("editor.verbDoNotSave")}
        </Button>
        {separator}
        <Button tabIndex={0} onClick={onCancel}>
          {t("cancel")}
        </Button>
      </div>
    </Modal>
  )
}

const separator = <div style={{ height: 5 }} />

const Header = styled.h3`
  font-weight: 600;
  margin: 0;
  text-align: center;
`
const Description = styled.p`
  text-align: center;
`
const Button = styled(Pill)`
  margin-top: 5px;
  width: 100%;
`

const PrimaryButton = styled(PrimaryPill)`
  width: 100%;
`
