import { RouterState } from '@remix-run/router';
import { useEffect } from 'react';
import { NavigationType } from 'react-router';

import { router } from '@/shared/configs/sentry';

type IRouterListener = (state: RouterState) => void;

export const useRouterListener = (callback: IRouterListener, actionType?: NavigationType) => {
  useEffect(() => {
    const unsubscribe = router.subscribe((state: any) => {
      if (actionType && state.historyAction !== actionType) return;
      if (!actionType || state.historyAction === actionType) {
        callback?.(state);
      }
    });

    return unsubscribe;
  }, [callback, actionType]);
};
