import React, { useEffect, useRef, useState } from "react"; import { cn } from "./lib/utils"; import { Input } from "./components/input"; import { SendIcon } from "lucide-react"; interface ChatWindowProps { isOpen: boolean; url: string; } interface Message { text: string; isUser: boolean; } const ChatWindow = ({ isOpen, url }: ChatWindowProps) => { const [messages, setMessages] = useState([]); const [inputValue, setInputValue] = useState(""); const messagesEndRef = useRef(null); const [sessionId, setSessionId] = useState(null); const scrollToBottom = () => { messagesEndRef.current?.scrollIntoView({ behavior: "smooth" }); }; useEffect(() => { scrollToBottom(); }, [messages]); const sendMessage = async (text: string) => { // Add user message to chat setMessages(prev => [...prev, { text, isUser: true }]); setInputValue(""); const body = { chatInput: text, sessionId: sessionId || 'abc123' }; try { const res = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body), }); const data = await res.json(); if (data.sessionId) { setSessionId(data.sessionId); } // Add bot response to chat setMessages(prev => [...prev, { text: data.output || '...', isUser: false }]); } catch (error) { console.error('Error sending message:', error); setMessages(prev => [...prev, { text: 'Sorry, there was an error processing your message.', isUser: false }]); } }; const handleSubmit = (e: React.FormEvent) => { e.preventDefault(); if (inputValue.trim()) { sendMessage(inputValue.trim()); } }; return (
{messages.map((message, index) => (
{message.text}
))}
setInputValue(e.target.value)} placeholder="Type a message..." className="flex-1 rounded-full border-gray-300" />
); }; export default ChatWindow;