import type { TableRequestOptions, TableResponse } from '@carto/api-client'
import { createModel, type ModelQueryFactory } from './utils/create-model'
import { getModelQueryOptions } from './utils/get-model-query-options'
import { useSourceSlices } from './utils/use-source-slices'
import type {
  ModelComponentProps,
  ModelHookResponse,
  ModelProps,
  TableWidgetProps,
} from './types'

export const getTable: ModelQueryFactory<TableWidgetProps, TableResponse> = (
  args,
) =>
  getModelQueryOptions<TableWidgetProps, TableResponse>({
    queryKeyPrefix: ['table'],
    getWidgetMethod: (widgetModel) => (params) =>
      widgetModel.getTable(params as TableRequestOptions),
    ...args,
  })

const { useModelHook: useTableQuery } = createModel<
  TableWidgetProps,
  TableResponse
>({ buildQuery: getTable })

/**
 * `useTable` is a hook that retrieves tabular data with pagination support for displaying detailed records.
 * `TableModel` is the render-props component equivalent.
 *
 * @example
 * ```tsx
 * <TableModel
 *   accessToken={token}
 *   sourceId="my_source"
 *   widgetProps={{ columns: ['name', 'revenue', 'city'], sortBy: 'revenue', sortDirection: 'desc' }}
 * >
 *   {({ data }) => <DataGrid rows={data?.rows} />}
 * </TableModel>
 * ```
 */
function useTable<P extends ModelProps<TableWidgetProps, TableResponse>>(
  props: P,
): ModelHookResponse<P, TableResponse> {
  const { sourceId, sourcesId } = props
  const slices = useSourceSlices(sourceId ? [sourceId] : (sourcesId ?? []))
  return useTableQuery(props, slices)
}

function TableModel<P extends ModelProps<TableWidgetProps, TableResponse>>(
  props: ModelComponentProps<TableWidgetProps, TableResponse, P>,
): React.ReactElement {
  return props.children(useTable(props)) as React.ReactElement
}

export { useTable, TableModel }
