import { useEffect, useState } from "react";
import { Box } from "@mui/material";
import { DragDropContext } from "react-beautiful-dnd";

import { StrictModeDroppable } from "./StrictModeDroppable";
import { DraggableListItem } from "./DraggableListItem";

import { reorder } from "./helper";

import type { DropResult } from "react-beautiful-dnd";
import type { Quizes } from "../../../stores/quizes";

export type ExtendedQuizes = Quizes & {
  onDelete: () => void;
};

type DraggableListProps = {
  items: ExtendedQuizes[];
};

export const DraggableList = ({ items }: DraggableListProps) => {
  const [listItems, setListItems] = useState(items);

  useEffect(() => {
    setListItems(items);
  }, [items]);

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

      setListItems(newItems);
    }
  };

  return (
    <DragDropContext onDragEnd={onDragEnd}>
      <StrictModeDroppable droppableId="droppable-list">
        {(provided) => (
          <Box ref={provided.innerRef} {...provided.droppableProps}>
            {listItems.map(({ onDelete }, index) => (
              <DraggableListItem
                key={index}
                index={index}
                onDelete={onDelete}
              />
            ))}
            {provided.placeholder}
          </Box>
        )}
      </StrictModeDroppable>
    </DragDropContext>
  );
};
