import { useEffect, useState } from 'react'
import { api, ApiError } from '../api/client'
import type { ExpandStrategy } from '../types/brand'
import {
  WEB_SEARCH_PROVIDER_OPTIONS,
  type PlacementResearchSettings,
  type WebSearchProvider,
} from '../lib/placementResearch'
import { ExpandStrategyField } from './ExpandStrategyField'
import { Button, ErrorText, Field, Input, SectionTitle, SuccessText } from './ui'

function isMaskedKey(value: string) {
  return value.startsWith('••••')
}

export function PlacementResearchSettings() {
  const [settings, setSettings] = useState<PlacementResearchSettings | null>(null)
  const [webProvider, setWebProvider] = useState<WebSearchProvider>('brave')
  const [braveKey, setBraveKey] = useState('')
  const [exaKey, setExaKey] = useState('')
  const [country, setCountry] = useState('tw')
  const [searchLang, setSearchLang] = useState('zh-hant')
  const [exaLocation, setExaLocation] = useState('TW')
  const [expandStrategy, setExpandStrategy] = useState<ExpandStrategy>('hybrid')
  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState('')
  const [message, setMessage] = useState('')

  const load = async () => {
    setLoading(true)
    setError('')
    try {
      const data = await api.get<PlacementResearchSettings>('/api/v1/members/me/placement-settings', { auth: true })
      setSettings(data)
      setWebProvider(data.web_search_provider || 'brave')
      setBraveKey(data.brave_api_key ?? '')
      setExaKey(data.exa_api_key ?? '')
      setCountry(data.brave_country || 'tw')
      setSearchLang(data.brave_search_lang || 'zh-hant')
      setExaLocation(data.exa_user_location || 'TW')
      setExpandStrategy(data.expand_strategy || 'hybrid')
    } catch (e) {
      setError(e instanceof ApiError ? e.message : '載入海巡研究設定失敗')
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    load().catch(() => undefined)
  }, [])

  const save = async () => {
    setSaving(true)
    setError('')
    setMessage('')
    try {
      const payload: Record<string, string> = {
        web_search_provider: webProvider,
        brave_country: country.trim(),
        brave_search_lang: searchLang.trim(),
        exa_user_location: exaLocation.trim(),
        expand_strategy: expandStrategy,
      }
      const trimmedBrave = braveKey.trim()
      if (trimmedBrave && !isMaskedKey(trimmedBrave)) {
        payload.brave_api_key = trimmedBrave
      }
      const trimmedExa = exaKey.trim()
      if (trimmedExa && !isMaskedKey(trimmedExa)) {
        payload.exa_api_key = trimmedExa
      }
      const data = await api.patch<PlacementResearchSettings>('/api/v1/members/me/placement-settings', payload, {
        auth: true,
      })
      setSettings(data)
      setWebProvider(data.web_search_provider || webProvider)
      setBraveKey(data.brave_api_key ?? '')
      setExaKey(data.exa_api_key ?? '')
      setExpandStrategy(data.expand_strategy || expandStrategy)
      setMessage('海巡研究設定已儲存（跟隨此登入帳號）')
    } catch (e) {
      setError(e instanceof ApiError ? e.message : '儲存失敗')
    } finally {
      setSaving(false)
    }
  }

  if (loading) {
    return <p className="text-base text-ink-secondary">載入海巡研究設定…</p>
  }

  return (
    <div className="grid gap-5">
      <div>
        <SectionTitle>研究地圖來源</SectionTitle>
        <p className="mt-2 text-base leading-relaxed text-ink-secondary">
          選擇 Web 搜尋引擎與延伸知識策略；API key 跟隨<strong>此登入帳號</strong>，所有主題產生研究地圖與海巡 fallback 時共用。
        </p>
      </div>

      <Field label="Web 搜尋引擎" hint="海巡掃描 fallback 與研究地圖參考資料收集">
        <div className="grid gap-2">
          {WEB_SEARCH_PROVIDER_OPTIONS.map((option) => {
            const active = webProvider === 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'
                } ${saving ? 'cursor-not-allowed opacity-70' : 'hover:border-brand/40'}`}
              >
                <input
                  type="radio"
                  name="web-search-provider"
                  className="mt-1 h-4 w-4 accent-[var(--hx-brand)]"
                  checked={active}
                  disabled={saving}
                  onChange={() => setWebProvider(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>
      </Field>

      <ExpandStrategyField
        value={expandStrategy}
        onChange={setExpandStrategy}
        settings={settings}
        disabled={saving}
      />

      {webProvider === 'brave' ? (
        <>
          <Field label="Brave Search API key" hint="brave.com/search/api">
            <Input
              type="password"
              value={braveKey}
              onChange={(e) => setBraveKey(e.target.value)}
              placeholder={settings?.brave_api_key_configured ? '已設定（留空則不變更）' : 'X-Subscription-Token'}
            />
          </Field>
          <div className="grid gap-4 sm:grid-cols-2">
            <Field label="Brave country" hint="例如 tw">
              <Input value={country} onChange={(e) => setCountry(e.target.value)} />
            </Field>
            <Field label="Brave search_lang" hint="例如 zh-hant">
              <Input value={searchLang} onChange={(e) => setSearchLang(e.target.value)} />
            </Field>
          </div>
        </>
      ) : (
        <>
          <Field label="Exa API key" hint="dashboard.exa.ai/api-keys">
            <Input
              type="password"
              value={exaKey}
              onChange={(e) => setExaKey(e.target.value)}
              placeholder={settings?.exa_api_key_configured ? '已設定（留空則不變更）' : 'x-api-key'}
            />
          </Field>
          <Field label="Exa userLocation" hint="兩碼國家代碼，例如 TW">
            <Input value={exaLocation} onChange={(e) => setExaLocation(e.target.value)} />
          </Field>
        </>
      )}

      <ErrorText message={error} />
      <SuccessText message={message} />
      <Button onClick={save} disabled={saving}>
        {saving ? '儲存中…' : '儲存研究設定'}
      </Button>
    </div>
  )
}