"use client"; import { useEffect, useState } from "react"; import { useRouter, useSearchParams } from "next/navigation"; import { ArrowDown, ArrowUp, Plus, Trash2, X } from "lucide-react"; import { Badge } from "@/app/components/ui/badge"; import { Button } from "@/app/components/ui/button"; import { Card, CardContent, CardHeader, CardTitle } from "@/app/components/ui/card"; import { ConfirmDialog } from "@/app/components/ui/confirm-dialog"; import { Input } from "@/app/components/ui/input"; import { Label } from "@/app/components/ui/label"; import { RadioGroup, RadioGroupItem } from "@/app/components/ui/radio-group"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/app/components/ui/select"; import { ErrorState } from "@/app/components/ui/states"; import { Textarea } from "@/app/components/ui/textarea"; import { FieldError } from "@/app/components/catalog-setup/FieldError"; import { ProductSearchCombobox } from "@/app/components/products/ProductSearchCombobox"; import { parseServerError, type FieldErrors } from "@/app/lib/catalogSetup"; import { useT } from "@/app/lib/i18n/MessagesProvider"; import { RULE_FIELD_LABELS, SORT_LABELS, collectionBody, collectionFromView, emptyCollection, moveProduct, previewBody, validateCollection, withTitle, withType, type CollectionDraft, type CollectionPreview, type CollectionSort, type RuleField, } from "@/app/lib/collections"; import { displayLocaleName } from "@/app/lib/messageContent"; import { deleteCollection, getCollection, previewCollection, saveCollection, uploadCollectionImage, } from "@/app/lib/services/adminCollections"; import { getProductOptions, listProductTags } from "@/app/lib/services/adminProduct"; import type { CatalogRow } from "@/app/lib/types"; // The collection form (add-storefront-collections): Manual (hand-picked, ordered products) or // Automatic (conditions on brand, category or tag). The type is chosen once, at creation. // The image is a SAME-REQUEST upload: it is sent only on save, just before the save call. const PREVIEW_DELAY_MS = 300; /** Error paths the form renders under a field; any other server path becomes the summary. */ const SHOWN_ERROR_SLOT = /^(title|slug|description|imageUrl|metaDescription|sort|rules|productIds|rules\[\d+\]\.(value|field))$/; const MANUAL_SORTS: CollectionSort[] = ["MANUAL", "PRICE_ASC", "PRICE_DESC", "NEWEST", "NAME"]; const AUTOMATIC_SORTS: CollectionSort[] = ["NEWEST", "PRICE_ASC", "PRICE_DESC", "NAME"]; function readDataUrl(file: File): Promise { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = () => resolve(reader.result as string); reader.onerror = () => reject(reader.error); reader.readAsDataURL(file); }); } export function CollectionForm({ collectionId }: { collectionId?: number }) { const t = useT(); const router = useRouter(); const [draft, setDraft] = useState(() => emptyCollection("MANUAL")); const [loading, setLoading] = useState(collectionId != null); const [loadError, setLoadError] = useState(null); const [errors, setErrors] = useState({}); const [summary, setSummary] = useState(null); // A new collection's save moves to its edit URL with ?saved=1, which remounts the form. const savedParam = useSearchParams()?.get("saved") === "1"; const [notice, setNotice] = useState(savedParam ? "CollSaved" : null); const [saving, setSaving] = useState(false); const [imageFile, setImageFile] = useState(null); const [imagePreview, setImagePreview] = useState(""); const [brands, setBrands] = useState([]); const [categories, setCategories] = useState([]); const [tags, setTags] = useState([]); const [preview, setPreview] = useState(null); const [confirmDelete, setConfirmDelete] = useState(false); useEffect(() => { let cancelled = false; getProductOptions() .then((opts) => { if (cancelled) return; setBrands(opts.brands); setCategories(opts.categories); }) .catch(() => {}); listProductTags() .then((found) => { if (!cancelled) setTags(found); }) .catch(() => {}); return () => { cancelled = true; }; }, []); useEffect(() => { if (collectionId == null) return; let cancelled = false; getCollection(collectionId) .then((view) => { if (!cancelled) setDraft(collectionFromView(view)); }) .catch((err: unknown) => { if (!cancelled) setLoadError(err instanceof Error ? err.message : "CollLoadFailed"); }) .finally(() => { if (!cancelled) setLoading(false); }); return () => { cancelled = true; }; }, [collectionId]); const previewKey = JSON.stringify(previewBody({ ...draft, title: "", slug: "", description: "", metaDescription: "", imageUrl: "" })); useEffect(() => { if (loading) return; let cancelled = false; const timer = setTimeout(() => { previewCollection(JSON.parse(previewKey)) .then((result) => { if (!cancelled) setPreview(result); }) .catch(() => { if (!cancelled) setPreview(null); }); }, PREVIEW_DELAY_MS); return () => { cancelled = true; clearTimeout(timer); }; }, [previewKey, loading]); function patch(next: Partial) { setDraft((d) => ({ ...d, ...next })); } function setRule(index: number, next: { field?: RuleField; value?: string }) { setDraft((d) => ({ ...d, rules: d.rules.map((rule, i) => i !== index ? rule : next.field && next.field !== rule.field ? { field: next.field, value: "" } : { ...rule, ...next }, ), })); } async function chooseImage(file: File | undefined) { if (!file) return; setImageFile(file); setImagePreview(await readDataUrl(file)); } async function save() { setSummary(null); setNotice(null); const clientErrors = validateCollection(draft, t); setErrors(clientErrors); if (Object.keys(clientErrors).length > 0) return; setSaving(true); try { let imageUrl = draft.imageUrl; if (imageFile) { const base = (await readDataUrl(imageFile)).split(",")[1]; imageUrl = (await uploadCollectionImage({ fileName: imageFile.name, fileType: imageFile.type, base })).url; // Keep the uploaded URL, so a retry after a failed save never uploads the image again. setImageFile(null); setImagePreview(""); patch({ imageUrl }); } const view = await saveCollection(collectionBody({ ...draft, imageUrl })); setDraft(collectionFromView(view)); setImageFile(null); setImagePreview(""); setNotice("CollSaved"); if (draft.id == null) router.replace(`/collections/${view.id}?saved=1`); } catch (err) { const message = err instanceof Error ? err.message : "CollSaveFailed"; const { path, message: fieldMessage } = parseServerError(message); const slot = path?.startsWith("productIds[") ? "productIds" : path; if (slot && SHOWN_ERROR_SLOT.test(slot)) setErrors({ [slot]: fieldMessage }); else setSummary(message); } finally { setSaving(false); } } async function remove() { if (draft.id == null) return; setSummary(null); try { await deleteCollection(draft.id); router.push("/collections"); } catch (err) { setSummary(err instanceof Error ? err.message : "CollDeleteFailed"); } } if (loadError) return ; if (loading) return null; const automatic = draft.type === "AUTOMATIC"; const sorts = automatic ? AUTOMATIC_SORTS : MANUAL_SORTS; const shownImage = imagePreview || draft.imageUrl; return (
{summary && } {notice && (

{t(notice)}

)}
{t("CollCardCollection")}
setDraft((d) => withTitle(d, e.target.value))} />
{"/collections/"} patch({ slug: e.target.value, slugTouched: true })} />