import { useEffect, useState } from 'react'
import { api, ApiError } from '../api/client'
import { Button, ErrorText, Field, Input, SectionTitle, SuccessText } from './ui'

type PlacementSettings = {
  brave_api_key?: string
  brave_api_key_configured: boolean
  brave_country: string
  brave_search_lang: string
}

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

export function PlacementResearchSettings() {
  const [settings, setSettings] = useState<PlacementSettings | null>(null)
  const [braveKey, setBraveKey] = useState('')
  const [country, setCountry] = useState('tw')
  const [searchLang, setSearchLang] = useState('zh-hant')
  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<PlacementSettings>('/api/v1/members/me/placement-settings', { auth: true })
      setSettings(data)
      setBraveKey(data.brave_api_key ?? '')
      setCountry(data.brave_country || 'tw')
      setSearchLang(data.brave_search_lang || 'zh-hant')
    } 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> = {
        brave_country: country.trim(),
        brave_search_lang: searchLang.trim(),
      }
      const trimmedKey = braveKey.trim()
      if (trimmedKey && !isMaskedKey(trimmedKey)) {
        payload.brave_api_key = trimmedKey
      }
      const data = await api.patch<PlacementSettings>('/api/v1/members/me/placement-settings', payload, {
        auth: true,
      })
      setSettings(data)
      setBraveKey(data.brave_api_key ?? '')
      setMessage('海巡研究設定已儲存（跟隨此登入帳號）')
    } catch (e) {
      setError(e instanceof ApiError ? e.message : '儲存失敗')
    } finally {
      setSaving(false)
    }
  }

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

  return (
    <div className="grid gap-4">
      <div>
        <SectionTitle>海巡研究設定</SectionTitle>
        <p className="mt-1 text-sm text-ink-secondary">
          Brave API key 與語系跟隨<strong>此登入帳號</strong>，所有經營帳號共用。知識圖譜擴展會用 Brave；正式模式下海巡搜尋走
          Threads API（見連線模式）。
        </p>
      </div>
      <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>
      <ErrorText message={error} />
      <SuccessText message={message} />
      <Button onClick={save} disabled={saving}>
        {saving ? '儲存中…' : '儲存研究設定'}
      </Button>
    </div>
  )
}