'use client'; import { useEffect, useState, useCallback } from 'react'; import { notificationTemplateService, type NotificationTemplate, type EventRegistry } from '@/services/api/notificationTemplateService'; import { Plus, Edit2, Eye, LayoutTemplate, MessageSquare, Mail, CheckCircle2, X, RefreshCw, Loader2 } from 'lucide-react'; import { toast } from 'sonner'; import { CustomSelect } from '@/components/ui/CustomSelect'; import dynamic from 'next/dynamic'; import 'react-quill-new/dist/quill.snow.css'; const ReactQuill = dynamic(() => import('react-quill-new'), { ssr: false }); export default function NotificationTemplatesPage() { const [templates, setTemplates] = useState([]); const [events, setEvents] = useState([]); const [loading, setLoading] = useState(true); const [isModalOpen, setIsModalOpen] = useState(false); const [editingTemplate, setEditingTemplate] = useState(null); // Form State const [form, setForm] = useState({ name: '', event_key: '', channel: 'EMAIL', subject: '', body_content: '', is_active: true }); // Preview State const [previewObj, setPreviewObj] = useState<{subject: string, body: string} | null>(null); const loadData = useCallback(async () => { try { setLoading(true); const [tpls, evts] = await Promise.all([ notificationTemplateService.getTemplates(), notificationTemplateService.getEvents() ]); setTemplates(tpls); setEvents(evts); } catch (err: any) { toast.error('Failed to load templates or events'); } finally { setLoading(false); } }, []); useEffect(() => { loadData(); }, [loadData]); const handleOpenCreate = () => { setEditingTemplate(null); setForm({ name: '', event_key: events[0]?.event_key || '', channel: 'EMAIL', subject: '', body_content: '', is_active: true }); setPreviewObj(null); setIsModalOpen(true); }; const handleOpenEdit = (t: NotificationTemplate) => { setEditingTemplate(t); setForm({ name: t.name, event_key: t.event_key, channel: t.channel, subject: t.subject || '', body_content: t.body_content, is_active: t.is_active }); setPreviewObj(null); setIsModalOpen(true); }; const handleToggle = async (id: string, current: boolean) => { try { await notificationTemplateService.toggleActivation(id, !current); toast.success('Template status updated'); loadData(); } catch (err: any) { toast.error(err.response?.data?.detail || err.message); } }; const handlePreview = async () => { const activeEvent = events.find(e => e.event_key === form.event_key); const mockContext: any = {}; if (activeEvent) { activeEvent.variables.forEach(v => { // Special case for items to render a fake list for the preview if (v.name === 'items') { mockContext[v.name] = [ { product_name: "Apple Camera Lens Guards for iPhone 16 Plus", sku: "IFK-APP-05334-V05", quantity: 1, unit_price: 4187.15 } ]; } else { mockContext[v.name] = v.example || `[${v.name}]`; } }); } try { const res = await notificationTemplateService.previewTemplateRaw(form.body_content, mockContext, form.subject); setPreviewObj(res); toast.success('Preview generated successfully!'); } catch (err: any) { toast.error(err.response?.data?.detail || err.message); } }; const loadDefaultTemplate = () => { if (form.channel === 'EMAIL' && form.event_key === 'ORDER_CREATED') { setForm({ ...form, subject: 'Order Confirmation & Tax Invoice #{{ invoice_no }} - iFixKart', body_content: `

Dear {{ customer_name }},


Thank you for your order! Your Tax Invoice #{{ invoice_no }} (Order Ref: {{ order_no }}) is attached as a PDF to this email.

` }); toast.success("Loaded Standard Template Design"); } else { toast.error("Standard template only available for ORDER_CREATED on EMAIL currently."); } }; const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); try { if (editingTemplate) { await notificationTemplateService.updateTemplate(editingTemplate.template_id, { name: form.name, subject: form.subject || undefined, body_content: form.body_content, is_active: form.is_active }); toast.success('Template updated'); } else { await notificationTemplateService.createTemplate(form); toast.success('Template created'); } setIsModalOpen(false); loadData(); } catch (err: any) { toast.error(err.response?.data?.detail || err.message); } }; const selectedEvent = events.find(e => e.event_key === form.event_key); const fieldClass = 'w-full h-9 px-3 bg-card border border-border crm-radius-control text-[13px] text-foreground focus:outline-none focus:border-primary disabled:opacity-60'; const areaClass = 'w-full px-3 py-2 bg-card border border-border crm-radius-control text-[13px] text-foreground focus:outline-none focus:border-primary'; const primaryButton = 'inline-flex items-center justify-center gap-1.5 h-9 px-3 crm-radius-control bg-primary hover:bg-primary/90 text-white text-[13px] font-semibold cursor-pointer disabled:opacity-50'; const secondaryButton = 'inline-flex items-center justify-center gap-1.5 h-9 px-3 crm-radius-control border border-border bg-card text-foreground text-[13px] font-medium hover:bg-muted cursor-pointer'; const shell = 'crm-radius-section border border-border bg-card shadow-[0_1px_3px_rgba(16,24,40,0.06)] min-w-0'; const labelClass = 'block text-[11px] font-semibold text-muted-foreground uppercase mb-1.5'; return (

Notification Templates

{templates.length}
{loading ? ( ) : templates.length === 0 ? ( ) : ( templates.map((tpl) => ( )) )}
Template Name Event Key Channel Variables Status Actions
No templates yet
{tpl.name} {tpl.event_key} {tpl.channel === 'EMAIL' ? : } {tpl.channel} {tpl.variables?.length || 0} vars
{/* Modal */} {isModalOpen && (

{editingTemplate ? 'Edit template' : 'Create template'}

setForm({...form, name: e.target.value})} className={fieldClass} placeholder="Name" />
setForm({...form, channel: value})} disabled={!!editingTemplate} options={[ { value: 'EMAIL', label: 'Email' }, { value: 'WHATSAPP', label: 'WhatsApp' }, ]} />
setForm({...form, event_key: value})} disabled={!!editingTemplate} placeholder="Select event" options={[ { value: '', label: 'Select event' }, ...events.map((ev) => ({ value: ev.event_key, label: ev.event_key })), ]} />
{form.channel === 'EMAIL' && (
setForm({...form, subject: e.target.value})} className={`${fieldClass} font-mono`} placeholder="Subject" />
)}
Body
{form.channel === 'EMAIL' ? (
setForm({...form, body_content: content})} modules={{ toolbar: [ [{ 'header': [1, 2, 3, false] }], ['bold', 'italic', 'underline', 'strike'], [{ 'color': [] }, { 'background': [] }], [{ 'list': 'ordered'}, { 'list': 'bullet' }], ['link', 'image'], ['clean'] ] }} />
) : (