import { ErrorOutline } from '@mui/icons-material';
import { Grid, Link as MUILink, Typography } from '@mui/material';
import { useQueryClient, useQueryErrorResetBoundary } from '@tanstack/react-query';
import { ErrorRouteComponent as TSErrorRouteComponent, useNavigate, useRouter } from '@tanstack/react-router';
import { useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import HeaderlessLayout from '../../components/Layouts/HeaderlessLayout';
import { ROUTES } from '../../types/Routes';
import { ERRORS } from './Errors';

const ErrorRouterComponent: TSErrorRouteComponent = ({ error }) => {
  const { t } = useTranslation();
  const router = useRouter();
  const navigate = useNavigate();
  const queryErrorResetBoundary = useQueryErrorResetBoundary();
  const queryClient = useQueryClient();

  useEffect(() => {
    // Reset the query error boundary
    console.log(queryErrorResetBoundary);
    queryErrorResetBoundary.reset();
  }, [queryErrorResetBoundary]);

  return (
    <HeaderlessLayout>
      <Grid container spacing={2} sx={{ marginTop: 0 }}>
        <Grid item xs={12} sx={{ display: 'flex', justifyContent: 'center' }}>
          <ErrorOutline sx={{ fontSize: '200px' }} />
        </Grid>
        <Grid item xs={12} sx={{ display: 'flex', justifyContent: 'center' }}>
          <Typography variant="h4" sx={{ textAlign: 'center' }}>
            {t('code' in error && error.code === ERRORS.UNAUTHORIZED ? 'Session expired' : 'General error')}
          </Typography>
        </Grid>
        <Grid item xs={12} sx={{ display: 'flex', justifyContent: 'center' }}>
          <MUILink
            variant="h6"
            sx={{ cursor: 'pointer' }}
            onClick={() => {
              queryClient.clear();
              router.invalidate();
              navigate({ to: ROUTES.INDEX });
            }}
          >
            {t('Back to main')}
          </MUILink>
        </Grid>
      </Grid>
    </HeaderlessLayout>
  );
};

export default ErrorRouterComponent;
