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

import { StrictModeDroppable } from "./StrictModeDroppable";
import { AnswerItem } from "./AnswerItem";

import { updateVariants } from "@root/questions";

import { reorder } from "./helper";

import type { DropResult } from "react-beautiful-dnd";
import type { Variants } from "@root/questions";

type AnswerDraggableListProps = {
  variants: Variants[];
  totalIndex: number;
};

export const AnswerDraggableList = ({
  variants,
  totalIndex,
}: AnswerDraggableListProps) => {
  const onDragEnd = ({ destination, source }: DropResult) => {
    if (destination) {
      const newItems = reorder(variants, source.index, destination.index);

      updateVariants(totalIndex, newItems);
    }
  };

  return (
    <DragDropContext onDragEnd={onDragEnd}>
      <StrictModeDroppable droppableId="droppable-list">
        {(provided) => (
          <Box ref={provided.innerRef} {...provided.droppableProps}>
            {variants.map((variant, index) => (
              <AnswerItem
                key={variant.answer + index}
                index={index}
                totalIndex={totalIndex}
                variants={variants}
                variant={variant}
              />
            ))}
          </Box>
        )}
      </StrictModeDroppable>
    </DragDropContext>
  );
};
