import { Box } from "@mui/material";
import { reorderQuestionsForm } from "@root/questions/actions";
import type { DropResult } from "react-beautiful-dnd";
import { DragDropContext, Droppable } from "react-beautiful-dnd";
import { FormDraggableListItem, FormItem } from "./FormDraggableListItem";
import { useQuestions } from "@root/questions/hooks";

export const FormDraggableList = () => {
  const questions = useQuestions().questions.filter((q) => q.type !== "result");
  const onDragEnd = ({ destination, source }: DropResult) => {
    if (destination) {
      reorderQuestionsForm(source.index, destination.index);
    }
  };

  return (
    <Box>
      {questions[0] && <FormItem question={questions[0]} questionIndex={0} />}
      <DragDropContext onDragEnd={onDragEnd}>
        <Droppable droppableId="droppable-list">
          {(provided) => (
            <Box ref={provided.innerRef} {...provided.droppableProps}>
              {questions
                ?.slice(1)
                .map((question, index) => (
                  <FormDraggableListItem
                    key={question.id}
                    question={question}
                    questionIndex={index + 1}
                  />
                ))}
              {provided.placeholder}
            </Box>
          )}
        </Droppable>
      </DragDropContext>
    </Box>
  );
};
