"use client"; import { useEffect, useState, type FormEvent } from "react"; import { Button } from "@/app/components/ui/button"; import { Input } from "@/app/components/ui/input"; import { Label } from "@/app/components/ui/label"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/app/components/ui/select"; import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle, } from "@/app/components/ui/dialog"; import { DateTimePicker } from "@/app/components/ui/date-time-picker"; import { ErrorState } from "@/app/components/ui/states"; import { ApiError } from "@/app/lib/clientApi"; import { LINK_KIND_OPTIONS, ZONE_OPTIONS, saveBanner, uploadBannerImage } from "@/app/lib/services/banners"; import type { AdminBanner, BannerLinkKind, BannerStatus, BannerZone } from "@/app/lib/types"; import { useT } from "@/app/lib/i18n/MessagesProvider"; import type { MessageParams } from "@/app/lib/i18n/t"; // The `/banners` create/edit dialog (spec "add-homepage-banners", task 13). Mirrors // app/bulletins/page.tsx's BulletinFormDialog: upload-on-submit images so an abandoned form // uploads nothing (both banner image uploads are SAME-REQUEST/file_autocommit=Y — see // app/api/banners/image/route.ts — so the returned URL can be persisted immediately). // // No product/category picker component exists anywhere in the admin portal (checked // app/components/ui, app/components/products, and grepped for Picker/Combobox — the only // typeahead is MemberSearchCombobox, which is member-specific). PRODUCT/CATEGORY link // references are therefore plain validated id/slug text fields, not a typeahead. interface FormState { id?: number; zone: BannerZone; desktopImageUrl: string; mobileImageUrl: string; altText: string; headline: string; subHeadline: string; ctaLabel: string; linkKind: BannerLinkKind; linkReference: string; displayOrder: string; dateFrom: string; dateTo: string; status: BannerStatus; } function emptyForm(zone: BannerZone): FormState { return { zone, desktopImageUrl: "", mobileImageUrl: "", altText: "", headline: "", subHeadline: "", ctaLabel: "", linkKind: "NONE", linkReference: "", displayOrder: "", dateFrom: "", dateTo: "", status: "Y", }; } function toFormState(banner: AdminBanner): FormState { return { id: banner.id, zone: banner.zone, desktopImageUrl: banner.desktopImageUrl, mobileImageUrl: banner.mobileImageUrl ?? "", altText: banner.altText, headline: banner.headline ?? "", subHeadline: banner.subHeadline ?? "", ctaLabel: banner.ctaLabel ?? "", linkKind: banner.linkKind ?? "NONE", linkReference: banner.linkReference ?? "", displayOrder: banner.displayOrder != null ? String(banner.displayOrder) : "", dateFrom: banner.dateFrom ?? "", dateTo: banner.dateTo ?? "", status: banner.status, }; } /** Reads a File as base64 with the `data:...;base64,` prefix stripped. */ function fileToBase64(file: File): Promise { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = () => { const dataUrl = String(reader.result ?? ""); const comma = dataUrl.indexOf(","); resolve(comma >= 0 ? dataUrl.slice(comma + 1) : dataUrl); }; reader.onerror = () => reject(new Error("UiImageReadFailed")); reader.readAsDataURL(file); }); } function toPayload(form: FormState, desktopImageUrl: string, mobileImageUrl: string): AdminBanner { return { id: form.id, zone: form.zone, desktopImageUrl, mobileImageUrl: mobileImageUrl || undefined, altText: form.altText.trim(), headline: form.headline.trim() || undefined, subHeadline: form.subHeadline.trim() || undefined, ctaLabel: form.ctaLabel.trim() || undefined, // Always sent explicitly (default "NONE") -- never omitted -- and the reference is dropped // whenever the kind is NONE, matching the route handler's validation. linkKind: form.linkKind, linkReference: form.linkKind === "NONE" ? undefined : form.linkReference.trim(), displayOrder: form.displayOrder === "" ? undefined : Number(form.displayOrder), dateFrom: form.dateFrom || undefined, dateTo: form.dateTo || undefined, status: form.status, }; } /** Mirrors app/api/banners/route.ts's POST/PUT validation, plus the displayOrder >= 0 rule. */ function validate(form: FormState, hasDesktopImage: boolean): string | null { if (!hasDesktopImage) return "BnrDesktopImageRequired"; if (!form.altText.trim()) return "BnrAltTextRequired"; if (form.linkKind !== "NONE" && !form.linkReference.trim()) { return "BnrLinkReferenceRequired"; } if (form.dateFrom && form.dateTo && new Date(form.dateFrom) >= new Date(form.dateTo)) { return "UiDateOrder"; } if (form.displayOrder !== "" && Number(form.displayOrder) < 0) { return "BnrDisplayOrderMin"; } return null; } /** Placeholder text for the link-reference field, per link kind. */ function referencePlaceholder(linkKind: BannerLinkKind): string { switch (linkKind) { case "PRODUCT": return "BnrRefPlaceholderProduct"; case "CATEGORY": return "BnrRefPlaceholderCategory"; case "URL": return "BnrRefPlaceholderUrl"; default: return ""; } } export function BannerFormDialog({ mode, banner, defaultZone, onClose, onSaved, }: { mode: "add" | "edit"; /** Required in edit mode; ignored (defaultZone is used instead) in add mode. */ banner?: AdminBanner; /** The zone a new banner starts with -- normally the page's current zone filter. */ defaultZone: BannerZone; onClose: () => void; onSaved: () => void; }) { const t = useT(); const [form, setForm] = useState(() => mode === "edit" && banner ? toFormState(banner) : emptyForm(defaultZone), ); const [saving, setSaving] = useState(false); const [error, setError] = useState<{ code: string; params?: MessageParams } | null>(null); // Upload-on-submit (mirrors BulletinFormDialog): a picked file is held locally and shown as a // blob: preview; nothing is uploaded until Save runs, so an abandoned form uploads nothing. const [desktopFile, setDesktopFile] = useState(null); const [desktopPreviewUrl, setDesktopPreviewUrl] = useState(null); const [mobileFile, setMobileFile] = useState(null); const [mobilePreviewUrl, setMobilePreviewUrl] = useState(null); useEffect(() => { return () => { if (desktopPreviewUrl && typeof URL.revokeObjectURL === "function") { URL.revokeObjectURL(desktopPreviewUrl); } if (mobilePreviewUrl && typeof URL.revokeObjectURL === "function") { URL.revokeObjectURL(mobilePreviewUrl); } }; }, [desktopPreviewUrl, mobilePreviewUrl]); function pickDesktopImage(file: File | undefined | null) { if (!file) return; setDesktopPreviewUrl(URL.createObjectURL(file)); setDesktopFile(file); } function removeDesktopImage() { setDesktopFile(null); setDesktopPreviewUrl(null); setForm((f) => ({ ...f, desktopImageUrl: "" })); } function pickMobileImage(file: File | undefined | null) { if (!file) return; setMobilePreviewUrl(URL.createObjectURL(file)); setMobileFile(file); } function removeMobileImage() { setMobileFile(null); setMobilePreviewUrl(null); setForm((f) => ({ ...f, mobileImageUrl: "" })); } async function handleSubmit(event: FormEvent) { event.preventDefault(); setError(null); const hasDesktopImage = Boolean(desktopFile) || Boolean(form.desktopImageUrl); const validationError = validate(form, hasDesktopImage); if (validationError) { setError({ code: validationError }); return; } setSaving(true); try { let desktopImageUrl = form.desktopImageUrl; if (desktopFile) { const base = await fileToBase64(desktopFile); try { const res = await uploadBannerImage({ fileName: desktopFile.name, fileType: desktopFile.type, base, zone: form.zone, }); desktopImageUrl = res.url; } catch (err) { // Upload failure BLOCKS the save: a banner must never be persisted referencing an // image that failed to upload. The finally below resets saving. setError( err instanceof ApiError ? { code: "BnrDesktopUploadFailedWith", params: { message: t(err.message) } } : { code: "BnrDesktopUploadFailed" }, ); return; } } let mobileImageUrl = form.mobileImageUrl; if (mobileFile) { const base = await fileToBase64(mobileFile); try { const res = await uploadBannerImage({ fileName: mobileFile.name, fileType: mobileFile.type, base, zone: form.zone, }); mobileImageUrl = res.url; } catch (err) { setError( err instanceof ApiError ? { code: "BnrMobileUploadFailedWith", params: { message: t(err.message) } } : { code: "BnrMobileUploadFailed" }, ); return; } } await saveBanner(toPayload(form, desktopImageUrl, mobileImageUrl)); onSaved(); onClose(); } catch (err) { setError({ code: err instanceof Error ? err.message : "BnrSaveFailed" }); } finally { setSaving(false); } } return ( !open && onClose()}> {t(mode === "add" ? "BnrNewBanner" : "BnrEditBanner")} {error && }
{form.zone === "CAMPAIGN" && (

{t("BnrCampaignNotShown")}

)}
{desktopPreviewUrl ?? form.desktopImageUrl ? ( {t("BnrDesktopImagePreview")} ) : (

{t("CatNoImageSelected")}

)} { pickDesktopImage(e.target.files?.[0]); e.target.value = ""; // allow re-picking the same file }} disabled={saving} /> {(desktopPreviewUrl ?? form.desktopImageUrl) && ( )}
{mobilePreviewUrl ?? form.mobileImageUrl ? ( {t("BnrMobileImagePreview")} ) : (

{t("CatNoImageSelected")}

)} { pickMobileImage(e.target.files?.[0]); e.target.value = ""; }} disabled={saving} /> {(mobilePreviewUrl ?? form.mobileImageUrl) && ( )}
setForm((f) => ({ ...f, altText: e.target.value }))} disabled={saving} />
setForm((f) => ({ ...f, headline: e.target.value }))} disabled={saving} />
setForm((f) => ({ ...f, subHeadline: e.target.value }))} disabled={saving} />
setForm((f) => ({ ...f, ctaLabel: e.target.value }))} disabled={saving} />
{form.linkKind !== "NONE" && (
setForm((f) => ({ ...f, linkReference: e.target.value }))} disabled={saving} />
)}
setForm((f) => ({ ...f, displayOrder: e.target.value }))} disabled={saving} />
); }