"use client" import React, { useState, useEffect } from "react"; import { useRouter } from "next/navigation"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; 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 axios from "axios"; import { toast } from "sonner"; import { getCookie } from "@/lib/client-utils"; interface Chat { _id: string; buyerId: string; vendorId: string; storeId: string; lastUpdated: string; orderId?: string; } interface UnreadCounts { totalUnread: number; chatCounts: Record; } export default function ChatList() { const router = useRouter(); const [chats, setChats] = useState([]); const [loading, setLoading] = useState(true); const [unreadCounts, setUnreadCounts] = useState({ totalUnread: 0, chatCounts: {} }); const [selectedStore, setSelectedStore] = useState(""); const [vendorStores, setVendorStores] = useState<{ _id: string, name: string }[]>([]); // Fetch vendor ID and stores useEffect(() => { const fetchVendorData = async () => { try { // Get auth token from cookies const authToken = getCookie("Authorization"); if (!authToken) { toast.error("You need to be logged in to view chats"); router.push("/auth/login"); return; } // Set up axios with the auth token const authAxios = axios.create({ baseURL: process.env.NEXT_PUBLIC_API_URL, headers: { Authorization: `Bearer ${authToken}` } }); // First, get vendor info using the /api/auth/me endpoint const vendorResponse = await authAxios.get('/auth/me'); const vendorId = vendorResponse.data._id; // Fetch vendor's stores using storefront endpoint const storesResponse = await authAxios.get(`/storefront`); setVendorStores(storesResponse.data); if (storesResponse.data.length > 0) { setSelectedStore(storesResponse.data[0]._id); } } catch (error) { console.error("Error fetching vendor data:", error); toast.error("Failed to load vendor data"); } }; fetchVendorData(); }, [router]); // Fetch chats and unread counts when store is selected useEffect(() => { const fetchChats = async () => { if (!selectedStore) return; setLoading(true); try { // Get auth token from cookies const authToken = getCookie("Authorization"); if (!authToken) { toast.error("You need to be logged in"); router.push("/auth/login"); 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('/api/auth/me'); const vendorId = vendorResponse.data._id; // Fetch chats const chatsResponse = await authAxios.get(`/api/chats/vendor/${vendorId}`); // Filter chats by selected store const filteredChats = chatsResponse.data.filter( (chat: Chat) => chat.storeId === selectedStore ); setChats(filteredChats); // Fetch unread counts const unreadResponse = await authAxios.get(`/api/chats/vendor/${vendorId}/unread`); setUnreadCounts(unreadResponse.data); } catch (error) { console.error("Error fetching chats:", error); toast.error("Failed to load chats"); } finally { setLoading(false); } }; fetchChats(); // Set up polling for updates every 30 seconds const intervalId = setInterval(fetchChats, 30000); return () => clearInterval(intervalId); }, [selectedStore]); // Handle chat selection const handleChatClick = (chatId: string) => { router.push(`/dashboard/chats/${chatId}`); }; // Handle store change const handleStoreChange = (e: React.ChangeEvent) => { setSelectedStore(e.target.value); }; // Create a new chat const handleCreateChat = () => { router.push("/dashboard/chats/new"); }; if (loading) { return ( Loading chats...
{[1, 2, 3].map((n) => (
))}
); } return ( Customer Chats
{chats.length === 0 ? (

No conversations yet

) : (
{chats.map((chat) => (
handleChatClick(chat._id)} >
{chat.buyerId.slice(0, 2).toUpperCase()}

Customer {chat.buyerId.slice(-4)}

{formatDistanceToNow(new Date(chat.lastUpdated), { addSuffix: true })}

{unreadCounts.chatCounts[chat._id] > 0 && ( {unreadCounts.chatCounts[chat._id]} unread )}
))}
)}
); }