import { useState, useEffect } from 'react';
import { useBlocker } from 'react-router';

export function useUnsavedChangesBlocker(hasUnsavedChanges: boolean) {
  const blocker = useBlocker(({ currentLocation, nextLocation }) =>
    hasUnsavedChanges && currentLocation.pathname !== nextLocation.pathname
  );

  const [dialogOpen, setDialogOpen] = useState(false);

  useEffect(() => {
    if (blocker.state === 'blocked') setDialogOpen(true);
  }, [blocker.state]);

  return {
    dialogOpen,
    confirm: () => {
      setDialogOpen(false);
      blocker.proceed?.();
    },
    cancel: () => {
      setDialogOpen(false);
      blocker.reset?.();
    },
  };
}
