'use client'; import { useEffect, useState, useCallback } from 'react'; import { openwaService, type OWASession } from '@/services/api/openwaService'; import { roleNotificationSettingsService, type RoleNotificationSetting } from '@/services/api/roleNotificationSettingsService'; import { rolePermissionService } from '@/services/api/rolePermissionService'; import { RefreshCw, Send, Loader2, Phone, User, Plus, Trash2, } from 'lucide-react'; import { toast } from 'sonner'; import { CustomSelect } from '@/components/ui/CustomSelect'; const field = 'w-full h-9 px-3 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 disabled:opacity-50'; const shell = 'crm-radius-section border border-border bg-card shadow-[0_1px_3px_rgba(16,24,40,0.06)] min-w-0'; const EVENT_TYPES = [ { value: 'ORDER_STATUS_CHANGED', label: 'Order status changed' }, { value: 'NEW_ORDER_ALERT', label: 'New order' }, { value: 'SERVICE_BOOKED_INTERNAL', label: 'Service booked' }, { value: 'SERVICE_STATUS_CHANGED', label: 'Service status changed' }, { value: 'INVENTORY_LOW_STOCK', label: 'Low stock' }, { value: 'REFUND_TRIGGERED', label: 'Refund' }, { value: 'END_OF_DAY_REPORT', label: 'End of day report' }, { value: 'REPAIR_SLA_BREACH', label: 'Repair SLA breach' }, ]; function eventLabel(value: string) { return EVENT_TYPES.find((event) => event.value === value)?.label || value.replaceAll('_', ' ').toLowerCase(); } export default function NotificationsGatewayPage() { const [activeTab, setActiveTab] = useState<'gateway' | 'rules'>('gateway'); // Gateway State const [sessions, setSessions] = useState([]); const [health, setHealth] = useState<{ status: string; version: string; timestamp: string } | null>(null); const [loading, setLoading] = useState(true); // Send message form const [recipient, setRecipient] = useState(''); const [message, setMessage] = useState(''); const [sending, setSending] = useState(false); const [confirming, setConfirming] = useState(false); // Rules State const [rules, setRules] = useState([]); const [roles, setRoles] = useState<{ role_id: string; role_name: string }[]>([]); const [loadingRules, setLoadingRules] = useState(false); const [showAddForm, setShowAddForm] = useState(false); const [newRule, setNewRule] = useState({ role_name: '', event_type: 'ORDER_STATUS_CHANGED', channel_email: true, channel_whatsapp: false }); const loadGatewayData = useCallback(async () => { try { setLoading(true); const [sessionsRes, healthRes] = await Promise.all([ openwaService.getSessions().catch(() => [] as OWASession[]), openwaService.getHealth().catch(() => null), ]); setSessions(sessionsRes); setHealth(healthRes); } finally { setLoading(false); } }, []); const loadRulesData = useCallback(async () => { try { setLoadingRules(true); const [rulesRes, rolesRes] = await Promise.all([ roleNotificationSettingsService.getSettings().catch(() => []), rolePermissionService.getRoles().catch(() => []) ]); setRules(rulesRes); setRoles(rolesRes); } catch (error) { toast.error('Failed to load notification rules'); } finally { setLoadingRules(false); } }, []); useEffect(() => { if (activeTab === 'gateway') { loadGatewayData(); } else { loadRulesData(); } }, [activeTab, loadGatewayData, loadRulesData]); const handleCreateRule = async (e: React.FormEvent) => { e.preventDefault(); if (!newRule.role_name) return toast.error('Please select a role'); try { await roleNotificationSettingsService.createSetting(newRule); toast.success('Rule created'); setShowAddForm(false); loadRulesData(); } catch (err: any) { toast.error(err.message || 'Failed to create rule'); } }; const handleToggleChannel = async (settingId: string, channel: 'email' | 'whatsapp', currentValue: boolean) => { try { await roleNotificationSettingsService.updateSetting(settingId, { [channel === 'email' ? 'channel_email' : 'channel_whatsapp']: !currentValue }); loadRulesData(); } catch (err: any) { toast.error(err.message || 'Failed to update rule'); } }; const handleDeleteRule = async (settingId: string) => { if (!confirm('Are you sure you want to delete this rule?')) return; try { await roleNotificationSettingsService.deleteSetting(settingId); toast.success('Rule deleted'); loadRulesData(); } catch (err: any) { toast.error(err.message || 'Failed to delete rule'); } }; const handleSendMessage = async (e: React.FormEvent) => { e.preventDefault(); const readySession = sessions.find((s) => s.status === 'ready'); if (!readySession) { toast.error('No active WhatsApp session. Please pair your device first.'); return; } if (!recipient.trim() || !message.trim()) { toast.error('Please enter a recipient and message.'); return; } // First click: show confirmation if (!confirming) { setConfirming(true); return; } // Second click: actually send try { setSending(true); setConfirming(false); const cleaned = recipient.replace(/\D/g, ''); const chatId = cleaned.endsWith('@c.us') ? cleaned : `${cleaned}@c.us`; await openwaService.sendText(readySession.id, chatId, message); toast.success(`Message sent to +${cleaned}`); setRecipient(''); setMessage(''); } catch (err: unknown) { const msg = err instanceof Error ? err.message : 'Failed to send message'; toast.error(msg); } finally { setSending(false); } }; const primarySession = sessions.find((s) => s.status === 'ready') || sessions[0] || null; const isConnected = primarySession?.status === 'ready'; return (

WhatsApp & Notification Gateway

{activeTab === 'gateway' && ( <> {/* Health + Status Cards */}

Health

{loading ? (

Loading

) : health ? (

{health.status === 'ok' ? 'Healthy' : 'Unhealthy'}

{health.version &&

Version {health.version}

}
) : (

Unreachable

)}

WhatsApp

{loading ? (

Loading

) : primarySession ? (

{isConnected ? 'Connected' : primarySession.status}

{primarySession.pushName && (

{primarySession.pushName}

)} {primarySession.phone && (

{primarySession.phone}

)}

{primarySession.name}

{primarySession.connectedAt && (

Since {new Date(primarySession.connectedAt).toLocaleString()}

)}
) : (

No sessions

)}
{/* Sessions Table */} {sessions.length > 0 && (

Sessions

{sessions.length}
{sessions.map((sess) => ( ))}
Name Status Phone Name on WhatsApp Last active
{sess.name} {sess.status === 'ready' ? 'Connected' : sess.status} {sess.phone || 'โ€”'} {sess.pushName || 'โ€”'} {sess.lastActive ? new Date(sess.lastActive).toLocaleString() : 'โ€”'}
)}

Send message

{!isConnected && ( No active session )}