import type {
  HistogramRequestOptions,
  HistogramResponse,
} 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 {
  HistogramWidgetProps,
  ModelComponentProps,
  ModelHookResponse,
  ModelProps,
} from './types'

export const getHistogram: ModelQueryFactory<
  HistogramWidgetProps,
  HistogramResponse
> = (args) =>
  getModelQueryOptions<HistogramWidgetProps, HistogramResponse>({
    queryKeyPrefix: ['histogram'],
    getWidgetMethod: (widgetModel) => (params) =>
      widgetModel.getHistogram(params as HistogramRequestOptions),
    ...args,
  })

const { useModelHook: useHistogramQuery } = createModel<
  HistogramWidgetProps,
  HistogramResponse
>({ buildQuery: getHistogram })

/**
 * `useHistogram` is a hook that creates frequency distributions of numerical data across value ranges.
 * `HistogramModel` is the render-props component equivalent.
 *
 * @example
 * ```tsx
 * <HistogramModel
 *   accessToken={token}
 *   sourceId="my_source"
 *   widgetProps={{ column: 'revenue', ticks: [0, 1000, 5000, 10000] }}
 * >
 *   {({ data }) => <HistogramChart data={data} />}
 * </HistogramModel>
 * ```
 */
function useHistogram<
  P extends ModelProps<HistogramWidgetProps, HistogramResponse>,
>(props: P): ModelHookResponse<P, HistogramResponse> {
  const { sourceId, sourcesId } = props
  const slices = useSourceSlices(sourceId ? [sourceId] : (sourcesId ?? []))
  return useHistogramQuery(props, slices)
}

function HistogramModel<
  P extends ModelProps<HistogramWidgetProps, HistogramResponse>,
>(
  props: ModelComponentProps<HistogramWidgetProps, HistogramResponse, P>,
): React.ReactElement {
  return props.children(useHistogram(props)) as React.ReactElement
}

export { useHistogram, HistogramModel }
