import {
  DataTablaRowActionFunction,
  DataTableRowActions,
  DataTableRowDragHandleCell,
} from "@repo/rdx-ui/components";
import { Checkbox } from "@repo/shadcn-ui/components";
import { ColumnDef } from "@tanstack/react-table";

import { useId, useMemo } from "react";

// eslint-disable-next-line @typescript-eslint/no-unused-vars
export function useDetailColumns<TData>(
  columns: ReadonlyArray<ColumnDef<TData>>,
  {
    enableDragHandleColumn = false,
    enableSelectionColumn = false,
    enableActionsColumn = false,
    rowActionFn,
  }: {
    enableDragHandleColumn?: boolean;
    enableSelectionColumn?: boolean;
    enableActionsColumn?: boolean;
    rowActionFn?: DataTablaRowActionFunction<TData>;
  } = {}
): ColumnDef<TData>[] {
  const idPrefix = useId();

  return useMemo(() => {
    const baseColumns: ColumnDef<TData>[] = [...columns];

    if (enableDragHandleColumn) {
      baseColumns.unshift({
        id: "row_drag_handle",
        header: () => null,
        cell: (info) => <DataTableRowDragHandleCell rowId={info.row.id} />,
        enableSorting: false,
        enableHiding: false,
        size: 40,
      });
    }

    if (enableSelectionColumn) {
      baseColumns.unshift({
        id: "select",
        header: ({ table }) => (
          <Checkbox
            id={`${idPrefix}-select-all`}
            checked={
              table.getIsAllPageRowsSelected() ||
              (table.getIsSomePageRowsSelected() && "indeterminate")
            }
            onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
            aria-label='Seleccionar todo'
            className='translate-y-[0px]'
          />
        ),
        cell: ({ row }) => (
          <Checkbox
            id={`${idPrefix}-select-row-${row.id}`}
            checked={row.getIsSelected()}
            disabled={!row.getCanSelect()}
            onCheckedChange={row.getToggleSelectedHandler()}
            aria-label='Seleccionar fila'
            className='mt-2'
          />
        ),
        enableSorting: false,
        enableHiding: false,
        size: 40,
      });
    }

    if (enableActionsColumn) {
      const RowActionsCell = (props: any) => (
        <DataTableRowActions rowContext={props} actions={rowActionFn} />
      );

      baseColumns.push({
        id: "row_actions",
        header: () => null,
        cell: RowActionsCell,
        enableSorting: false,
        enableHiding: false,
        size: 48,
      });
    }

    return baseColumns;
  }, [
    columns,
    rowActionFn,
    idPrefix,
    enableDragHandleColumn,
    enableSelectionColumn,
    enableActionsColumn,
  ]);
}
