"use client" import React, { useState, useEffect, useRef } from "react"; import { useRouter } from "next/navigation"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Avatar, AvatarFallback } from "@/components/ui/avatar"; import { cn } from "@/lib/utils"; import { formatDistanceToNow } from "date-fns"; import axios from "axios"; import { toast } from "sonner"; import { ArrowLeft, Send, RefreshCw } from "lucide-react"; interface Message { _id: string; sender: "buyer" | "vendor"; content: string; attachments: string[]; read: boolean; createdAt: string; buyerId: string; vendorId: string; } interface Chat { _id: string; buyerId: string; vendorId: string; storeId: string; messages: Message[]; lastUpdated: string; orderId?: string; } export default function ChatDetail({ chatId }: { chatId: string }) { const router = useRouter(); const [chat, setChat] = useState(null); const [loading, setLoading] = useState(true); const [message, setMessage] = useState(""); const [sending, setSending] = useState(false); const messagesEndRef = useRef(null); // Fetch chat data const fetchChat = async () => { try { const response = await axios.get(`/api/chats/${chatId}`); setChat(response.data); setLoading(false); } catch (error) { console.error("Error fetching chat:", error); toast.error("Failed to load conversation"); setLoading(false); } }; useEffect(() => { fetchChat(); // Poll for updates every 10 seconds const intervalId = setInterval(fetchChat, 10000); return () => clearInterval(intervalId); }, [chatId]); // Scroll to bottom when messages change useEffect(() => { messagesEndRef.current?.scrollIntoView({ behavior: "smooth" }); }, [chat?.messages]); // Send a message const handleSendMessage = async (e: React.FormEvent) => { e.preventDefault(); if (!message.trim()) return; setSending(true); try { await axios.post(`/api/chats/${chatId}/message`, { content: message }); setMessage(""); await fetchChat(); // Refresh chat after sending } catch (error) { console.error("Error sending message:", error); toast.error("Failed to send message"); } finally { setSending(false); } }; const handleBackClick = () => { router.push("/dashboard/chats"); }; if (loading) { return ( Loading conversation... ); } if (!chat) { return ( Chat not found

This conversation doesn't exist or you don't have access to it.

); } return ( Chat with Customer {chat.buyerId.slice(-4)} {chat.messages.length === 0 ? (

No messages yet. Send one to start the conversation.

) : ( chat.messages.map((msg, index) => (
{msg.sender === "buyer" && ( {chat.buyerId.slice(0, 2).toUpperCase()} )} {formatDistanceToNow(new Date(msg.createdAt), { addSuffix: true })}

{msg.content}

{/* Show attachments if any (future enhancement) */}
)) )}
setMessage(e.target.value)} placeholder="Type your message..." disabled={sending} className="flex-1" />
); }