"use client" import { useState, useEffect } from "react" import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/common/card" import { Button } from "@/components/common/button" import { Skeleton } from "@/components/common/skeleton" import { MessageSquare, MessageCircle, ArrowRight, Clock } from "lucide-react" import { clientFetch, getCookie } from "@/lib/api" import { Avatar, AvatarFallback } from "@/components/common/avatar" import Link from "next/link" import { RelativeTime } from "@/components/common/relative-time" interface PendingChatsWidgetProps { settings?: { showPreview?: boolean } } interface Chat { id: string buyerId: string telegramUsername?: string lastUpdated: string unreadCount: number } export default function PendingChatsWidget({ settings }: PendingChatsWidgetProps) { const showPreview = settings?.showPreview !== false const [chats, setChats] = useState([]) const [isLoading, setIsLoading] = useState(true) const [error, setError] = useState(null) const getVendorIdFromToken = () => { const authToken = getCookie("Authorization") || "" if (!authToken) return null try { const payload = JSON.parse(atob(authToken.split(".")[1])) return payload.id } catch { return null } } const fetchChats = async () => { try { setIsLoading(true) setError(null) const vendorId = getVendorIdFromToken() if (!vendorId) { setError("Please login to view chats") return } const response = await clientFetch(`/chats/vendor/${vendorId}/batch?page=1&limit=5`) const chatCounts = response.unreadCounts?.chatCounts || {} const pendingChats = (response.chats || []) .filter((c: any) => chatCounts[c._id] > 0) .map((c: any) => ({ id: c._id, buyerId: c.buyerId, telegramUsername: c.telegramUsername, lastUpdated: c.lastUpdated, unreadCount: chatCounts[c._id] || 0 })) setChats(pendingChats) } catch (err) { console.error("Error fetching chats:", err) setError("Failed to load chats") } finally { setIsLoading(false) } } useEffect(() => { fetchChats() }, []) if (isLoading) { return ( {[1, 2].map((i) => (
))}
) } return (
Pending Chats Unanswered customer messages
{error ? (

{error}

) : chats.length === 0 ? (

All caught up!

No pending customer chats that require your attention.

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

{chat.telegramUsername ? `@${chat.telegramUsername}` : `Customer ${chat.buyerId.slice(-6)}`}

{chat.unreadCount}
))}
)}
) }