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


export const DraggableList = () => {
    const { questions, isLoading } = useQuestions();

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

    if (isLoading && !questions) return <Box>Загрузка вопросов...</Box>;

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