import { useEffect } from "react";

const handleBeforeUnload = (e: BeforeUnloadEvent) => {
  e.preventDefault();
  e.returnValue = "Are you sure you want to leave this page?";
  return "Are you sure you want to leave this page?";
};

export const useUnsavedChangesRedirectionWarning = (isUnsaved: boolean) => {
  useEffect(() => {
    if (!isUnsaved) {
      window.onbeforeunload = null;
      window.removeEventListener("beforeunload", () => {});

      return;
    }
    window.addEventListener("beforeunload", handleBeforeUnload);

    return () => {
      window.onbeforeunload = null;
      window.removeEventListener("beforeunload", handleBeforeUnload);
    };
  }, [isUnsaved, handleBeforeUnload]);
};
