"use client"; import Link from "next/link"; import { useEffect, useMemo, useState } from "react"; import { Plus, Settings2 } from "lucide-react"; import { BrandFormDialog } from "@/components/product-profile/brand-form-dialog"; import { Button } from "@/components/ui/button"; import { Label } from "@/components/ui/label"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select"; import { formatCatalogProductSummary, type CatalogBrand, } from "@/lib/types/product-catalog"; interface BrandProductPickerProps { brandId: string | null; productId: string | null; onChange: (selection: { brandId: string | null; productId: string | null; context?: string; }) => void; label?: string; } export function BrandProductPicker({ brandId, productId, onChange, label = "品牌與產品", }: BrandProductPickerProps) { const [brands, setBrands] = useState([]); const [loading, setLoading] = useState(true); const [createBrandOpen, setCreateBrandOpen] = useState(false); async function load() { setLoading(true); try { const res = await fetch("/api/brands?all=1&productLimit=200"); const data = await res.json().catch(() => ({})); setBrands(data.brands ?? []); } catch { // 網路異常時保持空列表 } finally { setLoading(false); } } useEffect(() => { load(); }, []); const selectedBrand = useMemo( () => brands.find((b) => b.id === brandId) ?? null, [brands, brandId] ); const selectedProduct = useMemo(() => { if (!selectedBrand || !productId) return null; return selectedBrand.products.find((p) => p.id === productId) ?? null; }, [selectedBrand, productId]); const preview = selectedBrand && selectedProduct ? formatCatalogProductSummary(selectedBrand.name, selectedProduct.context, selectedProduct.label) : selectedBrand ? `${selectedBrand.name} · ${selectedBrand.products.length} 個產品(生成時依標籤自動推薦)` : null; function emit(nextBrandId: string | null, nextProductId: string | null) { if (!nextBrandId) { onChange({ brandId: null, productId: null }); return; } const brand = brands.find((b) => b.id === nextBrandId); if (!brand) return; const product = nextProductId && nextProductId !== "__auto__" ? brand.products.find((p) => p.id === nextProductId) ?? null : null; const context = product ? formatCatalogProductSummary(brand.name, product.context, product.label) : undefined; onChange({ brandId: nextBrandId, productId: nextProductId === "__auto__" ? null : nextProductId, context, }); } return (
管理品牌與產品
{selectedBrand && selectedBrand.products.length > 0 && ( )} {selectedBrand && selectedBrand.products.length === 0 && (

此品牌尚無產品,請到「品牌與產品」頁新增。

)} {preview &&

{preview}

} load()} />
); }