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 SubDialogProps,
  VECTOR_STORE_LABELS,
  defaultIndexing,
  getIndexing,
  saveIndexing,
} from "./dialog-indexing-helpers"

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

  const options: DialogSelectOption<string>[] = Object.entries(VECTOR_STORE_LABELS).map(([value, title]) => ({
    value,
    title,
    description: value === (indexing.vectorStore ?? "qdrant") ? "(current)" : undefined,
  }))

  return (
    <DialogSelect
      title="Vector Store"
      options={options}
      current={indexing.vectorStore ?? "qdrant"}
      onSelect={async (option) => {
        const store = option.value as "lancedb" | "qdrant"
        if (store === "lancedb") await showLancedbSettings(dialog, sync, sdk, toast, props.goBack)
        else await showQdrantSettings(dialog, sync, sdk, toast, props.goBack)
      }}
    />
  )
}

async function showLancedbSettings(
  dialog: ReturnType<typeof useDialog>,
  sync: ReturnType<typeof useSync>,
  sdk: any,
  toast: ReturnType<typeof useToast>,
  goBack: () => void,
) {
  const indexing = getIndexing(sync)
  const result = await DialogPrompt.show(dialog, "LanceDB — Directory", {
    value: indexing.lancedb?.directory ?? "",
    placeholder: "Leave empty for default",
  })
  if (result === null) {
    goBack()
    return
  }
  const updated: IndexingConfig = {
    ...getIndexing(sync),
    vectorStore: "lancedb",
    lancedb: { directory: result.trim() || undefined },
  }
  await saveIndexing(sdk, sync, updated, toast)
  goBack()
}

async function showQdrantSettings(
  dialog: ReturnType<typeof useDialog>,
  sync: ReturnType<typeof useSync>,
  sdk: any,
  toast: ReturnType<typeof useToast>,
  goBack: () => void,
) {
  const indexing = getIndexing(sync)
  const currentSettings = indexing.qdrant ?? {}

  const url = await DialogPrompt.show(dialog, "Qdrant — URL", {
    value: currentSettings.url ?? "",
    placeholder: "http://localhost:6333",
  })
  if (url === null) {
    goBack()
    return
  }

  const apiKey = await DialogPrompt.show(dialog, "Qdrant — API Key", {
    value: currentSettings.apiKey ?? "",
    placeholder: "Optional API key",
  })
  if (apiKey === null) {
    goBack()
    return
  }

  const updated: IndexingConfig = {
    ...getIndexing(sync),
    vectorStore: "qdrant",
    qdrant: { url: url.trim() || undefined, apiKey: apiKey.trim() || undefined },
  }
  await saveIndexing(sdk, sync, updated, toast)
  goBack()
}

export { VectorStoreSelect }
