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

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

import { settingsRoutes } from 'src/pages/dashboard/Learning/Settings/routes';
import { useLokaliseTranslation } from 'src/utils/i18n';

type UseCertificateGuardParams = {
  /** Whether the wizard is editing an existing certificate. */
  isEditMode: boolean;
  /** Whether the certificate query failed (e.g. a 404). */
  isError: boolean;
};

/**
 * Guards the edit flow: redirects to the certificates list with an informative
 * snackbar when the certificate being edited can't be loaded (missing or failed
 * request).
 */
export const useCertificateGuard = ({
  isEditMode,
  isError,
}: UseCertificateGuardParams) => {
  const navigate = useNavigate();
  const { enqueueSnackbar } = useSnackbar();
  const { t } = useLokaliseTranslation('learning');

  useEffect(() => {
    if (!isEditMode || !isError) return;
    enqueueSnackbar({
      title: t('settings.certificates.create_flow.load_error_title'),
      description: t(
        'settings.certificates.create_flow.load_error_description',
      ),
      variant: 'error',
    });
    navigate(settingsRoutes.certificates.base());
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isEditMode, isError]);
};
