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

import { AnswerItem } from "./AnswerItem";

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

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

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



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

  const onDragEnd = ({ destination, source }: DropResult) => {
    if (destination) {
      reorderVariants(quizId, totalIndex, source.index, destination.index);
    }
  };

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