'use client';

import { cn } from '@/lib/utils/cn';

type Props = {
  label: string;
  index: number;
  dragging: boolean;
  over: boolean;
  onDragStart: (index: number, e: React.DragEvent) => void;
  onDragOver: (index: number, e: React.DragEvent) => void;
  onDrop: (index: number, e: React.DragEvent) => void;
  onDragEnd: () => void;
  /**
   * HUB-612: the column sorts the list when its header is clicked. `sorted` is the current
   * direction when the list is sorted by this column. Lists that leave it out are unchanged.
   */
  sort?: { sorted: 'asc' | 'desc' | null; onSort: () => void };
};

/** Table `<th>` that can be dragged to reorder columns in the list (and clicked to sort). */
export function DraggableColumnHeader({
  label,
  index,
  dragging,
  over,
  onDragStart,
  onDragOver,
  onDrop,
  onDragEnd,
  sort,
}: Props) {
  return (
    <th
      scope="col"
      className={cn(
        'crm-th-draggable',
        dragging && 'is-dragging',
        over && !dragging && 'is-drag-over',
        sort && 'crm-th-sortable',
        sort?.sorted && 'is-sorted',
      )}
      aria-sort={
        sort?.sorted === 'asc' ? 'ascending' : sort?.sorted === 'desc' ? 'descending' : undefined
      }
      draggable
      onDragStart={(e) => onDragStart(index, e)}
      onDragOver={(e) => onDragOver(index, e)}
      onDrop={(e) => onDrop(index, e)}
      onDragEnd={onDragEnd}
      title={`Drag to reorder “${label}”`}
    >
      {sort ? (
        <button
          type="button"
          className="crm-th-sort"
          onClick={sort.onSort}
          title={`Sort by ${label}`}
        >
          <span className="crm-th-draggable__label">{label}</span>
          <svg
            className="crm-th-sort__icon"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="2"
            strokeLinecap="round"
            strokeLinejoin="round"
            aria-hidden
          >
            {sort.sorted === 'asc' ? (
              <path d="m7 14 5-5 5 5" />
            ) : sort.sorted === 'desc' ? (
              <path d="m7 10 5 5 5-5" />
            ) : (
              <path d="m8 9 4-4 4 4M8 15l4 4 4-4" />
            )}
          </svg>
        </button>
      ) : (
        <span className="crm-th-draggable__label">{label}</span>
      )}
    </th>
  );
}
