ifixkart-admin/app/(admin)/whatsapp-web/page.tsx

652 lines
29 KiB
TypeScript

'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<OWASession | null>(null);
const [sessionLoading, setSessionLoading] = useState(true);
// Chats
const [chats, setChats] = useState<OWAChat[]>([]);
const [contacts, setContacts] = useState<OWAContact[]>([]);
const [chatsLoading, setChatsLoading] = useState(false);
// Active chat
const [activeChatId, setActiveChatId] = useState<string>('');
const [messages, setMessages] = useState<LocalMessage[]>([]);
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<HTMLDivElement>(null);
const pollingRef = useRef<ReturnType<typeof setInterval> | 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<string, string> = {
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 (
<>
<div className="min-h-[70dvh] h-[calc(100dvh-8.5rem)] sm:h-[calc(100dvh-9rem)] flex flex-col gap-3 min-w-0">
<div className={`${shell} px-4 py-3 flex flex-col sm:flex-row sm:items-center justify-between gap-3 shrink-0`}>
<div className="flex items-center gap-2 min-w-0">
<h1 className="text-lg font-semibold text-foreground">WhatsApp</h1>
{sessionLoading ? (
<span className="inline-flex items-center gap-1 px-2 py-0.5 crm-radius-badge text-[11px] font-semibold bg-muted text-muted-foreground">
<Loader2 className="w-3 h-3 animate-spin" />
Connecting
</span>
) : isConnected ? (
<span className="inline-flex items-center gap-1 px-2 py-0.5 crm-radius-badge text-[11px] font-semibold bg-success/15 text-success">
{session?.pushName || session?.phone || 'Connected'}
</span>
) : (
<span className="inline-flex items-center gap-1 px-2 py-0.5 crm-radius-badge text-[11px] font-semibold bg-warning/15 text-warning">
<WifiOff className="w-3 h-3" />
Disconnected
</span>
)}
<span className="text-[13px] text-muted-foreground truncate">
{isConnected
? [session?.name, session?.phone].filter(Boolean).join(' · ')
: 'Not connected'}
</span>
</div>
<div className="flex items-center gap-2">
<button
onClick={async () => {
const sess = await loadSession();
if (sess?.id) loadChats(sess.id);
}}
disabled={sessionLoading || chatsLoading}
className="w-9 h-9 crm-radius-control border border-border bg-card text-muted-foreground hover:text-foreground hover:bg-muted flex items-center justify-center cursor-pointer disabled:opacity-50"
title="Refresh"
>
<RefreshCw className={`w-3.5 h-3.5 ${sessionLoading || chatsLoading ? 'animate-spin' : ''}`} />
</button>
<button type="button" onClick={() => router.push('/notifications-gateway')} className={primaryButton}>
<QrCode className="w-3.5 h-3.5" />
Gateway
</button>
</div>
</div>
<div className={`${shell} flex-1 overflow-hidden flex flex-col md:flex-row min-h-0`}>
{/* LEFT: Chat List */}
<div className={`${activeChatId ? 'hidden md:flex' : 'flex'} w-full md:w-80 lg:w-96 border-r border-border flex-col bg-card shrink-0 min-h-0 flex-1 md:flex-none`}>
<div className="p-3 border-b border-border space-y-2">
<div className="relative">
<Search className="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground pointer-events-none" />
<input
type="text"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
placeholder="Search"
className={field}
/>
</div>
<div className="grid grid-cols-3 gap-1 bg-muted p-1 crm-radius-control text-[12px] font-semibold text-center">
{(['ALL', 'UNREAD', 'GROUPS'] as const).map((tab) => (
<button
key={tab}
type="button"
onClick={() => setActiveTab(tab)}
className={`h-8 crm-radius-control cursor-pointer ${activeTab === tab ? 'bg-card text-primary' : 'text-muted-foreground'}`}
>
{tab === 'ALL' ? 'All' : tab === 'UNREAD' ? 'Unread' : 'Groups'}
</button>
))}
</div>
<p className="text-[12px] text-muted-foreground px-1">
{chatsLoading ? (
<span className="flex items-center gap-1"><Loader2 className="w-3 h-3 animate-spin" /> Loading chats</span>
) : (
<span>{filteredChats.length} chats</span>
)}
</p>
</div>
{/* Chat Items */}
<div className="flex-1 overflow-y-auto divide-y divide-border">
{!isConnected && !sessionLoading && (
<div className="p-6 text-center text-[13px] text-muted-foreground space-y-2">
<p className="font-semibold text-foreground">Not connected</p>
<button type="button" onClick={() => router.push('/notifications-gateway')} className={primaryButton}>
Open gateway
</button>
</div>
)}
{filteredChats.map((c) => {
const name = getNameFromChat(c, contacts);
const isActive = c.id === activeChatId;
const timeStr = c.timestamp ? formatTimestamp(c.timestamp) : '';
return (
<button
key={c.id}
onClick={() => setActiveChatId(c.id)}
className={`w-full px-3 py-3 text-left flex items-start gap-3 cursor-pointer ${isActive ? 'bg-primary/10' : 'hover:bg-muted/40'}`}
>
<div className="w-9 h-9 rounded-full bg-primary/10 text-primary text-[12px] font-semibold flex items-center justify-center shrink-0">
{getInitial(name)}
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center justify-between gap-1">
<span className="font-semibold text-[13px] text-foreground truncate">{name}</span>
<span className="text-[11px] text-muted-foreground shrink-0">{timeStr}</span>
</div>
<p className="text-[12px] text-muted-foreground truncate mt-0.5">
{c.lastMessage || (c.kind === 'channel' ? 'Channel' : c.isGroup ? 'Group' : '—')}
</p>
<div className="flex items-center justify-between gap-1 mt-1">
<span className="text-[11px] text-muted-foreground truncate">
{c.id.replace(/@.*/, '')}
</span>
<span className="flex items-center gap-1 shrink-0">
{c.pinned && <Pin className="w-3 h-3 text-muted-foreground" />}
{c.unreadCount > 0 && (
<span className="min-w-5 h-5 px-1.5 rounded-full text-[11px] font-semibold bg-primary text-white inline-flex items-center justify-center">
{c.unreadCount}
</span>
)}
</span>
</div>
</div>
</button>
);
})}
{!chatsLoading && isConnected && filteredChats.length === 0 && (
<p className="py-16 text-center text-[13px] text-muted-foreground">No chats</p>
)}
</div>
</div>
{/* RIGHT: Conversation */}
{activeChatId && activeChat ? (
<div className="flex-1 flex flex-col bg-background min-w-0">
{/* Header */}
<div className="px-3 py-2.5 border-b border-border bg-card flex items-center justify-between gap-2 shrink-0 min-w-0">
<div className="flex items-center gap-2 min-w-0">
<button
type="button"
onClick={() => setActiveChatId('')}
className="md:hidden w-8 h-8 crm-radius-control border border-border text-muted-foreground hover:text-foreground hover:bg-muted flex items-center justify-center shrink-0 cursor-pointer"
aria-label="Back to chats"
>
<ArrowLeft className="w-4 h-4" />
</button>
<div className="w-8 h-8 rounded-full bg-primary/10 text-primary text-[12px] font-semibold flex items-center justify-center shrink-0">
{getInitial(activeName)}
</div>
<div className="min-w-0">
<h2 className="text-[13px] font-semibold text-foreground truncate">{activeName}</h2>
<p className="text-[12px] text-muted-foreground flex items-center gap-1">
<Phone className="w-3 h-3" />
{activeChatId.replace(/@.*/, '')}
{activeChat.isGroup && <span>Group</span>}
</p>
</div>
</div>
<button
type="button"
onClick={() => session?.id && loadMessages(session.id, activeChatId)}
className="w-8 h-8 crm-radius-control border border-border text-muted-foreground hover:text-foreground hover:bg-muted flex items-center justify-center cursor-pointer"
title="Refresh messages"
>
<RefreshCw className={`w-3.5 h-3.5 ${messagesLoading ? 'animate-spin' : ''}`} />
</button>
</div>
<div className="px-3 py-2 border-b border-border flex items-center gap-2 overflow-x-auto shrink-0">
<button
type="button"
onClick={() => handleTemplate('QUOTE')}
disabled={!isConnected || isSending}
className={secondaryButton}
>
Quotation
</button>
<button
type="button"
onClick={() => handleTemplate('REPAIR')}
disabled={!isConnected || isSending}
className={secondaryButton}
>
Repair update
</button>
<button
type="button"
onClick={() => handleTemplate('PICKUP')}
disabled={!isConnected || isSending}
className={secondaryButton}
>
Pickup ready
</button>
</div>
{/* Messages */}
<div className="flex-1 p-4 overflow-y-auto space-y-3 bg-muted/10">
{messagesLoading && (
<div className="flex justify-center py-8">
<Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
</div>
)}
{!messagesLoading && messages.length === 0 && (
<p className="py-16 text-center text-[13px] text-muted-foreground">No messages</p>
)}
{messages.map((m) => {
const isOut = m.direction === 'outgoing';
return (
<div key={m.id} className={`flex flex-col ${isOut ? 'items-end' : 'items-start'}`}>
<div
className={`max-w-[80%] crm-radius-section px-3 py-2 text-[13px] space-y-1 ${isOut
? 'bg-primary text-white'
: 'bg-card border border-border text-foreground'
}`}
>
<p className="whitespace-pre-wrap leading-relaxed">
{m.body || <span className="italic opacity-70">[{m.type}]</span>}
</p>
<div className={`flex items-center justify-end gap-1 text-[11px] ${isOut ? 'text-white/80' : 'text-muted-foreground'}`}>
<span>{formatMessageTime(m.timestamp)}</span>
{isOut && <CheckCheck className="w-3 h-3" />}
</div>
</div>
</div>
);
})}
<div ref={messagesEndRef} />
</div>
{/* Input */}
<div className="p-3 bg-card border-t border-border flex items-center gap-2 shrink-0">
<button
type="button"
onClick={() => toast.info('File attachment coming soon!')}
className="w-9 h-9 crm-radius-control text-muted-foreground hover:text-foreground hover:bg-muted flex items-center justify-center cursor-pointer"
aria-label="Attach file"
>
<Paperclip className="w-4 h-4" />
</button>
<input
type="text"
value={inputText}
onChange={(e) => 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"
/>
<button
type="button"
disabled={isSending || !inputText.trim() || !isConnected}
onClick={() => handleSend()}
className={primaryButton}
>
{isSending ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <Send className="w-3.5 h-3.5" />}
Send
</button>
</div>
</div>
) : (
<div className="flex-1 flex flex-col items-center justify-center p-8 text-center text-[13px] text-muted-foreground">
{isConnected ? (
<p>Select a chat</p>
) : sessionLoading ? (
<span className="inline-flex items-center gap-2">
<Loader2 className="w-4 h-4 animate-spin" />
Connecting
</span>
) : (
<div className="space-y-3">
<p className="font-semibold text-foreground">Not connected</p>
<button type="button" onClick={() => router.push('/notifications-gateway')} className={primaryButton}>
Open gateway
</button>
</div>
)}
</div>
)}
</div>
</div>
{/* ── Confirm-before-Send Modal ── */}
<SlideOver
open={pendingMessage !== null}
onClose={() => setPendingMessage(null)}
title="Send message"
size="compact"
>
{pendingMessage && (
<div className="flex min-h-0 flex-1 flex-col">
<div className="flex-1 min-h-0 overflow-y-auto px-5 py-4 space-y-4">
<div className="space-y-1">
<p className="text-[11px] font-semibold text-muted-foreground uppercase">To</p>
<p className="text-[13px] font-semibold text-foreground">{pendingMessage.recipientName}</p>
<p className="text-[12px] text-muted-foreground">+{pendingMessage.recipientPhone}</p>
</div>
<div className="bg-muted/40 border border-border crm-radius-section p-3">
<p className="text-[13px] text-foreground whitespace-pre-wrap leading-relaxed">{pendingMessage.text}</p>
</div>
<div className="flex justify-end gap-2">
<button type="button" onClick={() => setPendingMessage(null)} className={secondaryButton}>
Cancel
</button>
<button type="button" onClick={confirmSend} disabled={isSending} className={primaryButton}>
{isSending ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <Send className="w-3.5 h-3.5" />}
Send
</button>
</div>
</div>
</div>
)}
</SlideOver>
</>
);
}
// ─── Page wrapper ─────────────────────────────────────────────────────────────
export default function WhatsAppWebPage() {
return (
<Suspense fallback={
<div className="py-16 text-center text-[13px] text-muted-foreground">Loading WhatsApp</div>
}>
<WhatsAppWebContent />
</Suspense>
);
}