import * as React from 'react'
import { useEffect, useMemo, useState } from 'react'
import { ModelPicker } from '../../components/ModelPicker.js'
import { Box, Text } from '../../ink.js'
import { Pane } from '../../components/design-system/Pane.js'
import { useAppState } from '../../state/AppState.js'
import { fetchRiosCloudModelCatalog } from '../../services/riosCloudModelCatalog.js'
import { buildRiOsCloudModelPickerOptions, type ModelOption } from '../../utils/model/modelOptions.js'
import { isRiOsGatewayAnthropicBaseUrl } from '../../utils/model/providers.js'
import type { EffortLevel } from '../../utils/effort.js'
import type { ModelSetting } from '../../utils/model/model.js'

export type RiOsCloudModelPickerFlowProps = {
  initial: string | null
  sessionModel?: ModelSetting
  onSelect: (model: string | null, effort: EffortLevel | undefined) => void
  onCancel?: () => void
  isStandaloneCommand?: boolean
  showFastModeNotice?: boolean
  headerText?: string
  skipSettingsWrite?: boolean
}

export function RiOsCloudModelPickerFlow(
  props: RiOsCloudModelPickerFlowProps,
): React.ReactNode {
  const isFastMode = useAppState(s => s.fastMode)
  const [catalogIds, setCatalogIds] = useState<string[] | null>(null)
  const [loadDone, setLoadDone] = useState(!isRiOsGatewayAnthropicBaseUrl())

  useEffect(() => {
    if (!isRiOsGatewayAnthropicBaseUrl()) {
      return
    }
    let cancelled = false
    void fetchRiosCloudModelCatalog().then(ids => {
      if (cancelled) {
        return
      }
      setCatalogIds(ids ?? [])
      setLoadDone(true)
    })
    return () => {
      cancelled = true
    }
  }, [])

  const riosCloudModelOptions = useMemo((): ModelOption[] | undefined => {
    if (!isRiOsGatewayAnthropicBaseUrl() || !catalogIds?.length) {
      return undefined
    }
    return buildRiOsCloudModelPickerOptions(catalogIds, isFastMode ?? false)
  }, [catalogIds, isFastMode])

  if (isRiOsGatewayAnthropicBaseUrl() && !loadDone) {
    return (
      <Pane color="permission">
        <Box marginBottom={1}>
          <Text dimColor>正在从 RiOS 云端加载可用模型列表…</Text>
        </Box>
      </Pane>
    )
  }

  return <ModelPicker {...props} riosCloudModelOptions={riosCloudModelOptions} />
}
