import { useEffect } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import toast from 'react-hot-toast';
import { useTranslation } from 'react-i18next';

interface ForbiddenRouteState {
  forbidden?: boolean;
  from?: string;
}

export function useForbiddenRouteToast(): void {
  const location = useLocation();
  const navigate = useNavigate();
  const { t } = useTranslation('common');

  useEffect(() => {
    const state = location.state as ForbiddenRouteState | null;

    if (!state?.forbidden) {
      return;
    }

    toast.error(t('errors.forbiddenRoute'));

    navigate(location.pathname, {
      replace: true,
      state: state.from ? { from: state.from } : null,
    });
  }, [location.pathname, location.state, navigate, t]);
}
