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 DataTableColumnHeaderProps<TData, TValue>
  extends React.HTMLAttributes<HTMLDivElement> {
  column: Column<TData, TValue>
}

export function DataTableColumnHeader<TData, TValue>({
  column,
  className
}: DataTableColumnHeaderProps<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="ghost"
      size="sm"
      className={cn('-ml-3 cursor-pointer', className)}
      onClick={() => column.toggleSorting(column.getIsSorted() === 'asc')}
    >
      <span>{title}</span>
      {column.getIsSorted() === 'desc' ? (
        <ChevronDownIcon />
      ) : column.getIsSorted() === 'asc' ? (
        <ChevronUpIcon />
      ) : (
        <ChevronsUpDownIcon />
      )}
    </Button>
  )
}
