"use client";

import { useState } from "react";
import { DragDropProvider } from "@dnd-kit/react";
import { useSortable } from "@dnd-kit/react/sortable";
import { move } from "@dnd-kit/helpers";
import type { ToolEntry } from "@/lib/types";
import { ToolTile } from "./ToolTile";

interface ToolGridProps {
  tools: ToolEntry[];
  order: string[];
  onEditTool: (tool: ToolEntry) => void;
  onReorder: (order: string[]) => void;
}

function SortableToolTile({
  tool,
  index,
  onEdit,
}: {
  tool: ToolEntry;
  index: number;
  onEdit: (tool: ToolEntry) => void;
}) {
  const { ref, isDragging } = useSortable({
    id: tool.id,
    index,
  });

  return (
    <div
      ref={ref}
      className={`transition-opacity ${isDragging ? "opacity-50" : ""}`}
      style={{ touchAction: "none" }}
    >
      <ToolTile tool={tool} onEdit={onEdit} />
    </div>
  );
}

function sortTools(tools: ToolEntry[], order: string[]): ToolEntry[] {
  const toolMap = new Map(tools.map((t) => [t.id, t]));
  const sorted: ToolEntry[] = [];

  for (const id of order) {
    const tool = toolMap.get(id);
    if (tool) {
      sorted.push(tool);
      toolMap.delete(id);
    }
  }

  for (const tool of toolMap.values()) {
    sorted.push(tool);
  }

  return sorted;
}

export function ToolGrid({
  tools,
  order,
  onEditTool,
  onReorder,
}: ToolGridProps) {
  const sortedTools = sortTools(tools, order);
  const [items, setItems] = useState<string[]>(() => sortedTools.map((t) => t.id));

  const currentIds = sortedTools.map((t) => t.id);
  const itemsKey = currentIds.join(",");
  const [prevKey, setPrevKey] = useState(itemsKey);
  if (itemsKey !== prevKey) {
    setItems(currentIds);
    setPrevKey(itemsKey);
  }

  const toolMap = new Map(tools.map((t) => [t.id, t]));
  const orderedTools = items
    .map((id) => toolMap.get(id))
    .filter((t): t is ToolEntry => t !== undefined);

  return (
    <DragDropProvider
      onDragEnd={(event) => {
        const newItems = move(items, event);
        setItems(newItems);
        onReorder(newItems);
      }}
    >
      <div className="grid grid-cols-2 gap-4 p-4 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6">
        {orderedTools.map((tool, index) => (
          <SortableToolTile
            key={tool.id}
            tool={tool}
            index={index}
            onEdit={onEditTool}
          />
        ))}
      </div>
    </DragDropProvider>
  );
}
