import { Done, Error } from '@mui/icons-material';
import { CircularProgress, Grid, Link as MUILink, Typography } from '@mui/material';
import { useMutation } from '@tanstack/react-query';
import { createFileRoute, Link, useNavigate } from '@tanstack/react-router';
import { useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { useApi } from '../../api/Api';
import HeaderlessLayout from '../../components/Layouts/HeaderlessLayout';
import { ROUTES } from '../../types/Routes';

const Home = () => {
  const Api = useApi();
  const { code } = Route.useSearch();
  const { t } = useTranslation();
  const navigate = useNavigate();

  const confirmMutation = useMutation({
    mutationFn: ({ code: _code }: { code: string }) => Api.confirmUser(_code),
  });

  useEffect(() => {
    if (code) setTimeout(() => confirmMutation.mutate({ code }), 1000);
  }, []); //eslint-disable-line react-hooks/exhaustive-deps

  useEffect(() => {
    if (!code) {
      navigate({ to: '/' });
    }
  }, [code]); //eslint-disable-line react-hooks/exhaustive-deps

  return (
    <HeaderlessLayout>
      <Grid container spacing={2} sx={{ marginTop: 0 }}>
        <Grid item xs={12} sx={{ display: 'flex', justifyContent: 'center' }}>
          {confirmMutation.isSuccess && <Done color="action" sx={{ fontSize: '200px' }} />}
          {confirmMutation.isError && <Error color="action" sx={{ fontSize: '200px' }} />}
          {(confirmMutation.isPending || confirmMutation.isIdle) && <CircularProgress size={200} />}
        </Grid>
        <Grid item xs={12} sx={{ display: 'flex', justifyContent: 'center' }}>
          {confirmMutation.isSuccess && <Typography variant="h5">{t('Confirm success header')}</Typography>}
          {confirmMutation.isError && (
            <Typography variant="h5" color="error">
              {t('Confirm error header')}
            </Typography>
          )}
          {(confirmMutation.isPending || confirmMutation.isIdle) && (
            <Typography variant="h5">{t('Confirm pending header')}</Typography>
          )}
        </Grid>
        {!confirmMutation.isPending && !confirmMutation.isIdle && (
          <Grid item xs={12} sx={{ display: 'flex', justifyContent: 'center' }}>
            <MUILink component={Link} to="/" variant="h6" underline="none">
              {t('Back to main')}
            </MUILink>
          </Grid>
        )}
      </Grid>
    </HeaderlessLayout>
  );
};

export const Route = createFileRoute(`${ROUTES.CONFIRM}/`)({
  validateSearch: (search: Record<string, unknown>): { code?: string } => {
    return {
      code: search?.code !== undefined ? (search?.code as string) : undefined,
    };
  },
  component: Home,
});
