import { useCallback, useContext } from "react";

import { MODAL_BACKDROP_TIMEOUT } from "../Modal";

import ConfirmContext from "./ConfirmContext";

type ResolveCallback = ((value: unknown) => void) | null;

let resolveCallback: ResolveCallback = null;

export default function useConfirm() {
  const [confirmState, { closeConfirm, showConfirm }] =
    useContext(ConfirmContext);

  const onConfirm = () => {
    closeConfirm();
    resolveCallback?.(true);
  };

  const onCancel = () => {
    closeConfirm();
    resolveCallback?.(false);
  };

  const confirm = useCallback(
    async (text: string) => {
      showConfirm(text);
      return new Promise((resolve) => {
        setTimeout(() => {
          resolveCallback = resolve;
        }, MODAL_BACKDROP_TIMEOUT);
      });
    },
    [showConfirm],
  );

  return { confirm, confirmState, onCancel, onConfirm };
}
