import { useBeforeUnload, useBlocker } from "react-router-dom";
import { useCallback, useEffect, useRef } from "react";

function usePrompt(message, { beforeUnload } = {}) {
  let blocker = useBlocker(
    useCallback(
      (location) => {
        // This has been put in, so it does not affect transitions between the same page
        if (location.currentLocation.pathname === location.nextLocation.pathname) {
          return false;
        }
        return typeof message === "string" ? !window.confirm(message) : false;
      },
      [message]
    )
  );

  let prevState = useRef(blocker.state);

  useEffect(() => {
    if (blocker.state === "blocked") {
      blocker.reset();
    }
    prevState.current = blocker.state;
  }, [blocker]);

  useBeforeUnload(
    useCallback(
      (event) => {
        if (beforeUnload && typeof message === "string") {
          event.preventDefault();
          event.returnValue = message;
        }
      },
      [message, beforeUnload]
    ),
    { capture: true }
  );
}

function Prompt({ when, message, ...props }) {
  usePrompt(when ? message : false, props);
  return null;
}

export default Prompt;
