import { useState } from "react";
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 [draggableId, setDraggableId] = useState<number>(-1);
  const [dropPlaceIndex, setDropPlaceIndex] = useState<number>(-1);
  const { listQuestions } = questionStore();

  const onDrop = () => {
    setDraggableId(-1);
    setDropPlaceIndex(-1);
  };

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

      updateQuestionsListDragAndDrop(newItems);
    }
  };

  return (
    <DragDropContext
      onDragStart={({ draggableId }) => setDraggableId(Number(draggableId))}
      onDragUpdate={({ destination }) => {
        setDropPlaceIndex(destination?.index ?? -1);
      }}
      onDragEnd={onDragEnd}
    >
      <StrictModeDroppable droppableId="droppable-list">
        {(provided) => (
          <Box
            ref={provided.innerRef}
            {...provided.droppableProps}
            onMouseUp={onDrop}
          >
            {listQuestions.map((_, index) => (
              <DraggableListItem
                key={index}
                index={index}
                dropPlaceIndex={
                  dropPlaceIndex < draggableId
                    ? dropPlaceIndex - 1
                    : dropPlaceIndex
                }
              />
            ))}
            {provided.placeholder}
          </Box>
        )}
      </StrictModeDroppable>
    </DragDropContext>
  );
};
