import { Helmet } from 'react-helmet-async';
import { useQuery } from 'react-query';
import { useParams } from 'react-router-dom';

import Box from '@material-hu/mui/Box';
import CircularProgress from '@material-hu/mui/CircularProgress';

import { useAuth } from 'src/contexts/JWTContext';
import useGeneralError from 'src/hooks/useGeneralError';
import { onBoardingKeys } from 'src/pages/dashboard/onboarding/queries';
import { getQuizAnswer } from 'src/services/onboarding';
import { formatTitle } from 'src/utils/helmetUtils';
import { useLokaliseTranslation } from 'src/utils/i18n';

import QuizAnswer from 'src/components/quiz/QuizAnswer';

export const QuizResults = () => {
  const { t } = useLokaliseTranslation('onboarding');
  const showGeneralError = useGeneralError();
  const { user } = useAuth();
  const { taskId } = useParams();

  const { data, isLoading } = useQuery(
    onBoardingKeys.quiz.completed.detail(user!.id, taskId!),
    () => getQuizAnswer(user!.id, taskId!),
    {
      onError: err => showGeneralError(err, t('error_loading_quiz_results')),
    },
  );

  return (
    <>
      <Helmet>
        <title>{formatTitle(t('onboardings'))}</title>
      </Helmet>
      <>
        {isLoading && (
          <Box sx={{ textAlign: 'center' }}>
            <CircularProgress />
          </Box>
        )}
        {!isLoading && data && (
          <QuizAnswer
            isOnboarding
            answer={data?.data}
          />
        )}
      </>
    </>
  );
};

export default QuizResults;
