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

import { AnswerItem } from "./AnswerItem";

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

import { reorder } from "./helper";

import type { DropResult } from "react-beautiful-dnd";
import type { QuestionVariant } from "../../../model/questionTypes/shared";

type AnswerDraggableListProps = {
  variants: QuestionVariant[];
  totalIndex: number;
  emoji?: boolean;
};

export const AnswerDraggableList = ({
  variants,
  totalIndex,
  emoji = false,
}: AnswerDraggableListProps) => {
  const quizId = Number(useParams().quizId);

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

      updateVariants(quizId, totalIndex, newItems);
    }
  };

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