import { type Column } from '@tanstack/react-table'
import {
  ChevronDownIcon,
  ChevronsUpDownIcon,
  ChevronUpIcon
} from 'lucide-react'

import { Button } from '@repo/ui/components/ui/button'
import { cn } from '@repo/ui/lib/utils'

interface DataTableColumnHeaderSortProps<TData, TValue>
  extends React.HTMLAttributes<HTMLDivElement> {
  column: Column<TData, TValue>
}

export function DataTableColumnHeaderSort<TData, TValue>({
  column,
  className
}: DataTableColumnHeaderSortProps<TData, TValue>) {
  // @ts-ignore
  const title = column.columnDef?.meta?.title ?? column.id

  if (!column.getCanSort()) {
    return <div className={cn(className)}>{title}</div>
  }

  return (
    <Button
      variant="link"
      size="sm"
      className={cn('-ml-3 cursor-pointer text-inherit h-auto', className)}
      onClick={() => column.toggleSorting(column.getIsSorted() === 'asc')}
    >
      <span>{title}</span>

      {column.getIsSorted() === 'desc' ? (
        <ChevronDownIcon />
      ) : column.getIsSorted() === 'asc' ? (
        <ChevronUpIcon />
      ) : (
        <ChevronsUpDownIcon />
      )}
    </Button>
  )
}
