import { Link } from 'react-router-dom'
import {
  EXPAND_STRATEGY_OPTIONS,
  expandStrategyRequiresWebSearch,
  webSearchKeyReady,
  type PlacementResearchSettings,
} from '../lib/placementResearch'
import type { ExpandStrategy } from '../types/brand'
import { Field, Notice } from './ui'

type ExpandStrategyFieldProps = {
  value: ExpandStrategy
  onChange: (value: ExpandStrategy) => void
  settings: PlacementResearchSettings | null
  disabled?: boolean
}

export function ExpandStrategyField({ value, onChange, settings, disabled }: ExpandStrategyFieldProps) {
  const webSearchReady = webSearchKeyReady(settings)
  const needsWebSearch = expandStrategyRequiresWebSearch(value)
  const providerLabel = settings?.web_search_provider === 'exa' ? 'Exa' : 'Brave'

  return (
    <Field label="研究來源" hint="只影響「延伸知識」怎麼產生；海巡掃 Threads 走 API／爬蟲，與此無關。Brave 較貴可改 LLM 推論。">
      <div className="grid gap-2">
        {EXPAND_STRATEGY_OPTIONS.map((option) => {
          const blocked = expandStrategyRequiresWebSearch(option.value) && !webSearchReady
          const active = value === option.value
          return (
            <label
              key={option.value}
              className={`flex cursor-pointer gap-3 rounded-[var(--radius-md)] border-2 px-4 py-3 transition ${
                active ? 'border-brand bg-brand-soft/30' : 'border-line bg-surface'
              } ${blocked || disabled ? 'cursor-not-allowed opacity-70' : 'hover:border-brand/40'}`}
            >
              <input
                type="radio"
                name="expand-strategy"
                className="mt-1 h-4 w-4 accent-[var(--hx-brand)]"
                checked={active}
                disabled={disabled || blocked}
                onChange={() => onChange(option.value)}
              />
              <span className="min-w-0 flex-1 font-zh">
                <span className="block text-base font-bold leading-snug text-ink">{option.label}</span>
                <span className="mt-1 block text-sm leading-relaxed text-ink-secondary">{option.hint}</span>
              </span>
            </label>
          )
        })}
      </div>
      {needsWebSearch && !webSearchReady ? (
        <div className="mt-3 space-y-2">
          <Notice
            tone="warning"
            title={`尚未設定 ${providerLabel} API key`}
            message={`選 Web search 相關模式前需先設定 ${providerLabel} API key；或改選「LLM 推論」即可先產生圖譜。`}
          />
          <Link to="/settings" className="text-sm font-semibold text-brand hover:underline">
            前往設定頁填入 API key →
          </Link>
        </div>
      ) : null}
    </Field>
  )
}