import { useCallback, useEffect, useState } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import { api, ApiError } from '../api/client'
import { rememberBrandId } from '../lib/brandContext'
import { Badge, Button, Card, ErrorText, Field, Input, PageTitle, TableAction } from '../components/ui'
import type { BrandData, ListBrandsData } from '../types/brand'

export function BrandsPage() {
  const navigate = useNavigate()
  const [brands, setBrands] = useState<BrandData[]>([])
  const [loading, setLoading] = useState(true)
  const [creating, setCreating] = useState(false)
  const [deletingId, setDeletingId] = useState<string | null>(null)
  const [newName, setNewName] = useState('')
  const [error, setError] = useState('')

  const load = useCallback(async () => {
    setError('')
    const data = await api.get<ListBrandsData>('/api/v1/brands/', { auth: true })
    setBrands(data.list ?? [])
  }, [])

  useEffect(() => {
    load()
      .catch((e) => setError(e instanceof ApiError ? e.message : '載入失敗'))
      .finally(() => setLoading(false))
  }, [load])

  const remove = async (item: BrandData) => {
    const label = item.display_name?.trim() || '未命名品牌'
    if (!window.confirm(`確定要刪除品牌「${label}」？相關海巡資料一併移除，無法復原。`)) return
    setDeletingId(item.id)
    setError('')
    try {
      await api.delete(`/api/v1/brands/${encodeURIComponent(item.id)}`, { auth: true })
      setBrands((prev) => prev.filter((p) => p.id !== item.id))
    } catch (e) {
      setError(e instanceof ApiError ? e.message : '刪除失敗')
    } finally {
      setDeletingId(null)
    }
  }

  const create = async () => {
    setCreating(true)
    setError('')
    try {
      const created = await api.post<BrandData>(
        '/api/v1/brands/',
        { display_name: newName.trim() || undefined },
        { auth: true },
      )
      setNewName('')
      rememberBrandId(created.id)
      navigate(`/brands/${created.id}`)
    } catch (e) {
      setError(e instanceof ApiError ? e.message : '建立失敗')
    } finally {
      setCreating(false)
    }
  }

  const startFlow = (brandId: string, path: '/research' | '/outreach' | '/brand-matrix') => {
    rememberBrandId(brandId)
    navigate(`${path}?brand=${encodeURIComponent(brandId)}`)
  }

  return (
    <div>
      <PageTitle
        title="品牌庫"
        subtitle="建立品牌與產品定位，供找 TA（流程 B）使用。仿寫爆款請走拷貝忍者；回覆語氣請到人設庫。"
      />

      <Card className="mb-4 grid gap-4 sm:grid-cols-[1fr_auto] sm:items-end">
        <Field label="新增品牌名稱">
          <Input
            value={newName}
            onChange={(e) => setNewName(e.target.value)}
            placeholder="例如：敏感肌保養品牌"
            onKeyDown={(e) => {
              if (e.key === 'Enter') void create()
            }}
          />
        </Field>
        <Button onClick={create} disabled={creating}>
          {creating ? '建立中…' : '建立品牌'}
        </Button>
      </Card>

      {loading ? (
        <Card>
          <p className="text-sm text-muted">載入中…</p>
        </Card>
      ) : brands.length ? (
        <div className="grid gap-3">
          {brands.map((item) => (
            <div key={item.id} className="ac-app-card p-5">
              <div className="flex flex-wrap items-start justify-between gap-3">
                <Link to={`/brands/${item.id}`} className="min-w-0 flex-1">
                  <h2 className="text-base font-bold text-ink transition hover:text-brand">
                    {item.display_name || '未命名品牌'}
                  </h2>
                  {item.product_brief?.trim() || item.brief?.trim() ? (
                    <p className="mt-2 line-clamp-2 text-sm text-ink-secondary">
                      {item.product_brief?.trim() || item.brief}
                    </p>
                  ) : (
                    <p className="mt-2 text-sm text-muted">尚未填寫產品與定位</p>
                  )}
                  <div className="mt-2 flex flex-wrap gap-2">
                    {item.target_audience?.trim() ? <Badge tone="sky">受眾已填</Badge> : null}
                    {item.brief?.trim() ? <Badge tone="neutral">定位已填</Badge> : null}
                  </div>
                </Link>
                <TableAction
                  variant="danger"
                  disabled={deletingId === item.id}
                  onClick={() => void remove(item)}
                >
                  {deletingId === item.id ? '刪除中…' : '刪除'}
                </TableAction>
              </div>
              <div className="mt-3 flex flex-wrap gap-2 border-t border-border/60 pt-3">
                <Button variant="soft" onClick={() => startFlow(item.id, '/research')}>
                  ① 海巡研究
                </Button>
                <Button variant="soft" onClick={() => startFlow(item.id, '/outreach')}>
                  ② 找 TA
                </Button>
                <Button variant="soft" onClick={() => startFlow(item.id, '/brand-matrix')}>
                  ③ 原創矩陣
                </Button>
              </div>
            </div>
          ))}
        </div>
      ) : (
        <Card>
          <p className="text-sm text-ink-secondary">
            尚無品牌。建立第一份品牌後，到品牌詳情填寫產品簡介與受眾，再從左側「核心工作流」開始。
          </p>
        </Card>
      )}

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