'use client';
import { flexRender } from '@tanstack/react-table';
import { TableHead, TableHeader as ShadTableHeader, TableRow } from '@/components/ui/table';
import { Table } from '@tanstack/react-table';
import { ArrowDownWideNarrow, ArrowUpDown, ArrowUpNarrowWide } from 'lucide-react';
import { cn } from '@/lib/utils';

const TableHeader = <TData, _>({ table }: { table: Table<TData> }) => {
  return (
    <ShadTableHeader className="sticky top-0 z-10 bg-card">
      {table.getHeaderGroups().map((headerGroup) => (
        <TableRow key={headerGroup.id}>
          {headerGroup.headers.map((header) => {
            const canSort = header.column.getCanSort();
            const sortDirection = header.column.getIsSorted();
            const SortIcon =
              sortDirection === 'asc'
                ? ArrowUpNarrowWide
                : sortDirection === 'desc'
                  ? ArrowDownWideNarrow
                  : ArrowUpDown;

            return (
              <TableHead
                key={header.id}
                onClick={canSort ? header.column.getToggleSortingHandler() : undefined}
                className={cn(
                  'h-10 bg-card px-2 text-foreground transition-colors',
                  canSort && 'cursor-pointer select-none hover:bg-muted/60',
                  sortDirection && 'bg-muted/70',
                )}
              >
                {header.isPlaceholder ? null : (
                  <div className="flex min-h-8 w-full items-center justify-between gap-2">
                    <span className="truncate">
                      {flexRender(header.column.columnDef.header, header.getContext())}
                    </span>
                    {canSort ? (
                      <SortIcon
                        className={cn(
                          'size-3.5 shrink-0 transition-colors',
                          sortDirection ? 'text-foreground' : 'text-muted-foreground/60',
                        )}
                      />
                    ) : null}
                  </div>
                )}
              </TableHead>
            );
          })}
        </TableRow>
      ))}
    </ShadTableHeader>
  );
};

export default TableHeader;
