import Stack from '@material-hu/mui/Stack';

import { TASKS_ICONS } from '@material-hu/components/composed-components/learning';
import HuListItem from '@material-hu/components/design-system/List/components/ListItem';
import HuTooltip from '@material-hu/components/design-system/Tooltip';

import useStartCourse from 'src/pages/dashboard/learning/courses/hooks/useStartCourse';
import {
  type Course,
  type Task,
  TaskStatus,
} from 'src/pages/dashboard/learning/courses/types';
import { canStartTask } from 'src/pages/dashboard/learning/courses/utils';
import { useLokaliseTranslation } from 'src/utils/i18n';

import CourseTaskStatusIcon from './CourseTaskStatusIcon';

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

const CourseTask = ({ task, course, moduleIndex }: CourseTaskProps) => {
  const { t } = useLokaliseTranslation('learning');
  const { handleStartCourse } = useStartCourse(course);

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

  const handleStartTask = () => {
    if (!userCanStartTask) return;

    handleStartCourse(task);
  };

  const getTooltipTitle = () => {
    if (!userCanStartTask) return t('course.lesson.blocked');

    if (task.status === TaskStatus.IN_PROGRESS)
      return t('course.lesson.in_progress');

    return t('course.lesson.completed');
  };

  const tooltipDescription = !userCanStartTask
    ? t('course.lesson.blocked_description')
    : undefined;

  return (
    <HuListItem
      disabled={!userCanStartTask}
      key={task.id}
      component="button"
      onClick={handleStartTask}
      sx={{
        '& > button': {
          p: 0,
          px: 2,
          py: 0.5,
        },
        '& .Mui-disabled': {
          pointerEvents: 'all',
        },
      }}
      avatar={{ Icon: TASKS_ICONS[task.type] }}
      text={{ title: task.title }}
      sideContent={
        <Stack sx={{ flexDirection: 'row', gap: 2 }}>
          <HuTooltip
            title={getTooltipTitle()}
            description={tooltipDescription}
          >
            <span>
              <CourseTaskStatusIcon
                task={task}
                course={course}
                moduleIndex={moduleIndex}
              />
            </span>
          </HuTooltip>
        </Stack>
      }
    />
  );
};

export default CourseTask;
