import type { Column } from '@tanstack/react-table';
import { ArrowDown, ArrowUp, ArrowUpDown } from 'lucide-react';
import { cn } from '@/lib/utils';

type Props<TData> = {
    column: Column<TData, unknown>;
    title: string;
    className?: string;
};

export function DataTableColumnHeader<TData>({
    column,
    title,
    className,
}: Props<TData>) {
    // `column` garde la même référence quand le tri change : sans cette directive,
    // le compilateur React figerait la flèche et empêcherait d'inverser le tri.
    'use no memo';

    if (!column.getCanSort()) {
        return (
            <span className={cn('text-sm font-medium', className)}>
                {title}
            </span>
        );
    }

    const sorted = column.getIsSorted();

    return (
        <button
            type="button"
            className={cn(
                'inline-flex items-center gap-1.5 text-sm font-medium transition-colors hover:text-foreground',
                sorted ? 'text-foreground' : 'text-muted-foreground',
                className,
            )}
            onClick={() => column.toggleSorting(sorted === 'asc')}
        >
            <span>{title}</span>
            {sorted === 'desc' ? (
                <ArrowDown className="size-3.5" />
            ) : sorted === 'asc' ? (
                <ArrowUp className="size-3.5" />
            ) : (
                <ArrowUpDown className="size-3.5 opacity-50" />
            )}
        </button>
    );
}
