import { QueryableMongoCrudReturn } from "../trpc";
import { UseDataTableReturn } from "./use-data-table";
import { DataTableTransformer, TData } from "../types";
import { PaginationState } from "@tanstack/react-table";
import { useState, useMemo } from "react";

export interface UseAdminDataTableProps<T extends TData> {
  /**
   * Generate tRPC router to use for data table population
   */
  router: QueryableMongoCrudReturn<T>;
  /**
   * (optional) Transformer to use for data table population
   */
  transformer?: DataTableTransformer<T>;
}

export interface UseAdminDataTableReturn<T extends TData> {
  dataTableProps: UseDataTableReturn<T>;
}

export const useAdminDataTable = <T extends TData>({
  router,
  transformer,
}: UseAdminDataTableProps<T>): UseAdminDataTableReturn<T> => {
  const [{ pageIndex, pageSize }, onPaginationChange] =
    useState<PaginationState>({
      pageIndex: 0,
      pageSize: 10,
    });
  const pagination = useMemo<PaginationState>(
    () => ({ pageIndex, pageSize }),
    [pageIndex, pageSize]
  );
  const queryResponse = router.get.useQuery({ pageIndex, pageSize });

  return {
    dataTableProps: {
      pagination,
      onPaginationChange,
      queryResponse,
      transformer,
    },
  };
};
