'use client'; import React, { useState, useEffect, useRef } from 'react'; import { useSearchParams } from 'next/navigation'; import { MessageSquare, QrCode, RefreshCw, Send, CheckCircle2, AlertCircle, Lock, Smartphone, } from 'lucide-react'; import { toast } from 'sonner'; import { IntegrationsHeaderNav } from '@/components/integrations/IntegrationsHeaderNav'; import { CustomSelect } from '@/components/ui/CustomSelect'; import { integrationService } from '@/services/api/integrationService'; 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 disabled:opacity-60'; 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 labelClass = 'block text-[11px] font-semibold text-muted-foreground uppercase mb-1.5'; export default function WhatsAppIntegrationsPage() { const searchParams = useSearchParams(); const initialTab = searchParams.get('tab') === 'wati' ? 'wati' : 'openwa'; const [activeSubTab, setActiveSubTab] = useState<'openwa' | 'wati'>(initialTab); // ------------------------------------------------------------- // OpenWA State // ------------------------------------------------------------- const [openwaStatus, setOpenwaStatus] = useState({ status: 'LOADING', qr_code: null, phone: null, push_name: null, }); const [openwaLoading, setOpenwaLoading] = useState(true); const [restarting, setRestarting] = useState(false); const [testPhone, setTestPhone] = useState(''); const [testMessage, setTestMessage] = useState('Test verification message from iFixKart ERP WhatsApp Gateway'); const [sendingTest, setSendingTest] = useState(false); const pollTimerRef = useRef(null); // ------------------------------------------------------------- // WATI State // ------------------------------------------------------------- const [watiCreds, setWatiCreds] = useState({ api_endpoint: 'https://live-mt-server.wati.io', api_token: '', source: 'unconfigured', is_locked_by_config: false, }); const [watiLoading, setWatiLoading] = useState(true); const [watiTesting, setWatiTesting] = useState(false); const [watiSaving, setWatiSaving] = useState(false); const [watiTemplates, setWatiTemplates] = useState([]); const [templatesLoading, setTemplatesLoading] = useState(false); const [selectedTemplate, setSelectedTemplate] = useState(''); const [watiRecipientPhone, setWatiRecipientPhone] = useState(''); const [sendingWatiTemplate, setSendingWatiTemplate] = useState(false); // Fetch OpenWA QR status const fetchOpenWaStatus = async (showToast = false) => { try { const res = await integrationService.getWhatsappQr(); setOpenwaStatus(res); if (showToast) { toast.success(`OpenWA Gateway: ${res.status}`); } } catch (err: any) { setOpenwaStatus({ status: 'OFFLINE', message: err.message || 'Cannot reach OpenWA service' }); } finally { setOpenwaLoading(false); } }; // Poll QR code if in QR_READY or INITIALIZING useEffect(() => { if (activeSubTab === 'openwa') { fetchOpenWaStatus(); if (pollTimerRef.current) clearInterval(pollTimerRef.current); pollTimerRef.current = setInterval(() => { fetchOpenWaStatus(); }, 4500); } else { if (pollTimerRef.current) clearInterval(pollTimerRef.current); } return () => { if (pollTimerRef.current) clearInterval(pollTimerRef.current); }; }, [activeSubTab]); // Fetch WATI credentials and templates const fetchWatiData = async () => { setWatiLoading(true); try { const creds = await integrationService.getWatiCredentials(); setWatiCreds(creds); if (creds.api_token) { loadTemplates(); } } catch (err: any) { toast.error('Failed to load WATI configuration'); } finally { setWatiLoading(false); } }; const loadTemplates = async () => { setTemplatesLoading(true); try { const res = await integrationService.getWatiTemplates(); setWatiTemplates(res.templates || []); } catch (err) { console.warn('WATI templates error:', err); } finally { setTemplatesLoading(false); } }; useEffect(() => { if (activeSubTab === 'wati') { fetchWatiData(); } }, [activeSubTab]); // Restart OpenWA session const handleRestartOpenWa = async () => { setRestarting(true); try { await integrationService.restartWhatsappSession(); toast.info('Session restart initiated. Generating fresh QR code...'); setTimeout(() => fetchOpenWaStatus(), 2000); } catch (err: any) { toast.error(err.message || 'Failed to restart WhatsApp session'); } finally { setRestarting(false); } }; // Send OpenWA Test Message const handleSendOpenWaTest = async (e: React.FormEvent) => { e.preventDefault(); if (!testPhone.trim()) { toast.error('Please enter a valid phone number'); return; } setSendingTest(true); try { const res = await integrationService.sendWhatsappTest(testPhone.trim(), testMessage.trim()); if (res.status === 'SUCCESS') { toast.success(`Message sent successfully to ${testPhone}!`); } else { toast.error(`Send failed: ${res.detail || JSON.stringify(res)}`); } } catch (err: any) { toast.error(err.message || 'Failed to send WhatsApp message'); } finally { setSendingTest(false); } }; // Test WATI Connection const handleTestWati = async () => { setWatiTesting(true); try { const res = await integrationService.testWatiConnection({ api_endpoint: watiCreds.api_endpoint, api_token: watiCreds.api_token, }); if (res.status === 'SUCCESS') { toast.success(`Connected! ${res.templates_count || 0} approved templates discovered.`); setWatiTemplates(res.templates || []); } else { toast.error(`Connection failed: ${res.detail || 'Invalid token or endpoint'}`); } } catch (err: any) { toast.error(err.message || 'WATI test connection failed'); } finally { setWatiTesting(false); } }; // Save WATI Credentials const handleSaveWati = async (e: React.FormEvent) => { e.preventDefault(); setWatiSaving(true); try { await integrationService.saveWatiCredentials({ api_endpoint: watiCreds.api_endpoint, api_token: watiCreds.api_token, }); toast.success('WATI credentials saved successfully'); loadTemplates(); } catch (err: any) { toast.error(err.message || 'Failed to save WATI credentials'); } finally { setWatiSaving(false); } }; // Send WATI template message const handleSendWatiTemplate = async (e: React.FormEvent) => { e.preventDefault(); if (!watiRecipientPhone.trim() || !selectedTemplate) { toast.error('Select a template and enter a valid recipient phone number'); return; } setSendingWatiTemplate(true); try { const res = await integrationService.sendWatiTemplate({ phone: watiRecipientPhone.trim(), template_name: selectedTemplate, broadcast_name: `test_${Date.now()}`, }); if (res.status === 'SUCCESS') { toast.success('WATI template message dispatched successfully!'); } else { toast.error(`Dispatch failed: ${res.detail || JSON.stringify(res)}`); } } catch (err: any) { toast.error(err.message || 'Failed to send WATI template'); } finally { setSendingWatiTemplate(false); } }; return (

WhatsApp

{/* ========================================================================= */} {/* TAB A: OPENWA (INTERNAL LIVE QR SCANNER) */} {/* ========================================================================= */} {activeSubTab === 'openwa' && (

Internal Staff Gateway (OpenWA Live QR)

{/* QR Scanner Card (Cols 1-7) */}

Session Connection State

{openwaLoading ? (

Checking session

) : openwaStatus.status === 'CONNECTED' ? (

Connected

{openwaStatus.phone ? `+${openwaStatus.phone}` : '—'} {openwaStatus.push_name ? ` · ${openwaStatus.push_name}` : ''}

) : openwaStatus.qr_code ? (
WhatsApp Scan QR
QR ready

WhatsApp → Settings → Linked devices → Link a device

) : (

Status: {openwaStatus.status || 'OFFLINE'}

{openwaStatus.message || 'Session is initializing or waiting for gateway response.'}

)}
{/* Test Send Form (Cols 8-12) */}

Direct Test Dispatch

setTestPhone(e.target.value)} className={fieldClass} />