import { useCallback, useEffect, useState } from 'react'
import { Link, useNavigate, useParams } from 'react-router-dom'
import { api, ApiError } from '../api/client'
import { ProductContextForm } from '../components/ProductContextForm'
import { rememberBrandId } from '../lib/brandContext'
import { hasProductContext } from '../lib/productContext'
import { AcLink, Button, Card, ErrorText, Field, Input, Notice, SuccessText, Textarea } from '../components/ui'
import type { BrandData } from '../types/brand'

const emptyBrand = (): BrandData => ({
  id: '',
  display_name: '',
  seed_query: '',
  brief: '',
  product_brief: '',
  product_context: '',
  target_audience: '',
  goals: '',
  create_at: 0,
  update_at: 0,
})

export function BrandDetailPage() {
  const navigate = useNavigate()
  const { id = '' } = useParams()
  const [draft, setDraft] = useState<BrandData>(emptyBrand())
  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState('')
  const [message, setMessage] = useState('')

  const load = useCallback(async () => {
    if (!id) return
    setLoading(true)
    setError('')
    try {
      const data = await api.get<BrandData>(`/api/v1/brands/${encodeURIComponent(id)}`, { auth: true })
      setDraft(data)
      rememberBrandId(id)
    } catch (e) {
      setError(e instanceof ApiError ? e.message : '載入失敗')
    } finally {
      setLoading(false)
    }
  }, [id])

  useEffect(() => {
    void load()
  }, [load])

  const save = async () => {
    if (!id) return
    setSaving(true)
    setError('')
    setMessage('')
    try {
      const productContext = draft.product_context ?? ''
      const productBrief = hasProductContext(productContext)
        ? undefined
        : draft.product_brief
      const updated = await api.patch<BrandData>(
        `/api/v1/brands/${encodeURIComponent(id)}`,
        {
          display_name: draft.display_name,
          seed_query: draft.seed_query,
          brief: draft.brief,
          product_brief: productBrief,
          product_context: productContext || undefined,
          target_audience: draft.target_audience,
          goals: draft.goals,
        },
        { auth: true },
      )
      setDraft(updated)
      rememberBrandId(id)
      setMessage('已儲存主題設定')
    } catch (e) {
      setError(e instanceof ApiError ? e.message : '儲存失敗')
    } finally {
      setSaving(false)
    }
  }

  const goFlow = (path: '/research' | '/outreach' | '/brand-matrix') => {
    rememberBrandId(id)
    navigate(`${path}?brand=${encodeURIComponent(id)}`)
  }

  if (!id) {
    return (
      <Card>
        <p className="text-sm text-muted">未指定主題。</p>
      </Card>
    )
  }

  return (
    <div className="space-y-6">
      <AcLink to="/outreach" className="inline-flex items-center gap-1.5 text-sm">
        ← 返回找 TA 主題
      </AcLink>

      <header className="space-y-2">
        <p className="display-en text-[10px] font-bold tracking-[0.16em] text-brand uppercase">Placement Topic</p>
        <h1 className="text-2xl font-black text-ink">主題設定</h1>
        <p className="max-w-2xl text-sm text-ink-secondary">
          調整種子詞、主題目標與置入產品。寫留言的語氣請到
          <Link to="/personas" className="mx-1 font-semibold text-brand hover:underline">
            人設庫
          </Link>
          設定。
        </p>
      </header>

      <Notice tone="info" title="下一步" message="儲存後從下方進入 ① 海巡研究查看研究地圖與知識圖譜。" />

      <Card className="grid gap-5">
        <Field label="主題名稱">
          <Input
            value={draft.display_name ?? ''}
            onChange={(e) => setDraft((prev) => ({ ...prev, display_name: e.target.value }))}
            disabled={loading}
          />
        </Field>
        <Field label="種子關鍵字">
          <Input
            value={draft.seed_query ?? ''}
            onChange={(e) => setDraft((prev) => ({ ...prev, seed_query: e.target.value }))}
            placeholder="例：敏感肌、換季泛紅"
            disabled={loading}
          />
        </Field>
        <Field label="這個主題想做什么">
          <Textarea
            rows={3}
            value={draft.brief ?? ''}
            onChange={(e) => setDraft((prev) => ({ ...prev, brief: e.target.value }))}
            disabled={loading}
          />
        </Field>
        <div>
          <p className="mb-2 text-sm font-semibold text-ink">想置入的品牌與產品</p>
          <ProductContextForm
            value={draft.product_context ?? ''}
            onChange={(value) => setDraft((prev) => ({ ...prev, product_context: value }))}
          />
        </div>
        {!hasProductContext(draft.product_context) ? (
          <Field label="產品簡介（備用，若未用上方結構化表單）">
            <Textarea
              rows={3}
              value={draft.product_brief ?? ''}
              onChange={(e) => setDraft((prev) => ({ ...prev, product_brief: e.target.value }))}
              disabled={loading}
            />
          </Field>
        ) : null}
        <Field label="目標受眾（選填，研究地圖產生後可自動帶入）">
          <Textarea
            rows={3}
            value={draft.target_audience ?? ''}
            onChange={(e) => setDraft((prev) => ({ ...prev, target_audience: e.target.value }))}
            disabled={loading}
          />
        </Field>
        <div className="flex flex-wrap gap-2">
          <Button onClick={save} disabled={saving || loading}>
            {saving ? '儲存中…' : '儲存設定'}
          </Button>
          <Button variant="soft" onClick={() => goFlow('/research')}>
            ① 海巡研究
          </Button>
          <Button variant="soft" onClick={() => goFlow('/outreach')}>
            ② 找 TA 留言
          </Button>
        </div>
      </Card>

      <SuccessText message={message} />
      <ErrorText message={error} />
    </div>
  )
}