import { TrashIcon } from "@heroicons/react/24/outline"; import { useSupabaseClient } from "@supabase/auth-helpers-react"; import Link from "next/link"; import { useRouter } from "next/router"; import React from "react"; import { api } from "~/utils/api"; import { iconUrl } from "~/utils/icon"; import { useForm } from "@mantine/form"; import axios from "axios"; import { useMutation } from "@tanstack/react-query"; type Message = { isBot: boolean; message: string; }; type History = { bot_response: string; human_message: string; }; type Props = { title: string | null; id: string; created_at: Date | null; icon: string | null; url: string | null; }; export const CahtBox = (props: Props) => { const supabase = useSupabaseClient(); const form = useForm({ initialValues: { message: "", isBot: false, }, }); const sendToBot = async (message: string) => { const { data } = await supabase.auth.getSession(); const response = await axios.post( `${process.env.NEXT_PUBLIC_PAGEASSIST_URL}/api/v1/chat/app`, { user_message: message, history: history, url: props.url, id: props.id, }, { headers: { "X-Auth-Token": data.session?.access_token, }, } ); return response.data; }; const { mutateAsync: sendToBotAsync, isLoading: isSending } = useMutation( sendToBot, { onSuccess: (data) => { setMessages([...messages, { isBot: true, message: data.bot_response }]); setHistory([...history, data]); }, onError: (error) => { setMessages([ ...messages, { isBot: true, message: "Something went wrong" }, ]); }, } ); const [messages, setMessages] = React.useState([ { isBot: true, message: "Hi, I'm PageAssist Bot. How can I help you?", }, ]); // const fetchSession = async () => { // const {data}= await supabase.auth.getSession(); // data.session?.access_token // } const [history, setHistory] = React.useState([]); const divRef = React.useRef(null); React.useEffect(() => { //@ts-ignore divRef.current.scrollIntoView({ behavior: "smooth" }); }); const router = useRouter(); const { mutateAsync: deleteChatByIdAsync, isLoading: isDeleting } = api.chat.deleteChatById.useMutation({ onSuccess: () => { router.push("/dashboard"); }, }); return (
{/* header */}

{props?.title && props?.title?.length > 100 ? props?.title?.slice(0, 100) + "..." : props?.title}

{props.url && new URL(props.url).hostname}

{/* */}
{messages.map((message, index) => { return (

{/* {message.message} */} {message.message}

); })} {isSending && (

Hold on, I'm looking...

)}
{ setMessages([...messages, values]); form.reset(); await sendToBotAsync(values.message); })} >
); };