import { useEffect } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';

import { NavigationAction } from 'src/constants/navigationActions';

const useNavigationAction = (
  action: NavigationAction,
  callback: () => void,
) => {
  const location = useLocation();
  const navigate = useNavigate();

  useEffect(() => {
    if (location.state?.navigationAction === action) {
      callback();
      // Clear state to avoid re-triggering on refresh or further navigation.
      navigate(location.pathname, {
        replace: true,
        state: { ...location.state, navigationAction: undefined },
      });
    }
    // We intentionally depend on location.state?.action so the effect only
    // re-runs when the action changes, not on unrelated location changes.
  }, [
    location.state?.navigationAction,
    action,
    callback,
    navigate,
    location.pathname,
  ]);
};

export default useNavigationAction;

// Hook to easily trigger a navigation action from any component
export const useTriggerNavigationAction = () => {
  const navigate = useNavigate();

  /**
   * Navigates to the given `to` path adding the provided `action` in the
   * navigation state. You can optionally pass `replace` to avoid pushing a new
   * history entry.
   */
  return (
    to: string,
    action: NavigationAction,
    options: { replace?: boolean } = {},
  ) => {
    navigate(to, {
      state: { navigationAction: action },
      replace: options.replace ?? false,
    });
  };
};
