"use client" import React, { useState, useEffect } from "react"; import { useRouter } from "next/navigation"; import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; import { Bell } from "lucide-react"; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu"; import axios from "axios"; import { getCookie } from "@/lib/client-utils"; interface UnreadCounts { totalUnread: number; chatCounts: Record; } export default function ChatNotifications() { const router = useRouter(); const [unreadCounts, setUnreadCounts] = useState({ totalUnread: 0, chatCounts: {} }); const [loading, setLoading] = useState(true); const [chatMetadata, setChatMetadata] = useState>({}); // Fetch unread counts useEffect(() => { const fetchUnreadCounts = async () => { try { // Get auth token from cookies const authToken = getCookie("Authorization"); if (!authToken) return; // Set up axios with the auth token const authAxios = axios.create({ baseURL: process.env.NEXT_PUBLIC_API_URL, headers: { Authorization: `Bearer ${authToken}` } }); // Get vendor ID from profile const vendorResponse = await authAxios.get('/auth/me'); const vendorId = vendorResponse.data.vendor._id; const response = await authAxios.get(`/chats/vendor/${vendorId}/unread`); setUnreadCounts(response.data); // If there are unread messages, fetch chat metadata if (response.data.totalUnread > 0) { const chatIds = Object.keys(response.data.chatCounts); if (chatIds.length > 0) { // Create a simplified metadata object with just needed info const metadata: Record = {}; // Fetch each chat to get buyer IDs await Promise.all( chatIds.map(async (chatId) => { try { const chatResponse = await authAxios.get(`/api/chats/${chatId}`); metadata[chatId] = { buyerId: chatResponse.data.buyerId, }; } catch (error) { console.error(`Error fetching chat ${chatId}:`, error); } }) ); setChatMetadata(metadata); } } } catch (error) { console.error("Error fetching unread counts:", error); } finally { setLoading(false); } }; fetchUnreadCounts(); // Set polling interval (every 30 seconds) const intervalId = setInterval(fetchUnreadCounts, 30000); return () => clearInterval(intervalId); }, []); const handleChatClick = (chatId: string) => { router.push(`/dashboard/chats/${chatId}`); }; if (loading || unreadCounts.totalUnread === 0) { return ( ); } return (

Unread Messages

{Object.entries(unreadCounts.chatCounts).map(([chatId, count]) => ( handleChatClick(chatId)} >

Customer {chatMetadata[chatId]?.buyerId.slice(-4) || 'Unknown'}

{count} new {count === 1 ? 'message' : 'messages'}

{count}
))}
); }