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

const emptyBrand = (): BrandData => ({
  id: '',
  display_name: '',
  products: [],
  goals: '',
  create_at: 0,
  update_at: 0,
})

export function BrandDetailPage() {
  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 updated = await api.patch<BrandData>(
        `/api/v1/brands/${encodeURIComponent(id)}`,
        {
          display_name: draft.display_name,
          goals: draft.goals,
        },
        { auth: true },
      )
      setDraft((prev) => ({ ...prev, ...updated, products: prev.products }))
      rememberBrandId(id)
      setMessage('已儲存')
    } catch (e) {
      setError(e instanceof ApiError ? e.message : '儲存失敗')
    } finally {
      setSaving(false)
    }
  }

  if (!id) {
    return (
      <Card className="py-8 text-center">
        <p className="text-sm text-muted">未指定品牌。</p>
      </Card>
    )
  }

  return (
    <div className="mx-auto w-full max-w-3xl space-y-8">
      <AcLink to="/brands" className="inline-flex items-center gap-1.5 text-sm">
        ← 品牌庫
      </AcLink>

      <PageTitle
        title={draft.display_name?.trim() || '未命名品牌'}
        subtitle="先設定品牌，再於下方產品目錄新增產品線。"
      />

      <Card className="grid gap-5">
        <SectionTitle>品牌設定</SectionTitle>
        <Field label="品牌名稱">
          <Input
            value={draft.display_name ?? ''}
            onChange={(e) => setDraft((prev) => ({ ...prev, display_name: e.target.value }))}
            placeholder="品牌名稱"
            disabled={loading}
          />
        </Field>
        <Field label="備註" hint="選填，例如定位、受眾或內部備忘">
          <Textarea
            rows={3}
            value={draft.goals ?? ''}
            onChange={(e) => setDraft((prev) => ({ ...prev, goals: e.target.value }))}
            placeholder="例：天然成分、主攻敏感肌"
            disabled={loading}
          />
        </Field>
        <div className="flex flex-wrap gap-2">
          <Button onClick={save} disabled={saving || loading}>
            {saving ? '儲存中…' : '儲存'}
          </Button>
        </div>
      </Card>

      <BrandProductsPanel
        brand={draft}
        brandId={id}
        onProductsChange={(products) => setDraft((prev) => ({ ...prev, products }))}
      />

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