import { useMutation } from 'react-query';
import { useNavigate } from 'react-router';

import { logEvent } from 'src/config/logging';
import { initCourse } from 'src/services/courses';
import { EventName } from 'src/types/amplitude';

import useRoutes from '../../hooks/useRoutes';
import { coursesKeys } from '../queries';
import {
  type Course,
  CourseStatus,
  type InitCourseData,
  StartCourseEventAction,
  StartCourseEventReason,
  type Task,
} from '../types';
import { getFirstPendingTask } from '../utils';

const useStartCourse = (course: Course) => {
  const navigate = useNavigate();
  const routes = useRoutes();

  const getTaskToNavigateTo = (task?: Task) => {
    if (task) return task;

    if (course.status === CourseStatus.FINISHED) {
      return course.modules[0].tasks[0];
    }

    return getFirstPendingTask(course.modules).task;
  };

  const navigateToTask = (task?: Task) => {
    const taskToNavigateTo = getTaskToNavigateTo(task);
    if (!taskToNavigateTo) return;

    return navigate(
      routes.courses.lesson(
        course.id,
        taskToNavigateTo.id,
        taskToNavigateTo.tag,
      ),
    );
  };

  const startCourseMutation = useMutation(
    coursesKeys.detail.init(course.id),
    (payload: InitCourseData) => initCourse(payload.courseId),
    {
      onSuccess: (_, data) => {
        logEvent(EventName.COURSE_STARTED, {
          courseId: course.id,
          resumedFrom: StartCourseEventReason.NEW,
          action: data.task
            ? StartCourseEventAction.SELECT_TASK
            : StartCourseEventAction.VIEW_COURSE,
        });

        navigateToTask(data.task);
      },
    },
  );

  const handleStartCourse = (task?: Task) => {
    if (course.status === CourseStatus.PENDING_SIGNATURE) {
      navigate(routes.courses.sign(course.id));
      return;
    }

    if (course.status === CourseStatus.PENDING) {
      startCourseMutation.mutate({ courseId: course.id, task });

      return;
    }

    logEvent(EventName.COURSE_STARTED, {
      courseId: course.id,
      resumedFrom:
        course.status === CourseStatus.FINISHED
          ? StartCourseEventReason.RESUMED
          : StartCourseEventReason.FINISHED,
    });

    navigateToTask(task);
  };

  return {
    handleStartCourse,
    startCourseMutation,
  };
};

export default useStartCourse;
