import { useCallback, useEffect, useState } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import { api, ApiError } from '../api/client'
import { summarizeProductContext } from '../lib/productContext'
import type { BrandData, BrandProductData } from '../types/brand'
import { Badge, Button, Card, ErrorText, SectionTitle, TableAction } from './ui'

type Props = {
  brand: BrandData
  /** 路由上的品牌 id；避免 draft 尚未載入時 brand.id 為空 */
  brandId?: string
  onProductsChange: (products: BrandProductData[]) => void
}

function productSummary(item: BrandProductData): string {
  return summarizeProductContext(item.product_context) || item.label
}

export function BrandProductsPanel({ brand, brandId: brandIdProp, onProductsChange }: Props) {
  const navigate = useNavigate()
  const [products, setProducts] = useState<BrandProductData[]>(brand.products ?? [])
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')
  const [deletingId, setDeletingId] = useState<string | null>(null)

  const brandId = (brandIdProp ?? brand.id).trim()
  const newProductPath = `/brands/${encodeURIComponent(brandId)}/products/new`
  const editProductPath = (productId: string) =>
    `/brands/${encodeURIComponent(brandId)}/products/${encodeURIComponent(productId)}`

  const syncProducts = (list: BrandProductData[]) => {
    setProducts(list)
    onProductsChange(list)
  }

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

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

  const remove = async (item: BrandProductData) => {
    if (!window.confirm(`確定刪除產品「${item.label}」？`)) return
    setDeletingId(item.id)
    setError('')
    try {
      await api.delete(
        `/api/v1/brands/${encodeURIComponent(brandId)}/products/${encodeURIComponent(item.id)}`,
        { auth: true },
      )
      await load()
    } catch (e) {
      setError(e instanceof ApiError ? e.message : '刪除失敗')
    } finally {
      setDeletingId(null)
    }
  }

  return (
    <Card className="space-y-5">
      <div className="flex flex-wrap items-center justify-between gap-3">
        <div className="flex flex-wrap items-center gap-3">
          <SectionTitle>產品目錄</SectionTitle>
          {products.length ? (
            <Badge tone="sky">{products.length} 個產品</Badge>
          ) : (
            <span className="text-sm text-muted">一個品牌可對應多個產品線</span>
          )}
        </div>
        <Button variant="soft" onClick={() => navigate(newProductPath)}>
          ＋ 新增產品
        </Button>
      </div>

      {loading ? (
        <p className="py-6 text-center text-sm text-muted">載入中…</p>
      ) : products.length ? (
        <div className="grid gap-3">
          {products.map((item) => (
            <div key={item.id} className="ac-app-card p-4 md:p-5">
              <div className="flex flex-wrap items-start justify-between gap-3">
                <Link to={editProductPath(item.id)} className="min-w-0 flex-1 transition hover:text-brand">
                  <h3 className="text-base font-bold text-ink">{item.label}</h3>
                  <p className="mt-2 line-clamp-2 text-sm leading-relaxed text-ink-secondary">
                    {productSummary(item)}
                  </p>
                  {item.match_tags?.length ? (
                    <div className="mt-3 flex flex-wrap gap-1.5">
                      {item.match_tags.map((tag) => (
                        <Badge key={tag} tone="neutral">
                          {tag}
                        </Badge>
                      ))}
                    </div>
                  ) : null}
                </Link>
                <div className="flex shrink-0 flex-wrap gap-2">
                  <TableAction onClick={() => navigate(editProductPath(item.id))}>編輯</TableAction>
                  <TableAction
                    variant="danger"
                    disabled={deletingId === item.id}
                    onClick={() => void remove(item)}
                  >
                    {deletingId === item.id ? '刪除中…' : '刪除'}
                  </TableAction>
                </div>
              </div>
            </div>
          ))}
        </div>
      ) : (
        <div className="py-8 text-center">
          <p className="text-sm text-ink-secondary">尚無產品。</p>
          <Button className="mt-4" variant="soft" onClick={() => navigate(newProductPath)}>
            新增第一個產品
          </Button>
        </div>
      )}

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