import React, { useState, useEffect } from "react";
import { DragDropContext, Droppable, Draggable } from "@hello-pangea/dnd";
import { useGetCategoryTreeQuery, useReorderCategoriesMutation } from "../../features/categories/categoryAPI";

const ReorderCategories = () => {
  const { data } = useGetCategoryTreeQuery();
  const [reorderCategories] = useReorderCategoriesMutation();
  const [categories, setCategories] = useState([]);

  const flattenCategories = (nodes, level = 0) => {
    let list = [];
    nodes.forEach((node) => {
      list.push({ ...node, level });
      if (node.children?.length) {
        list = list.concat(flattenCategories(node.children, level + 1));
      }
    });
    return list;
  };

  useEffect(() => {
    if (data?.data) setCategories(flattenCategories(data.data));
  }, [data]);

  const handleDragEnd = async (result) => {
    if (!result.destination) return;

    const reordered = Array.from(categories);
    const [moved] = reordered.splice(result.source.index, 1);
    reordered.splice(result.destination.index, 0, moved);

    setCategories(reordered);

    const updatedOrders = reordered.map((item, index) => ({
      id: item.id,
      sequence: index + 1,
    }));

    try {
      await reorderCategories(updatedOrders).unwrap();
      console.log("Category order updated!");
    } catch (err) {
      console.error("Failed to reorder:", err);
    }
  };

  return (
    <div className="p-6">
      <h2 className="text-xl font-semibold mb-4">Reorder Categories</h2>
      <DragDropContext onDragEnd={handleDragEnd}>
        <Droppable droppableId="categories">
          {(provided) => (
            <div {...provided.droppableProps} ref={provided.innerRef}>
              {categories.map((cat, index) => (
                <Draggable key={cat.id} draggableId={cat.id} index={index}>
                  {(provided) => (
                    <div
                      ref={provided.innerRef}
                      {...provided.draggableProps}
                      {...provided.dragHandleProps}
                      className="p-4 mb-2 border rounded-lg shadow-sm bg-white flex justify-between items-center"
                    >
                      <span>{"-".repeat(cat.level * 2)} {cat.name}</span>
                      <span className="text-gray-400 text-sm">Seq: {index + 1}</span>
                    </div>
                  )}
                </Draggable>
              ))}
              {provided.placeholder}
            </div>
          )}
        </Droppable>
      </DragDropContext>
    </div>
  );
};

export default ReorderCategories;
