import { useDialog } from "@tui/ui/dialog"
import { DialogSelect, type DialogSelectOption } from "@tui/ui/dialog-select"
import { DialogPrompt } from "@tui/ui/dialog-prompt"
import { useSync } from "@tui/context/sync"
import { useToast } from "@tui/ui/toast"
import type { IndexingConfig } from "@saeeol/sdk/v2"
import {
  type EmbeddingProvider,
  type SubDialogProps,
  PROVIDER_LABELS,
  PROVIDER_FIELDS,
  defaultIndexing,
  getIndexing,
  hasSaeeolAuth,
  saeeolModel,
  saveIndexing,
} from "./dialog-indexing-helpers"

function ProviderSelect(props: SubDialogProps & { goBack: () => void }) {
  const dialog = useDialog()
  const sync = useSync()
  const sdk = props.useSDK()
  const toast = useToast()
  const indexing = defaultIndexing(sync)

  const options: DialogSelectOption<EmbeddingProvider>[] = (
    Object.entries(PROVIDER_LABELS) as [EmbeddingProvider, string][]
  )
    .filter(([v]) => v !== "saeeol" || hasSaeeolAuth(sync) || indexing.provider === "saeeol")
    .map(([value, title]) => ({
      value,
      title,
      description: value === indexing.provider ? "(current)" : undefined,
    }))

  return (
    <DialogSelect
      title="Embedding Provider"
      options={options}
      current={indexing.provider}
      onSelect={async (option) => {
        const provider = option.value
        const current = getIndexing(sync)
        const updated: IndexingConfig =
          provider === "saeeol"
            ? { ...current, provider, model: saeeolModel(current.model), dimension: undefined }
            : { ...current, provider, model: undefined, dimension: undefined }
        const saved = await saveIndexing(sdk, sync, updated, toast)
        if (!saved) {
          dialog.clear()
          return
        }
        await showProviderSettings(dialog, sync, sdk, toast, provider, props.useSDK, props.goBack)
      }}
    />
  )
}

export async function showProviderSettings(
  dialog: ReturnType<typeof useDialog>,
  sync: ReturnType<typeof useSync>,
  sdk: any,
  toast: ReturnType<typeof useToast>,
  provider: EmbeddingProvider,
  useSDK: () => any,
  goBack: () => void,
) {
  const fields = PROVIDER_FIELDS[provider]
  if (fields.length === 0) {
    goBack()
    return
  }
  const indexing = defaultIndexing(sync)
  const currentSettings = (indexing[provider] as Record<string, string | undefined>) ?? {}
  const newSettings: Record<string, string | undefined> = { ...currentSettings }

  for (const field of fields) {
    const currentValue = currentSettings[field.key] ?? ""
    const result = await DialogPrompt.show(dialog, `${PROVIDER_LABELS[provider]} — ${field.label}`, {
      value: currentValue,
      placeholder: field.placeholder,
    })
    if (result === null) {
      goBack()
      return
    }
    newSettings[field.key] = result.trim() || undefined
  }

  const updated = { ...getIndexing(sync), [provider]: newSettings }
  await saveIndexing(sdk, sync, updated, toast)
  goBack()
}

export { ProviderSelect }
