import { useState, useEffect } from 'react';
import { Helmet } from 'react-helmet-async';
import { useQuery, useMutation } from 'react-query';
import { useParams, useNavigate } from 'react-router-dom';

import { differenceInSeconds } from 'date-fns';

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

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

import { logEvent } from 'src/config/logging';
import { useAuth } from 'src/contexts/JWTContext';
import useGeneralError from 'src/hooks/useGeneralError';
import {
  onBoardingKeys,
  updateTaksOfCategory,
  isCategoryListInCache,
  invalidateOnboardingNotifications,
} from 'src/pages/dashboard/onboarding/queries';
import { onboardingRoutes } from 'src/pages/dashboard/onboarding/routes';
import {
  getOnboardingQuiz,
  completeOnboardingTask,
} from 'src/services/onboarding';
import { EventName } from 'src/types/amplitude';
import { formatValues } from 'src/utils/form';
import { formatTitle } from 'src/utils/helmetUtils';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { checkCategoryAlreadyDone } from 'src/utils/onboarding';

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

export const QuizForm = () => {
  // eslint-disable-next-line react/hook-use-state
  const [startTime] = useState(new Date());
  const { t } = useLokaliseTranslation('onboarding');
  const { enqueueSnackbar } = useSnackbar();
  const showGeneralError = useGeneralError();
  const { categoryId, taskId } = useParams();
  const navigate = useNavigate();
  const { user } = useAuth();

  useEffect(() => {
    if (!isCategoryListInCache(categoryId!)) {
      navigate(onboardingRoutes.taks(categoryId!, taskId!));
    }
  }, []);

  const { data, isLoading } = useQuery(
    onBoardingKeys.quiz.detail(categoryId!, taskId!),
    () => getOnboardingQuiz(taskId),
    {
      onError: err => {
        showGeneralError(err, t('error_loading_quiz_form'));
      },
    },
  );

  const postMutation = useMutation(completeOnboardingTask, {
    onError: err => {
      showGeneralError(err, t('error_send_quiz'));
    },
    onSuccess: () => {
      updateTaksOfCategory(categoryId!, taskId!);
      invalidateOnboardingNotifications();

      if (checkCategoryAlreadyDone(categoryId)) {
        logEvent(EventName.ONBOARDING_TASK_COMPLETE, { categoryId, taskId });
        logEvent(EventName.ONBOARDING_CATEGORY_COMPLETE, { categoryId });
      } else {
        logEvent(EventName.ONBOARDING_TASK_COMPLETE, { categoryId, taskId });
      }

      enqueueSnackbar({
        title: t('SUCCESS_SEND_QUIZ'),
        variant: 'success',
      });
      navigate(onboardingRoutes.quizResults(categoryId!, taskId!), {
        replace: true,
      });
    },
  });

  const handleSubmit = async (values: any) => {
    const endTime = new Date();
    const fillingTime = differenceInSeconds(endTime, startTime);

    const questions = formatValues(values);

    const body = {
      questions,
      fillingTime,
    };

    postMutation.mutate({
      userId: user?.id,
      taskId,
      quizId: data?.data?.id,
      body,
    });
  };

  return (
    <>
      <Helmet>
        <title>{formatTitle(t('onboardings'))}</title>
      </Helmet>
      <Box
        sx={{
          backgroundColor: 'background.default',
          minHeight: '100%',
          pt: 2,
          pb: 8,
        }}
      >
        <Container maxWidth="lg">
          {isLoading && (
            <Box sx={{ textAlign: 'center' }}>
              <CircularProgress />
            </Box>
          )}
          {!isLoading && data && (
            <QuizDetail
              template={data.data || []}
              onSubmit={handleSubmit}
              isLoading={postMutation.isLoading}
            />
          )}
        </Container>
      </Box>
    </>
  );
};

export default QuizForm;
