import { useNavigate } from 'react-router';

import { IconType } from '@material-hu/types/icons';

import { TASKS_ICONS } from '@material-hu/components/composed-components/learning';
import HuSubSidebar from '@material-hu/components/composed-components/SubSidebar';
import { type SubSidebarSectionProps as SubSidebarSection } from '@material-hu/components/composed-components/SubSidebar/types';

import useIds from '../../../hooks/useIds';
import useRoutes from '../../../hooks/useRoutes';
import CourseTaskStatusIcon from '../../Detail/components/content/CourseTaskStatusIcon';
import { type Course } from '../../types';
import { canStartTask, getModuleByTaskId } from '../../utils';

type TasksSidebarProps = {
  course: Course | undefined;
  loading: boolean;
  hide: boolean;
};

const TasksSidebar = ({ course, hide, loading }: TasksSidebarProps) => {
  const navigate = useNavigate();
  const routes = useRoutes();
  const { taskId: selectedTaskId, tag: selectedTag } = useIds();

  if (hide || !course) return null;

  const accordionSections: SubSidebarSection[] = course?.modules.map(
    (module, moduleIndex) => ({
      title: module.title,
      value: module.id,
      avatar: {
        text:
          module.icon.type === IconType.EMOJI ? module.icon.value : undefined,
        src:
          module.icon.type === IconType.IMAGE ? module.icon.value : undefined,
      },
      items: module.tasks.map((task, taskIndex) => {
        const userCanStartTask = canStartTask(
          course.modules,
          moduleIndex,
          taskIndex,
          course.isSequential,
        );
        return {
          text: { title: task.title, withEllipsis: true, overflow: 'tooltip' },
          value: `${task.id}+${task.tag}`,
          disabled: !userCanStartTask,
          avatar: { Icon: TASKS_ICONS[task.type] },
          selected: selectedTaskId === task.id && selectedTag === task.tag,
          sideContent: (
            <CourseTaskStatusIcon
              task={task}
              course={course}
              moduleIndex={moduleIndex}
            />
          ),
        };
      }),
    }),
  );

  const handleChange = (lesson: string | number) => {
    const [taskId, tag] = (lesson as string).split('+');
    const parsedTaskId = parseInt(taskId);
    if (Number.isNaN(parsedTaskId)) return;

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

  const selectedModule = getModuleByTaskId(course, selectedTaskId);

  const defaultOpenAccordions = selectedModule ? [selectedModule?.id] : [];

  return (
    <HuSubSidebar
      isCollapsible
      onChange={handleChange}
      isLoading={loading}
      accordionSections={accordionSections}
      defaultOpenAccordions={defaultOpenAccordions}
      sx={{
        backgroundColor: ({ palette }) =>
          palette.new.background.layout.tertiary,
        '& .MuiAccordionSummary-content > div > div': {
          '& > .MuiStack-root > .MuiTypography-root': {
            width: '100%',
            display: '-webkit-box',
            overflow: 'hidden',
            WebkitBoxOrient: 'vertical',
            WebkitLineClamp: 2,
            WebkitBoxFlex: '1',
          },
        },
      }}
    />
  );
};

export default TasksSidebar;
