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

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

  const options: DialogSelectOption<string>[] = TUNING_PARAMS.map((param) => {
    const value = indexing[param.key]
    return {
      value: param.key,
      title: param.label,
      description: value !== undefined ? String(value) : `default (${param.defaultValue})`,
    }
  })

  return (
    <DialogSelect
      title="Tuning Parameters"
      options={options}
      onSelect={async (option) => {
        const param = TUNING_PARAMS.find((p) => p.key === option.value)!
        const currentIndexing = getIndexing(sync)
        const currentValue = currentIndexing[param.key]
        const result = await DialogPrompt.show(dialog, param.label, {
          value: currentValue !== undefined ? String(currentValue) : "",
          placeholder: `Default: ${param.defaultValue}`,
        })
        if (result === null) {
          dialog.replace(() => <TuningMenu {...props} />)
          return
        }
        const trimmed = result.trim()
        const num = trimmed ? Number(trimmed) : undefined
        if (trimmed && isNaN(num!)) {
          toast.show({ message: `Invalid number: "${trimmed}"`, variant: "error" })
          dialog.replace(() => <TuningMenu {...props} />)
          return
        }
        const updated = { ...getIndexing(sync), [param.key]: num }
        await saveIndexing(sdk, sync, updated, toast)
        dialog.replace(() => <TuningMenu {...props} />)
      }}
    />
  )
}

export { TuningMenu }
