import { useEffect } from "react";
import { Box } from "@mui/material";
import { reorderQuestions } from "@root/questions/actions";
import type { DropResult } from "react-beautiful-dnd";
import { DragDropContext, Droppable } from "react-beautiful-dnd";
import DraggableListItem from "./DraggableListItem";
import { useQuestions } from "@root/questions/hooks";
import { createUntypedQuestion } from "@root/questions/actions";
import { useCurrentQuiz } from "@root/quizes/hooks";

interface Props {
  openBranchingPage: boolean;
  setOpenBranchingPage: (a: boolean) => void;
}

export const DraggableList = ({
  openBranchingPage,
  setOpenBranchingPage,
}: Props) => {
  const quiz = useCurrentQuiz();
  const { isLoading, questions } = useQuestions();
  const filteredQuestions = questions.filter(
    (question) => question.type !== "result",
  );
  const onDragEnd = ({ destination, source }: DropResult) => {
    if (destination) reorderQuestions(source.index, destination.index);
  };

  useEffect(() => {
    if (!isLoading && quiz && !filteredQuestions.length) {
      createUntypedQuestion(Number(quiz.backendId));
    }
  }, [quiz, filteredQuestions]);

  return (
    <DragDropContext onDragEnd={onDragEnd}>
      <Droppable droppableId="droppable-list">
        {(provided, snapshot) => (
          <Box ref={provided.innerRef} {...provided.droppableProps}>
            {filteredQuestions.map((question, index) => (
              <DraggableListItem
                openBranchingPage={openBranchingPage}
                setOpenBranchingPage={setOpenBranchingPage}
                key={question.id}
                question={question}
                isDragging={snapshot.isDraggingOver}
                index={index}
              />
            ))}
            {provided.placeholder}
          </Box>
        )}
      </Droppable>
    </DragDropContext>
  );
};
