import { useCallback, useState } from 'react';

const DEFAULT_MESSAGE = 'Änderungen wurden noch nicht gespeichert.';

const useDirtyNavigationGuard = ({ isDirty, saveConfig, onDiscard }) => {
  const [dialogOpen, setDialogOpen] = useState(false);
  const [dialogMessage, setDialogMessage] = useState(DEFAULT_MESSAGE);
  const [dialogSaving, setDialogSaving] = useState(false);
  const [pendingNavigation, setPendingNavigation] = useState(null);

  const requestNavigation = useCallback(
    (message, action = () => {}) => {
      if (!isDirty) {
        action();
        return;
      }
      setDialogMessage(message || DEFAULT_MESSAGE);
      setPendingNavigation(() => action);
      setDialogOpen(true);
    },
    [isDirty]
  );

  const handleDirtySave = useCallback(async () => {
    if (!pendingNavigation) {
      setDialogOpen(false);
      return;
    }
    setDialogSaving(true);
    const success = await saveConfig();
    setDialogSaving(false);
    if (!success) {
      return;
    }
    const action = pendingNavigation;
    setPendingNavigation(null);
    setDialogOpen(false);
    action();
  }, [pendingNavigation, saveConfig]);

  const handleDirtyDiscard = useCallback(() => {
    const action = pendingNavigation;
    setPendingNavigation(null);
    setDialogOpen(false);
    onDiscard?.();
    if (action) {
      action();
    }
  }, [pendingNavigation, onDiscard]);

  const handleDirtyCancel = useCallback(() => {
    setDialogOpen(false);
    setPendingNavigation(null);
  }, []);

  return {
    requestNavigation,
    dialogState: {
      open: dialogOpen,
      message: dialogMessage,
      saving: dialogSaving
    },
    handleDirtySave,
    handleDirtyDiscard,
    handleDirtyCancel
  };
};

export default useDirtyNavigationGuard;
