import { useRouter } from "next/router"; import React, { useState, useEffect } from "react"; import BotWrapper from "@/components/chat/BotWrapper"; import HumanWrapper from "@/components/chat/HumanWrapper"; import SetSources from "@/containers/SetSources"; export default function ChatWindow({ embedding_model, app_type, setBotTitle }) { const [bot, setBot] = useState(null); const [chats, setChats] = useState([]); const [isLoading, setIsLoading] = useState(false); const [selectChat, setSelectChat] = useState(true); const router = useRouter(); const { bot_slug } = router.query; useEffect(() => { if (bot_slug) { const fetchBots = async () => { const response = await fetch("/api/get_bots"); const data = await response.json(); const matchingBot = data.find((item) => item.slug === bot_slug); setBot(matchingBot); setBotTitle(matchingBot.name); }; fetchBots(); } }, [bot_slug]); useEffect(() => { const storedChats = localStorage.getItem(`chat_${bot_slug}_${app_type}`); if (storedChats) { const parsedChats = JSON.parse(storedChats); setChats(parsedChats.chats); } }, [app_type, bot_slug]); const handleChatResponse = async (e) => { e.preventDefault(); setIsLoading(true); const queryInput = e.target.query.value; e.target.query.value = ""; const chatEntry = { sender: "H", message: queryInput, }; setChats((prevChats) => [...prevChats, chatEntry]); const response = await fetch("/api/get_answer", { method: "POST", body: JSON.stringify({ query: queryInput, embedding_model, app_type, }), headers: { "Content-Type": "application/json", }, }); const data = await response.json(); if (response.ok) { const botResponse = data.response; const botEntry = { sender: "B", message: botResponse, }; setIsLoading(false); setChats((prevChats) => [...prevChats, botEntry]); const savedChats = { chats: [...chats, chatEntry, botEntry], }; localStorage.setItem( `chat_${bot_slug}_${app_type}`, JSON.stringify(savedChats) ); } else { router.reload(); } }; return ( <>