"use client"; import { useState, useCallback } from "react"; import { useRouter } from "next/navigation"; import Link from "next/link"; import type { Template, TemplateType, CampaignType } from "@/actions/communications/templates"; import { formatDate } from "@/lib/format-date"; import { upsertTemplate } from "@/actions/communications/templates"; import { BUILT_IN_TEMPLATES, renderTemplate, TEMPLATE_VARIABLES, type EmailTemplate, } from "@/lib/email-templates"; const TEMPLATE_TYPES: { value: TemplateType; label: string }[] = [ { value: "email_template", label: "Email" }, { value: "sms_template", label: "SMS" }, { value: "internal_note", label: "Internal Note" }, ]; const CAMPAIGN_TYPES: { value: CampaignType; label: string }[] = [ { value: "operational", label: "Operational" }, { value: "marketing", label: "Marketing" }, { value: "transactional", label: "Transactional" }, ]; const TYPE_COLORS: Record = { email_template: "bg-blue-100 text-blue-700", sms_template: "bg-emerald-100 text-emerald-700", internal_note: "bg-stone-100 text-stone-600", }; // Sample variables for preview rendering const SAMPLE_VARS: Record = { first_name: "Jane", company_name: "Route Commerce", stop_name: "Tuxedo Warehouse", pickup_date: "May 15, 2026", order_total: "$450.00", balance_due: "$225.00", due_date: "May 10, 2026", item_summary: "10× Tuxedo Set, 5× Dress Shirt", custom_message: "We look forward to seeing you!", cta_text: "Shop Now", cta_url: "https://routecommerce.com", tag: "New Arrivals", headline: "Spring Collection is Here!", unsubscribe_url: "#", }; // Icon components const Icons = { plus: (className: string) => ( ), x: (className: string) => ( ), fileText: (className: string) => ( ), arrowRight: (className: string) => ( ), }; // New Template Modal function NewTemplateModal({ isOpen, onClose, onSuccess, brandId }: { isOpen: boolean; onClose: () => void; onSuccess: () => void; brandId: string; }) { const router = useRouter(); const [saving, setSaving] = useState(false); const [name, setName] = useState(""); const [templateType, setTemplateType] = useState("email_template"); const [error, setError] = useState(""); if (!isOpen) return null; const handleCreate = async () => { if (!name.trim()) { setError("Template name is required"); return; } setSaving(true); setError(""); const result = await upsertTemplate({ brand_id: brandId, name: name.trim(), subject: "", body_text: "", template_type: templateType, }); setSaving(false); if (!result.success) { setError(result.error ?? "Failed to create template"); return; } setName(""); setTemplateType("email_template"); onSuccess(); router.refresh(); }; return (
{/* Backdrop */}
{/* Modal */}
{/* Header */}
{Icons.fileText("h-5 w-5 text-white")}

New Template

Create a new email template

{/* Content */}
{error && (
{error}
)}
setName(e.target.value)} className="w-full border border-[var(--admin-border)] rounded-lg px-3 py-2.5 text-sm bg-white text-[var(--admin-text-primary)] focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500 outline-none" placeholder="e.g. Pickup Reminder" autoFocus />
{/* Footer */}
); } export function TemplateListPanel({ templates, brandId = "64294306-5f42-463d-a5e8-2ad6c81a96de" }: { templates: Template[], brandId?: string }) { const router = useRouter(); const [showNewModal, setShowNewModal] = useState(false); return (
setShowNewModal(false)} onSuccess={() => { setShowNewModal(false); router.refresh(); }} brandId={brandId} /> {/* Header */}
{Icons.fileText("w-4 h-4 text-[var(--admin-bg)]")}

Templates

{templates.length} template{templates.length !== 1 ? "s" : ""}

{/* Table */} {templates.length === 0 ? (
No templates yet
) : (
{templates.map((t) => ( router.push(`/admin/communications/templates/${t.id}`)} > ))}
Name Type Subject Updated
{t.name} {t.template_type} {t.subject} {formatDate(new Date(t.updated_at))} {Icons.arrowRight("h-4 w-4 text-[var(--admin-text-muted)]")}
)}
); } export function TemplateEditForm({ template, mode = "edit", brandId, }: { template?: Template; mode?: "edit" | "new"; brandId: string; }) { const router = useRouter(); const [saving, setSaving] = useState(false); const [name, setName] = useState(template?.name ?? ""); const [subject, setSubject] = useState(template?.subject ?? ""); const [bodyText, setBodyText] = useState(template?.body_text ?? ""); const [bodyHtml, setBodyHtml] = useState(template?.body_html ?? ""); const [templateType, setTemplateType] = useState(template?.template_type ?? "email_template"); const [campaignType, setCampaignType] = useState(template?.campaign_type ?? ""); const [error, setError] = useState(""); const [activeTab, setActiveTab] = useState<"edit" | "preview">("edit"); const [previewDevice, setPreviewDevice] = useState<"desktop" | "mobile">("desktop"); const [htmlMode, setHtmlMode] = useState(!!template?.body_html); // Apply a built-in template to the editor fields function applyBuiltIn(tpl: EmailTemplate) { const rendered = renderTemplate(tpl, SAMPLE_VARS); setName(tpl.name); setSubject(rendered.subject); setBodyText(rendered.body_text); setBodyHtml(rendered.body_html); setHtmlMode(true); } function insertVariable(key: string) { const token = `{{${key}}}`; const ta = document.getElementById("body-textarea") as HTMLTextAreaElement; if (ta) { const start = ta.selectionStart; const end = ta.selectionEnd; const next = bodyText.slice(0, start) + token + bodyText.slice(end); setBodyText(next); setTimeout(() => { ta.focus(); ta.setSelectionRange(start + token.length, start + token.length); }, 0); } else { setBodyText((prev) => prev + "\n" + token); } } const preview = { subject: subject || "Your Email Subject", body_text: bodyText, body_html: bodyHtml || `

${bodyText}

`, }; const handleSave = async () => { setSaving(true); setError(""); const result = await upsertTemplate({ id: template?.id, brand_id: brandId, name, subject, body_text: bodyText, body_html: (htmlMode && bodyHtml) ? bodyHtml : undefined, template_type: templateType, campaign_type: (campaignType as CampaignType) || undefined, }); setSaving(false); if (!result.success) { setError(result.error ?? "Failed to save"); return; } router.push("/admin/communications/templates"); router.refresh(); }; return (
{/* Header */}
{Icons.fileText("w-4 h-4 text-[var(--admin-bg)]")}

{mode === "new" ? "New Template" : "Edit Template"}

{mode === "new" ? "Create a new email template" : "Update template settings"}

{error && (
{error}
)} {activeTab === "edit" ? (
{/* Basic info */}

Template Info

{/* Built-in template picker */}
Start from:
setName(e.target.value)} className="w-full border border-[var(--admin-border)] rounded-lg px-3 py-2 text-sm bg-white text-[var(--admin-text-primary)]" placeholder="e.g. Pickup Reminder" />
{/* Subject */}

Subject Line

setSubject(e.target.value)} className="w-full border border-[var(--admin-border)] rounded-lg px-3 py-2 text-sm bg-white text-[var(--admin-text-primary)]" placeholder="Email subject line" />

Variables:{" "} {TEMPLATE_VARIABLES.slice(0, 6).map((v) => ( ))}

{/* Body editor */}

Message Body

{/* Variable toolbar */}
Insert: {TEMPLATE_VARIABLES.map((v) => ( ))}
{htmlMode ? ( <>