import { type TablerIcon } from '@material-hu/icons/tabler';

import { TaskTypes } from '@material-hu/components/composed-components/learning';

import { TASKS_STATUS_ICONS } from 'src/pages/dashboard/learning/courses/constants';
import {
  type Course,
  CourseStatus,
  type Task,
  TaskStatus,
} from 'src/pages/dashboard/learning/courses/types';
import {
  canStartTask,
  isFirstTask,
} from 'src/pages/dashboard/learning/courses/utils';

type CourseTaskStatusIconProps = {
  task: Task;
  moduleIndex: number;
  course: Course;
};

const CourseTaskStatusIcon = ({
  task,
  moduleIndex,
  course,
}: CourseTaskStatusIconProps) => {
  if (!task) return null;

  const TaskStatusIcon = TASKS_STATUS_ICONS[task.status] as TablerIcon;

  const isCourseInProgress = course.status === CourseStatus.IN_PROGRESS;
  const isTaskPending = task.status === TaskStatus.PENDING;
  const isEvaluationTask = task.type === TaskTypes.EVALUATION;
  const isTheFirstTask = isFirstTask(moduleIndex, task.position);

  if (!course.isSequential) {
    if (task.status === TaskStatus.PENDING) return null;
    return <TaskStatusIcon />;
  }

  // Edge case: The user click on first task and the status for that task is not updated yet
  // so to show the correct icon we need to check if:
  // 1. The course changed from PENDING to IN_PROGRESS
  // 2. The task is the first task of the module
  // 3. The task is still PENDING
  if (isCourseInProgress && isTaskPending && isTheFirstTask) {
    const InProgressIcon = TASKS_STATUS_ICONS[TaskStatus.IN_PROGRESS];
    return <InProgressIcon />;
  }

  const userCanStartTask = canStartTask(
    course.modules,
    moduleIndex,
    task.position,
    course.isSequential,
  );

  if (userCanStartTask && isTaskPending) return null;

  // Edge case: the status not updated until the user start the evaluation
  // so to show the correct icon we need to check if:
  // 1. The task is an evaluation task
  // 2. The task is pending
  // 3. The user can start the task
  if (isEvaluationTask && isTaskPending && userCanStartTask) {
    const InProgressIcon = TASKS_STATUS_ICONS[TaskStatus.IN_PROGRESS];
    return <InProgressIcon />;
  }

  return <TaskStatusIcon />;
};

export default CourseTaskStatusIcon;
