"use client";

import { useRef, useState } from "react";

interface DraggableTableRowProps {
  id: string;
  /** Shared ref across all rows in the table — holds the ID currently being dragged. */
  dragRef: React.MutableRefObject<string | null>;
  /**
   * Called when another row is dropped onto this row.
   * Receives the ID of the row that was dragged (not this row's ID).
   */
  onDrop: (draggedId: string) => void;
  children: React.ReactNode;
  className?: string;
  style?: React.CSSProperties;
}

/**
 * Table row with a left-side drag handle for manual row reordering.
 *
 * Usage: replace <tr> with <DraggableTableRow>, add <th className="w-8 px-2" /> as the
 * first header cell. Each table shares one dragRef (useRef<string | null>(null)).
 */
export function DraggableTableRow({
  id,
  dragRef,
  onDrop,
  children,
  className = "",
  style,
}: DraggableTableRowProps) {
  const [isDragOver, setIsDragOver] = useState(false);

  return (
    <tr
      style={style}
      className={`${className} ${isDragOver ? "border-t-2 border-brand-400" : ""}`}
      onDragOver={(e) => {
        e.preventDefault();
        if (dragRef.current && dragRef.current !== id) setIsDragOver(true);
      }}
      onDragLeave={() => setIsDragOver(false)}
      onDrop={(e) => {
        e.preventDefault();
        setIsDragOver(false);
        if (dragRef.current && dragRef.current !== id) {
          // Pass the dragged ID so the caller knows what moved where
          onDrop(dragRef.current);
        }
        dragRef.current = null;
      }}
    >
      {/* Drag handle — left-most cell */}
      <td
        draggable
        onDragStart={(e) => {
          dragRef.current = id;
          // Semi-transparent ghost
          e.dataTransfer.effectAllowed = "move";
        }}
        onDragEnd={() => {
          dragRef.current = null;
          setIsDragOver(false);
        }}
        className="w-8 px-2 py-3 cursor-grab active:cursor-grabbing select-none text-gray-300 hover:text-gray-400 text-center"
        title="Drag to reorder"
      >
        ⠿
      </td>
      {children}
    </tr>
  );
}
