import { useEffect } from 'react';
import { Helmet } from 'react-helmet-async';
import { FormProvider, useForm } from 'react-hook-form';

import useHuGoTheme from 'src/hooks/useHuGoTheme';
import { formatTitle } from 'src/utils/helmetUtils';

import useIds from '../../hooks/useIds';
import useCoursesTitle from '../hooks/useCoursesTitle';
import useGetCourse from '../hooks/useGetCourse';
import useGetTask from '../hooks/useGetTask';
import useTaskNavigation from '../hooks/useTaskNavigation';
import { type EvaluationTask, type TaskLayoutForm } from '../types';

import ModuleFinished from './components/ModuleFinished';
import TaskEvaluation from './components/TaskEvaluation';
import TaskLayout from './components/TaskLayout';

const CourseTasks = () => {
  const HugoThemeProvider = useHuGoTheme();
  const title = useCoursesTitle();
  const { courseId, taskId, tag } = useIds();

  const form = useForm<TaskLayoutForm>({
    defaultValues: {
      finished: false,
      multimediaFinished: false,
    },
  });

  useEffect(() => {
    return () => form.reset();
  }, [taskId]);

  const { course, isLoading: isLoadingCourse } = useGetCourse({
    courseId,
  });

  const { data: task, isLoading: isLoadingTask } = useGetTask({ taskId, tag });

  const {
    showTaskEvaluation,
    showTaskBase,
    showModuleFinished,
    handlePrevious,
    handleNext,
  } = useTaskNavigation();

  return (
    <>
      <Helmet>
        <title>{formatTitle(title)}</title>
      </Helmet>
      <HugoThemeProvider>
        <FormProvider {...form}>
          {showTaskEvaluation && (
            <TaskEvaluation
              key={taskId}
              course={course}
              task={task as EvaluationTask}
              loadingCourse={isLoadingCourse}
              loadingTask={isLoadingTask}
              onNext={handleNext}
              onPrevious={handlePrevious}
            />
          )}
          {showTaskBase && (
            <TaskLayout
              key={taskId}
              course={course}
              task={task}
              loadingCourse={isLoadingCourse}
              loadingTask={isLoadingTask}
              onNext={handleNext}
              onPrevious={handlePrevious}
            />
          )}
          {showModuleFinished && (
            <ModuleFinished
              course={course}
              loadingCourse={isLoadingCourse}
              onNext={handleNext}
              onPrevious={handlePrevious}
            />
          )}
        </FormProvider>
      </HugoThemeProvider>
    </>
  );
};

export default CourseTasks;
