import { useState } from "react";
import { useParams } from "react-router-dom";
import { Box } from "@mui/material";
import { DragDropContext, Droppable } from "react-beautiful-dnd";

import { DraggableListItem } from "./DraggableListItem";

import { questionStore, updateQuestionsListDragAndDrop } from "@root/questions";

import { reorder } from "./helper";

import type { DropResult } from "react-beautiful-dnd";

export const DraggableList = () => {
  const quizId = Number(useParams().quizId);
  const { listQuestions } = questionStore();

  const onDragEnd = ({ destination, source }: DropResult) => {
    if (destination) {
      const newItems = reorder(
        listQuestions[quizId],
        source.index,
        destination.index
      );

      updateQuestionsListDragAndDrop(quizId, newItems);
    }
  };

  return (
    <DragDropContext onDragEnd={onDragEnd}>
      <Droppable droppableId="droppable-list">
        {(provided, snapshot) => (
          <Box ref={provided.innerRef} {...provided.droppableProps}>
            {listQuestions[quizId]?.map(({ id }, index) => (
              <DraggableListItem
                key={id}
                index={index}
                isDragging={snapshot.isDraggingOver}
              />
            ))}
            {provided.placeholder}
          </Box>
        )}
      </Droppable>
    </DragDropContext>
  );
};
