"use client"

import type { Column } from "@tanstack/react-table"
import { cn } from "@/lib/utils"
import { ArrowDownIcon, ArrowUpDownIcon, ArrowUpIcon } from "lucide-react"

interface DataGridSortHeaderProps<TData> {
  column: Column<TData, unknown>
  title: string
  className?: string
}

function DataGridSortHeader<TData>({
  column,
  title,
  className,
}: DataGridSortHeaderProps<TData>) {
  const sorted = column.getIsSorted()
  const canSort = column.getCanSort()

  if (!canSort) {
    return (
      <span className={cn("text-xs font-medium text-muted-foreground", className)}>
        {title}
      </span>
    )
  }

  return (
    <button
      type="button"
      className={cn(
        "inline-flex items-center gap-1.5 text-xs font-medium text-muted-foreground",
        "hover:text-foreground transition-colors rounded-md -ml-1 px-1 py-0.5",
        className,
      )}
      onClick={column.getToggleSortingHandler()}
    >
      {title}
      {sorted === "asc" ? (
        <ArrowUpIcon className="size-3 text-foreground" />
      ) : sorted === "desc" ? (
        <ArrowDownIcon className="size-3 text-foreground" />
      ) : (
        <ArrowUpDownIcon className="size-3 opacity-35" />
      )}
    </button>
  )
}

export { DataGridSortHeader, type DataGridSortHeaderProps }
