import type { Column, ColumnDef, Row, Table } from '@tanstack/react-table';
import { ArrowDown, ArrowUp, ArrowUpDown } from 'lucide-react';
import { Checkbox } from '@/components/ui/checkbox';
import { cn } from '@/lib/utils';

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

export function DataTableColumnHeader<TData, TValue>({
    column,
    title,
    className,
}: DataTableColumnHeaderProps<TData, TValue>) {
    if (!column.getCanSort()) {
        return <div className={cn(className)}>{title}</div>;
    }

    const sorted = column.getIsSorted();

    return (
        <button
            type="button"
            className={cn(
                '-ml-2 inline-flex items-center gap-1.5 rounded-md px-2 py-1 hover:bg-muted',
                sorted && 'text-foreground',
                className,
            )}
            onClick={column.getToggleSortingHandler()}
        >
            <span>{title}</span>
            {sorted === 'asc' ? (
                <ArrowUp className="size-3.5" />
            ) : sorted === 'desc' ? (
                <ArrowDown className="size-3.5" />
            ) : (
                <ArrowUpDown className="size-3.5 opacity-40" />
            )}
        </button>
    );
}

export function getSelectionColumn<TData>(): ColumnDef<TData> {
    return {
        id: 'select',
        size: 40,
        enableSorting: false,
        enableHiding: false,
        header: ({ table }: { table: Table<TData> }) => (
            <Checkbox
                checked={
                    table.getIsAllPageRowsSelected() ||
                    (table.getIsSomePageRowsSelected() && 'indeterminate')
                }
                onCheckedChange={(value) =>
                    table.toggleAllPageRowsSelected(!!value)
                }
                aria-label="Tout sélectionner"
            />
        ),
        cell: ({ row }: { row: Row<TData> }) => (
            <Checkbox
                checked={row.getIsSelected()}
                disabled={!row.getCanSelect()}
                onCheckedChange={(value) => row.toggleSelected(!!value)}
                aria-label="Sélectionner la ligne"
                onClick={(event) => event.stopPropagation()}
            />
        ),
    };
}
