import { QueryableMongoCrudReturn } from "../trpc";
import { UseDataTableReturn, useDataTable } from "./use-data-table";
import { DataTableTransformer, PaginatedResponse, TData } from "../types";
import {
  FormKeyConfig,
  UseEditRecordModalReturn,
  useEditRecordModal,
} from "../edit-record";
import { Path } from "react-hook-form";
import { PaginationState } from "@tanstack/react-table";
import { useState, useMemo } from "react";

export interface UseAdminDataTableProps<T extends TData> {
  router: QueryableMongoCrudReturn<T>;
  transformer?: DataTableTransformer<T>;
}

export interface UseAdminDataTableReturn<T extends TData> {
  dataTableProps: UseDataTableReturn<T>;
  // editRecordProps: UseEditRecordModalReturn<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 });

  // TODO provide form overrides
  const formKeys: FormKeyConfig<T>[] = (Object.keys({} as T) as Path<T>[]).map(
    (key): FormKeyConfig<T> => ({
      key,
      label: key,
      type: "text",
      required: false,
      canEdit: true,
    })
  );

  // const editRecordProps = useEditRecordModal<T>({
  //   title: "Edit Record",
  //   mutationFn: router.update.useMutation,
  //   formKeys,
  // });

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