import { Box } from "@mui/material";
import { DragDropContext } from "react-beautiful-dnd";

import { StrictModeDroppable } from "./StrictModeDroppable";
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 { listQuestions } = questionStore();

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

      updateQuestionsListDragAndDrop(newItems);
    }
  };

  return (
    <DragDropContext onDragEnd={onDragEnd}>
      <StrictModeDroppable droppableId="droppable-list">
        {(provided, snapshot) => (
          <Box ref={provided.innerRef} {...provided.droppableProps}>
            {listQuestions.map((_, index) => (
              <DraggableListItem
                key={index}
                index={index}
                activePlus={snapshot.isDraggingOver}
              />
            ))}
            {provided.placeholder}
          </Box>
        )}
      </StrictModeDroppable>
    </DragDropContext>
  );
};
