import { Checkbox } from "@repo/shadcn-ui/components";
import type { ColumnDef } from "@tanstack/react-table";
import * as React from "react";

// Columna estable (definida una vez)
const selectionCol: ColumnDef<any, unknown> = {
    id: "select",
    header: ({ table }) => (
        <Checkbox
            checked={table.getIsAllPageRowsSelected() || (table.getIsSomePageRowsSelected() && "indeterminate")}
            onCheckedChange={(v) => table.toggleAllPageRowsSelected(!!v)}
            aria-label="Select all"
            className="translate-y-[2px]"
        />
    ),
    cell: ({ row }) => (
        <Checkbox
            checked={row.getIsSelected()}
            onCheckedChange={(v) => row.toggleSelected(!!v)}
            aria-label="Select row"
            className="translate-y-[2px]"
        />
    ),
    enableSorting: false,
    enableHiding: false,
    size: 36, minSize: 36, maxSize: 36,
};

// Función pura (sin hooks)
export function withRowSelection<T>(
    base: ColumnDef<T, unknown>[],
    enabled: boolean
): ColumnDef<T, unknown>[] {
    if (!enabled) return base; // misma referencia si está desactivado
    // Evita duplicar si ya viene incluida
    if (base.length > 0 && base[0].id === selectionCol.id) return base;
    return [selectionCol as ColumnDef<T, unknown>, ...base];
}

// Custom hook ergonómico
export function useWithRowSelection<T>(
    baseColumns: ColumnDef<T, unknown>[],
    enabled: boolean
) {
    return React.useMemo(
        () => withRowSelection(baseColumns, enabled),
        [baseColumns, enabled]
    );
}
