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'

function productCount(item: BrandData): number {
  return item.products?.length ?? 0
}

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)
    }
  }

  return (
    <div className="space-y-8">
      <PageTitle title="品牌庫" subtitle="管理品牌與產品目錄，一個品牌可對應多個產品。" />

      <Card className="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 className="py-10 text-center">
          <p className="text-sm text-muted">載入中…</p>
        </Card>
      ) : brands.length ? (
        <div className="grid gap-4 sm:grid-cols-2">
          {brands.map((item) => {
            const count = productCount(item)
            return (
              <div key={item.id} className="ac-app-card group relative p-5">
                <div className="flex items-start justify-between gap-3">
                  <Link to={`/brands/${item.id}`} className="min-w-0 flex-1">
                    <h2 className="text-lg font-bold text-ink transition group-hover:text-brand">
                      {item.display_name || '未命名品牌'}
                    </h2>
                    <p className="mt-2 text-sm text-ink-secondary">
                      {count > 0 ? `${count} 個產品` : '尚未新增產品'}
                    </p>
                    <div className="mt-3">
                      <Badge tone={count > 0 ? 'sky' : 'neutral'}>
                        {count > 0 ? `${count} 個產品` : '待新增產品'}
                      </Badge>
                    </div>
                  </Link>
                  <TableAction
                    variant="danger"
                    disabled={deletingId === item.id}
                    onClick={() => void remove(item)}
                  >
                    {deletingId === item.id ? '刪除中…' : '刪除'}
                  </TableAction>
                </div>
              </div>
            )
          })}
        </div>
      ) : (
        <Card className="py-12 text-center">
          <p className="text-sm text-ink-secondary">尚無品牌。建立後即可在品牌內新增產品。</p>
        </Card>
      )}

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