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

import useSnackbar from '@material-hu/components/design-system/Snackbar';

import { useLokaliseTranslation } from 'src/utils/i18n';

import { huLibrariesRoutes } from '../routes';

type UseLibraryAccessGuardParams = {
  resetKey: string | undefined;
  isInvalid: boolean;
};

/**
 * @description When `isInvalid` is `true`, shows an error snackbar and redirects
 * to home. Dedupes redirects per `resetKey` (changing the key allows a new redirect).
 * @param resetKey - identifies current params; resets the dedupe flag when it changes.
 * @param isInvalid - keep `false` while queries load to avoid premature redirects.
 */
export const useLibraryAccessGuard = ({
  resetKey,
  isInvalid,
}: UseLibraryAccessGuardParams) => {
  const navigate = useNavigate();
  const { enqueueSnackbar } = useSnackbar();
  const { t } = useLokaliseTranslation('libraries');
  const hasRedirectedRef = useRef(false);
  const prevKeyRef = useRef(resetKey);

  useEffect(() => {
    if (prevKeyRef.current !== resetKey) {
      hasRedirectedRef.current = false;
      prevKeyRef.current = resetKey;
    }

    if (!isInvalid || hasRedirectedRef.current) return;
    hasRedirectedRef.current = true;

    enqueueSnackbar({
      title: t('library.no_access'),
      variant: 'error',
    });
    navigate(huLibrariesRoutes.base(), { replace: true });
  }, [resetKey, isInvalid, navigate, enqueueSnackbar, t]);
};
