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 { ReactNode } from "react";
import type { DropResult } from "react-beautiful-dnd";
import type { QuestionVariant } from "../../../model/questionTypes/shared";

type AnswerDraggableListProps = {
  variants: QuestionVariant[];
  totalIndex: number;
  additionalContent?: (variant: QuestionVariant, index: number) => ReactNode;
  additionalMobile?: (variant: QuestionVariant, index: number) => ReactNode;
};

export const AnswerDraggableList = ({
  variants,
  totalIndex,
  additionalContent,
  additionalMobile,
}: 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}
                additionalContent={additionalContent?.(variant, index)}
                additionalMobile={additionalMobile?.(variant, index)}
              />
            ))}
            {provided.placeholder}
          </Box>
        )}
      </Droppable>
    </DragDropContext>
  );
};
