'use client'; import { useEffect, useState, useRef, useCallback, Suspense } from 'react'; import { useSearchParams, useRouter } from 'next/navigation'; import { openwaService, type OWASession, type OWAChat, type OWAMessage, type OWAContact, } from '@/services/api/openwaService'; import { Send, Search, CheckCheck, Paperclip, Phone, RefreshCw, ArrowLeft, QrCode, Loader2, WifiOff, Pin, } from 'lucide-react'; import { toast } from 'sonner'; import { SlideOver } from '@/components/ui/SlideOver'; const field = 'w-full h-9 pl-9 pr-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'; // ─── Helpers ───────────────────────────────────────────────────────────────── function formatTimestamp(ts: number | string): string { if (!ts) return ''; const date = typeof ts === 'number' ? new Date(ts * 1000) : new Date(ts); if (isNaN(date.getTime())) return ''; const now = new Date(); const diffMs = now.getTime() - date.getTime(); const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24)); if (diffDays === 0) return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }); if (diffDays === 1) return 'Yesterday'; if (diffDays < 7) return date.toLocaleDateString([], { weekday: 'short' }); return date.toLocaleDateString([], { day: '2-digit', month: 'short' }); } function formatMessageTime(ts: number | string): string { if (!ts) return ''; const date = typeof ts === 'number' ? new Date(ts * 1000) : new Date(ts); if (isNaN(date.getTime())) return ''; return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }); } function getNameFromChat(chat: OWAChat, contacts: OWAContact[]): string { if (chat.name && chat.name !== chat.id && !/^\d+$/.test(chat.name)) return chat.name; // Try to match from contacts by id or number const phoneRaw = chat.id.replace(/@.*/, ''); const contact = contacts.find((c) => c.number === phoneRaw || c.id === chat.id); if (contact?.name) return contact.name; // Format phone if (phoneRaw.length >= 10) { return `+${phoneRaw.slice(0, 2)} ${phoneRaw.slice(2, 7)} ${phoneRaw.slice(7)}`; } return chat.id.split('@')[0]; } function getInitial(name: string): string { return (name || '?').charAt(0).toUpperCase(); } // ─── Active conversation state ──────────────────────────────────────────────── interface LocalMessage { id: string; body: string; direction: 'incoming' | 'outgoing'; timestamp: number; type: string; status?: string; } // ─── Main component ────────────────────────────────────────────────────────── function WhatsAppWebContent() { const searchParams = useSearchParams(); const router = useRouter(); const paramPhone = searchParams.get('phone') || ''; const paramName = searchParams.get('name') || ''; // Session const [session, setSession] = useState(null); const [sessionLoading, setSessionLoading] = useState(true); // Chats const [chats, setChats] = useState([]); const [contacts, setContacts] = useState([]); const [chatsLoading, setChatsLoading] = useState(false); // Active chat const [activeChatId, setActiveChatId] = useState(''); const [messages, setMessages] = useState([]); const [messagesLoading, setMessagesLoading] = useState(false); // UI const [searchQuery, setSearchQuery] = useState(''); const [activeTab, setActiveTab] = useState<'ALL' | 'UNREAD' | 'GROUPS'>('ALL'); const [inputText, setInputText] = useState(''); const [isSending, setIsSending] = useState(false); // Confirm-before-send state const [pendingMessage, setPendingMessage] = useState<{ text: string; chatId: string; recipientName: string; recipientPhone: string } | null>(null); const messagesEndRef = useRef(null); const pollingRef = useRef | null>(null); // ── Load session ──────────────────────────────────────────────────────────── const loadSession = useCallback(async () => { try { setSessionLoading(true); const sess = await openwaService.getReadySession(); setSession(sess); return sess; } catch { setSession(null); return null; } finally { setSessionLoading(false); } }, []); // ── Load chats + contacts ──────────────────────────────────────────────────── const loadChats = useCallback(async (sessionId: string) => { try { setChatsLoading(true); const [chatList, contactList] = await Promise.all([ openwaService.getChats(sessionId, 100), openwaService.getContacts(sessionId, 200).catch(() => [] as OWAContact[]), ]); setContacts(contactList); // Sort chats: pinned first, then by timestamp desc const sorted = [...chatList].sort((a, b) => { if (a.pinned && !b.pinned) return -1; if (!a.pinned && b.pinned) return 1; return b.timestamp - a.timestamp; }); setChats(sorted); // Auto-select: if URL param phone, find that chat or construct target ID if (paramPhone) { const cleanDigits = paramPhone.replace(/\D/g, ''); const fullPhone = cleanDigits.length === 10 ? `91${cleanDigits}` : cleanDigits; const targetId = fullPhone.includes('@') ? fullPhone : `${fullPhone}@c.us`; const found = sorted.find((c) => c.id.includes(cleanDigits)); if (found) { setActiveChatId(found.id); } else { setActiveChatId(targetId); } } else if (!activeChatId && sorted.length > 0) { setActiveChatId(sorted[0].id); } } catch (err) { console.error('Failed to load chats', err); toast.error('Failed to load WhatsApp chats'); } finally { setChatsLoading(false); } }, [paramPhone, activeChatId]); // ── Load messages for active chat ──────────────────────────────────────────── const loadMessages = useCallback(async (sessionId: string, chatId: string) => { if (!chatId) return; try { setMessagesLoading(true); const res = await openwaService.getMessages(sessionId, { chatId, limit: 50 }); const sorted = [...(res.messages || [])].sort((a, b) => a.timestamp - b.timestamp); setMessages( sorted.map((m) => ({ id: m.id, body: m.body || (m.type !== 'text' ? `[${m.type}]` : ''), direction: m.direction, timestamp: m.timestamp, type: m.type, status: m.status, })) ); } catch { setMessages([]); } finally { setMessagesLoading(false); } }, []); // ── Init ────────────────────────────────────────────────────────────────── useEffect(() => { (async () => { const sess = await loadSession(); if (sess?.id) { await loadChats(sess.id); } })(); }, []); // eslint-disable-line react-hooks/exhaustive-deps // ── Load messages on chat switch ───────────────────────────────────────────── useEffect(() => { if (session?.id && activeChatId) { loadMessages(session.id, activeChatId); } }, [session?.id, activeChatId, loadMessages]); // ── Scroll to bottom ────────────────────────────────────────────────────────── useEffect(() => { messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' }); }, [messages]); // ── Polling (refresh messages every 10s) ──────────────────────────────────── useEffect(() => { if (pollingRef.current) clearInterval(pollingRef.current); if (session?.id && activeChatId) { pollingRef.current = setInterval(() => { loadMessages(session.id, activeChatId); }, 10000); } return () => { if (pollingRef.current) clearInterval(pollingRef.current); }; }, [session?.id, activeChatId, loadMessages]); // ── Send message ────────────────────────────────────────────────────────────── /** Stage a message for confirmation — does NOT send yet */ const handleSend = (textOverride?: string) => { const text = (textOverride || inputText).trim(); if (!text || !session?.id || !activeChatId) return; const activeChat = chats.find((c) => c.id === activeChatId); const recipientName = activeChat ? getNameFromChat(activeChat, contacts) : activeChatId; const recipientPhone = activeChatId.replace(/@.*/, ''); // Show confirmation dialog setPendingMessage({ text, chatId: activeChatId, recipientName, recipientPhone }); }; /** Actually send after user confirmed */ const confirmSend = async () => { if (!pendingMessage || !session?.id) return; const { text, chatId } = pendingMessage; setPendingMessage(null); try { setIsSending(true); await openwaService.sendText(session.id, chatId, text); // Optimistic update setMessages((prev) => [ ...prev, { id: `local-${Date.now()}`, body: text, direction: 'outgoing', timestamp: Math.floor(Date.now() / 1000), type: 'text', status: 'sent', }, ]); setInputText(''); toast.success('Message sent via OpenWA!'); // Refresh messages after 2s setTimeout(() => { if (session?.id && chatId) loadMessages(session.id, chatId); }, 2000); } catch (err: unknown) { const msg = err instanceof Error ? err.message : 'Failed to send'; toast.error(msg); } finally { setIsSending(false); } }; const handleTemplate = (type: 'QUOTE' | 'REPAIR' | 'PICKUP') => { const activeChat = chats.find((c) => c.id === activeChatId); const name = activeChat ? getNameFromChat(activeChat, contacts) : 'Customer'; const templates: Record = { QUOTE: `Hello ${name},\n\nHere is your official iFixKart quotation for repair services. We offer a 6-Month IMEI Warranty & Free Doorstep Return.\n\nThank you for choosing iFixKart! 🔧`, REPAIR: `Hello ${name},\n\nYour device diagnosis is complete! ✅ All OEM parts passed our 24-point quality inspection. We are proceeding with the repair now.`, PICKUP: `Hello ${name},\n\n🎉 Great news! Your repair is COMPLETED. Your device is ready for doorstep delivery or counter pickup at your convenience.`, }; handleSend(templates[type]); }; // ── Filter chats ────────────────────────────────────────────────────────────── const filteredChats = chats.filter((c) => { const name = getNameFromChat(c, contacts).toLowerCase(); const matchesSearch = name.includes(searchQuery.toLowerCase()) || c.id.includes(searchQuery); if (activeTab === 'UNREAD') return matchesSearch && c.unreadCount > 0; if (activeTab === 'GROUPS') return matchesSearch && c.isGroup; return matchesSearch; }); const activeChat = chats.find((c) => c.id === activeChatId); const activeName = activeChat ? getNameFromChat(activeChat, contacts) : ''; const isConnected = session?.status === 'ready'; // ── Render ──────────────────────────────────────────────────────────────────── return ( <>

WhatsApp

{sessionLoading ? ( Connecting ) : isConnected ? ( {session?.pushName || session?.phone || 'Connected'} ) : ( Disconnected )} {isConnected ? [session?.name, session?.phone].filter(Boolean).join(' · ') : 'Not connected'}
{/* LEFT: Chat List */}
setSearchQuery(e.target.value)} placeholder="Search" className={field} />
{(['ALL', 'UNREAD', 'GROUPS'] as const).map((tab) => ( ))}

{chatsLoading ? ( Loading chats ) : ( {filteredChats.length} chats )}

{/* Chat Items */}
{!isConnected && !sessionLoading && (

Not connected

)} {filteredChats.map((c) => { const name = getNameFromChat(c, contacts); const isActive = c.id === activeChatId; const timeStr = c.timestamp ? formatTimestamp(c.timestamp) : ''; return ( ); })} {!chatsLoading && isConnected && filteredChats.length === 0 && (

No chats

)}
{/* RIGHT: Conversation */} {activeChatId && activeChat ? (
{/* Header */}
{getInitial(activeName)}

{activeName}

{activeChatId.replace(/@.*/, '')} {activeChat.isGroup && Group}

{/* Messages */}
{messagesLoading && (
)} {!messagesLoading && messages.length === 0 && (

No messages

)} {messages.map((m) => { const isOut = m.direction === 'outgoing'; return (

{m.body || [{m.type}]}

{formatMessageTime(m.timestamp)} {isOut && }
); })}
{/* Input */}
setInputText(e.target.value)} onKeyDown={(e) => e.key === 'Enter' && !e.shiftKey && handleSend()} placeholder={isConnected ? 'Message' : 'Connect WhatsApp to send messages'} disabled={!isConnected} className="flex-1 h-9 px-3 bg-card border border-border crm-radius-control text-[13px] text-foreground focus:outline-none focus:border-primary disabled:opacity-50" />
) : (
{isConnected ? (

Select a chat

) : sessionLoading ? ( Connecting ) : (

Not connected

)}
)}
{/* ── Confirm-before-Send Modal ── */} setPendingMessage(null)} title="Send message" size="compact" > {pendingMessage && (

To

{pendingMessage.recipientName}

+{pendingMessage.recipientPhone}

{pendingMessage.text}

)}
); } // ─── Page wrapper ───────────────────────────────────────────────────────────── export default function WhatsAppWebPage() { return ( Loading WhatsApp
}> ); }