"use client"; import { useEffect, useState } from "react"; import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, } from "@/components/ui/dialog"; import { Skeleton } from "@/components/ui/skeleton"; import { useChat } from "@/lib/hooks/use-chat"; import { useSession } from "@/lib/hooks/use-session"; import { ChatHeader } from "./ChatHeader"; import { MessageInput } from "./MessageInput"; import { MessageList } from "./MessageList"; interface ChatModalProps { open: boolean; onOpenChange: (open: boolean) => void; listingId?: number | null; chatId?: string | null; initialMessage?: string; } export function ChatModal({ open, onOpenChange, listingId, chatId: initialChatId, initialMessage, }: ChatModalProps) { const { user } = useSession(); const [chatId, setChatId] = useState(initialChatId || null); const [isCreatingChat, setIsCreatingChat] = useState(false); const { chat, messages, isLoading, isSending, sendMessage, loadMoreMessages, hasMore, otherUserTyping, } = useChat(chatId); // Se chatId for fornecido diretamente, usar ele useEffect(() => { if (initialChatId) { setChatId(initialChatId); return; } }, [initialChatId]); // Criar ou buscar chat quando modal abrir (apenas se não tiver chatId) useEffect(() => { if (!open || !user || !listingId || initialChatId) { if (!initialChatId && !listingId) { setChatId(null); } return; } const createOrGetChat = async () => { setIsCreatingChat(true); try { const res = await fetch("/api/chats", { method: "POST", headers: { "Content-Type": "application/json", }, credentials: "include", body: JSON.stringify({ listing_id: listingId, buyer_message: initialMessage, }), }); if (!res.ok) { throw new Error("Erro ao criar chat"); } const data = await res.json(); setChatId(data.chat.chat_id); // Se houver mensagem inicial, já foi enviada no backend } catch (error) { console.error("Erro ao criar/buscar chat:", error); } finally { setIsCreatingChat(false); } }; createOrGetChat(); }, [open, user, listingId, initialMessage, initialChatId]); if (!user) { return null; } return ( Chat com vendedor Conversa sobre o anúncio {isCreatingChat || (isLoading && !chat) ? (
) : chat ? ( <> ) : (

Erro ao carregar chat

)}
); }