import type { ScatterRequestOptions, ScatterResponse } 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,
  ScatterWidgetProps,
} from './types'

export const getScatter: ModelQueryFactory<
  ScatterWidgetProps,
  ScatterResponse
> = (args) =>
  getModelQueryOptions<ScatterWidgetProps, ScatterResponse>({
    queryKeyPrefix: ['scatter'],
    getWidgetMethod: (widgetModel) => (params) =>
      widgetModel.getScatter(params as ScatterRequestOptions),
    ...args,
  })

const { useModelHook: useScatterQuery } = createModel<
  ScatterWidgetProps,
  ScatterResponse
>({ buildQuery: getScatter })

/**
 * `useScatter` is a hook that creates scatter plot data for analyzing relationships between two numerical variables.
 * `ScatterModel` is the render-props component equivalent.
 *
 * @example
 * ```tsx
 * <ScatterModel
 *   accessToken={token}
 *   sourceId="my_source"
 *   widgetProps={{ xAxisColumn: 'income', yAxisColumn: 'spending' }}
 * >
 *   {({ data }) => <ScatterChart data={data} />}
 * </ScatterModel>
 * ```
 */
function useScatter<P extends ModelProps<ScatterWidgetProps, ScatterResponse>>(
  props: P,
): ModelHookResponse<P, ScatterResponse> {
  const { sourceId, sourcesId } = props
  const slices = useSourceSlices(sourceId ? [sourceId] : (sourcesId ?? []))
  return useScatterQuery(props, slices)
}

function ScatterModel<
  P extends ModelProps<ScatterWidgetProps, ScatterResponse>,
>(
  props: ModelComponentProps<ScatterWidgetProps, ScatterResponse, P>,
): React.ReactElement {
  return props.children(useScatter(props)) as React.ReactElement
}

export { useScatter, ScatterModel }
