import { useEffect, useState } from 'react'
import { api, streamAIChat } from '../api/client'
import { ApiError } from '../api/client'
import { storage } from '../lib/storage'
import { Button, Card, ErrorText, Field, Input, PageTitle, Textarea } from '../components/ui'
import type { AIProviderOption } from '../types/api'

export function AiPage() {
  const [providers, setProviders] = useState<AIProviderOption[]>([])
  const [provider, setProvider] = useState('opencode-go')
  const [model, setModel] = useState('')
  const [models, setModels] = useState<string[]>([])
  const [providerToken, setProviderToken] = useState(() => storage.getAiProviderToken())
  const [prompt, setPrompt] = useState('用一句話介紹巡樓系統')
  const [reply, setReply] = useState('')
  const [streaming, setStreaming] = useState(false)
  const [error, setError] = useState('')

  useEffect(() => {
    api
      .get<{ providers: AIProviderOption[] }>('/api/v1/ai/providers')
      .then((d) => {
        setProviders(d.providers)
        if (d.providers[0]) setProvider(d.providers[0].id)
      })
      .catch((e: ApiError) => setError(e.message))
  }, [])

  const loadModels = async () => {
    setError('')
    storage.setAiProviderToken(providerToken)
    try {
      const data = await api.post<{ models: string[]; error?: string }>(
        `/api/v1/ai/providers/${provider}/models`,
        { provider },
        { memberAuth: true, providerToken },
      )
      setModels(data.models)
      if (data.models[0]) setModel(data.models[0])
      if (data.error) setError(data.error)
    } catch (e) {
      setError(e instanceof ApiError ? e.message : '拉 models 失敗')
    }
  }

  const chatOnce = async () => {
    setError('')
    setReply('')
    storage.setAiProviderToken(providerToken)
    try {
      const data = await api.post<{ text: string }>(
        '/api/v1/ai/chat',
        {
          provider,
          model,
          messages: [{ role: 'user', content: prompt }],
        },
        { memberAuth: true, providerToken },
      )
      setReply(data.text)
    } catch (e) {
      setError(e instanceof ApiError ? e.message : 'chat 失敗')
    }
  }

  const chatStream = async () => {
    setError('')
    setReply('')
    setStreaming(true)
    storage.setAiProviderToken(providerToken)
    await streamAIChat(
      { provider, model, messages: [{ role: 'user', content: prompt }] },
      (t) => setReply((r) => r + t),
      () => setStreaming(false),
      (msg) => {
        setError(msg)
        setStreaming(false)
      },
    )
    setStreaming(false)
  }

  return (
    <div>
      <PageTitle
        title="AI"
        subtitle="Provider token 放 Authorization；會員 JWT 放 X-Member-Authorization"
      />
      <div className="grid gap-4 lg:grid-cols-2">
        <Card className="space-y-4">
          <Field label="Provider API Token">
            <Input
              type="password"
              value={providerToken}
              onChange={(e) => setProviderToken(e.target.value)}
              placeholder="sk-..."
            />
          </Field>
          <Field label="Provider">
            <select
              className="w-full rounded-[var(--radius-md)] border border-line bg-surface px-4 py-3 text-[15px] text-ink outline-none focus:border-brand focus:ring-4 focus:ring-brand-soft"
              value={provider}
              onChange={(e) => setProvider(e.target.value)}
            >
              {providers.map((p) => (
                <option key={p.id} value={p.id}>
                  {p.label} {p.streams ? '(stream)' : ''}
                </option>
              ))}
            </select>
          </Field>
          <div className="flex gap-2">
            <Button variant="ghost" onClick={loadModels}>
              從 Provider 載入模型清單
            </Button>
            <select
              className="flex-1 rounded-[var(--radius-md)] border border-line bg-surface px-4 py-3 text-[15px] text-ink outline-none focus:border-brand focus:ring-4 focus:ring-brand-soft"
              value={model}
              onChange={(e) => setModel(e.target.value)}
            >
              {models.map((m) => (
                <option key={m} value={m}>
                  {m}
                </option>
              ))}
            </select>
          </div>
          <Field label="Prompt">
            <Textarea rows={4} value={prompt} onChange={(e) => setPrompt(e.target.value)} />
          </Field>
          <div className="flex gap-2">
            <Button onClick={chatOnce} disabled={!model || streaming}>
              送出對話（一次完整回覆）
            </Button>
            <Button variant="ghost" onClick={chatStream} disabled={!model || streaming}>
              {streaming ? '串流回覆中…' : '送出對話（SSE 串流回覆）'}
            </Button>
          </div>
          <ErrorText message={error} />
        </Card>
        <Card>
          <h2 className="font-semibold text-ink">回應</h2>
          <pre className="mt-3 whitespace-pre-wrap text-[15px] leading-relaxed text-ink">{reply || '—'}</pre>
        </Card>
      </div>
    </div>
  )
}