"use client" import { useState, useEffect, useRef } from "react"; import { useRouter } from "next/navigation"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow, } from "@/components/ui/table"; import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; import { Avatar, AvatarFallback } from "@/components/ui/avatar"; import { formatDistanceToNow } from "date-fns"; import { Plus, MessageCircle, Loader2, RefreshCw, Eye, User } from "lucide-react"; import { clientFetch } from "@/lib/client-utils"; import { toast } from "sonner"; import { getCookie } from "@/lib/client-utils"; interface Chat { _id: string; buyerId: string; vendorId: string; storeId: string; lastUpdated: string; orderId?: string; telegramUsername?: string | null; } interface UnreadCounts { totalUnread: number; chatCounts: Record; } export default function ChatTable() { const router = useRouter(); const [chats, setChats] = useState([]); const [loading, setLoading] = useState(true); const [unreadCounts, setUnreadCounts] = useState({ totalUnread: 0, chatCounts: {} }); const audioRef = useRef(null); // Initialize audio element for notifications useEffect(() => { audioRef.current = new Audio('/notification.mp3'); return () => { if (audioRef.current) { audioRef.current = null; } }; }, []); // Play notification sound const playNotificationSound = () => { if (audioRef.current) { audioRef.current.play().catch(e => { console.log("Failed to play notification sound:", e); }); } }; // Get vendor ID from JWT token const getVendorIdFromToken = () => { const authToken = getCookie("Authorization") || ""; if (!authToken) { throw new Error("No auth token found"); } const tokenParts = authToken.split("."); if (tokenParts.length !== 3) { throw new Error("Invalid token format"); } const payload = JSON.parse(atob(tokenParts[1])); const vendorId = payload.id; if (!vendorId) { throw new Error("Vendor ID not found in token"); } return { vendorId, authToken }; }; // Fetch chats when component mounts useEffect(() => { fetchChats(); // Set up polling for unread messages const interval = setInterval(() => { fetchUnreadCounts(); }, 30000); // Check every 30 seconds return () => clearInterval(interval); }, []); // Fetch unread counts const fetchUnreadCounts = async () => { try { // Get the vendor ID from the auth token const { vendorId } = getVendorIdFromToken(); // Fetch unread counts for this vendor using clientFetch const response = await clientFetch(`/chats/vendor/${vendorId}/unread`); const newUnreadCounts = response; // Play sound if there are new messages if (newUnreadCounts.totalUnread > unreadCounts.totalUnread) { //playNotificationSound(); } setUnreadCounts(newUnreadCounts); } catch (error) { console.error("Failed to fetch unread counts:", error); } }; // Fetch chats const fetchChats = async () => { setLoading(true); try { // Get the vendor ID from the auth token const { vendorId } = getVendorIdFromToken(); // Now fetch chats for this vendor using clientFetch const response = await clientFetch(`/chats/vendor/${vendorId}`); setChats(Array.isArray(response) ? response : []); await fetchUnreadCounts(); } catch (error) { console.error("Failed to fetch chats:", error); toast.error("Failed to load chat conversations"); setChats([]); } finally { setLoading(false); } }; // Navigate to chat detail page const handleChatClick = (chatId: string) => { router.push(`/dashboard/chats/${chatId}`); }; // Create new chat const handleCreateChat = () => { router.push("/dashboard/chats/new"); }; return (
Customer Last Activity Status Actions {loading ? ( ) : chats.length === 0 ? (

No chats found

) : ( chats.map((chat) => ( handleChatClick(chat._id)} >
{chat.telegramUsername ? `@${chat.telegramUsername}` : 'Customer'}
ID: {chat.buyerId}
{chat.orderId && (
Order #{chat.orderId}
)}
{formatDistanceToNow(new Date(chat.lastUpdated), { addSuffix: true })} {unreadCounts.chatCounts[chat._id] > 0 ? ( {unreadCounts.chatCounts[chat._id]} new ) : ( Read )}
)) )}
); }