import { FC } from 'react';
import { useQuery, useMutation } from 'react-query';
import { useParams, useNavigate } from 'react-router-dom';

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 ArticleDetail from 'src/pages/dashboard/news/components/ArticleDetail';
import {
  onBoardingKeys,
  updateTaksOfCategory,
  invalidateOnboardingNotifications,
} from 'src/pages/dashboard/onboarding/queries';
import { onboardingRoutes } from 'src/pages/dashboard/onboarding/routes';
import {
  getOnboardingTasksDetail,
  finalizeOnboardingTask,
} from 'src/services/onboarding';
import { EventName } from 'src/types/amplitude';
import { CopyTypePath } from 'src/types/deeplinks';
import { OnboardingStatus } from 'src/types/onboarding';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { checkCategoryAlreadyDone } from 'src/utils/onboarding';

import GoBackButton from 'src/components/dashboard/GoBackButton';
import FinalizeButton from 'src/components/quiz/FinalizeButton';
import ViewResults from 'src/components/quiz/ViewResults';

const TaskDetail: FC = () => {
  const { taskId, categoryId } = useParams();
  const { t } = useLokaliseTranslation('onboarding');
  const { enqueueSnackbar } = useSnackbar();
  const showGeneralError = useGeneralError();
  const navigate = useNavigate();
  const { user } = useAuth();

  const { data: task, isLoading: isLoadingTask } = useQuery(
    onBoardingKeys.tasks.detail(taskId!, categoryId!),
    () => getOnboardingTasksDetail(user!.id, categoryId!, taskId!),
    {
      onError: err => showGeneralError(err, t('error_loading_tasks_detail')),
    },
  );

  const { isLoading: loadingMutation, mutate: finalizeOnboardingTaskMutate } =
    useMutation((param: any) => finalizeOnboardingTask(param), {
      onSuccess: () => {
        invalidateOnboardingNotifications();
        updateTaksOfCategory(categoryId!, taskId!);

        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_finalize_task'),
          variant: 'success',
        });
        navigate('..');
      },
      onError: error => {
        showGeneralError(error, t('error_finalize_task'));
      },
    });

  const handleFinalizeOnboarding = () => {
    finalizeOnboardingTaskMutate({ userId: user!.id, taskId });
  };

  const handleViewResults = () => {
    navigate(onboardingRoutes.quizResults(categoryId!, taskId!));
  };

  const handleQuiz = () => {
    navigate(onboardingRoutes.quizForm(categoryId!, taskId!));
  };

  const handleBack = () => {
    navigate('..');
  };

  const { name, body, coverPicture, attachments, hasQuiz } = task?.task || {};

  if (isLoadingTask) {
    return (
      <Box sx={{ textAlign: 'center', mt: 8 }}>
        <CircularProgress />
      </Box>
    );
  }

  return (
    <Container maxWidth="md">
      <Box sx={{ mt: 3, mb: 3 }}>
        <GoBackButton onClick={handleBack} />
        <ArticleDetail
          title={name}
          body={body}
          coverPicture={coverPicture}
          isArticle={false}
          copyType={CopyTypePath.ONBOARDING_TASK}
          copyRoute={onboardingRoutes.taks(categoryId!, taskId!)}
          attachments={attachments}
        />
        {!hasQuiz && task?.status === OnboardingStatus.TODO && (
          <FinalizeButton
            label={t('finalize')}
            onClick={handleFinalizeOnboarding}
            disabled={loadingMutation}
          />
        )}
        {hasQuiz && task?.status === OnboardingStatus.TODO && (
          <FinalizeButton
            label={t('complete_and_finalize')}
            onClick={handleQuiz}
            disabled={loadingMutation}
          />
        )}
        {hasQuiz && task?.status === OnboardingStatus.DONE && (
          <ViewResults
            handleViewResults={handleViewResults}
            textButton={t('view_results')}
          />
        )}
      </Box>
    </Container>
  );
};

export default TaskDetail;
