import { type CSSProperties } from 'react';

import { useSortable } from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import Stack from '@material-hu/mui/Stack';

import { CourseInsertPosition } from 'src/pages/dashboard/Learning/Paths/types';

import { type PathCourse } from '../../../types';

import CourseDivider from './CourseDivider';
import CoursesListItem from './CoursesListItem';

type CoursesSortableListItemProps = {
  course: PathCourse;
  index: number;
  activeIndex: number;
};

const CoursesSortableListItem = ({
  course,
  index,
  activeIndex,
}: CoursesSortableListItemProps) => {
  const {
    attributes,
    listeners,
    transform,
    transition,
    over,
    isDragging,
    setNodeRef,
    setActivatorNodeRef,
  } = useSortable({ id: course.courseId });

  const styles: CSSProperties = {
    transform: CSS.Transform.toString(transform),
    transition,
    position: 'relative',
    visibility: isDragging ? 'hidden' : 'visible',
  };

  const getInsertPosition = () => {
    if (over?.id === course.courseId) {
      return index > activeIndex
        ? CourseInsertPosition.AFTER
        : CourseInsertPosition.BEFORE;
    }
    return undefined;
  };

  const position = getInsertPosition();
  const showBeforeDivider = position === CourseInsertPosition.BEFORE;
  const showAfterDivider = position === CourseInsertPosition.AFTER;

  return (
    <Stack sx={{ position: 'relative' }}>
      <CourseDivider
        position="before"
        show={showBeforeDivider}
      />
      <CoursesListItem
        ref={setNodeRef}
        course={course}
        styles={styles}
        {...setActivatorNodeRef}
        {...attributes}
        {...listeners}
      />
      <CourseDivider
        position="after"
        show={showAfterDivider}
      />
    </Stack>
  );
};

export default CoursesSortableListItem;
