File size: 3,126 Bytes
e454383
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import React, { useCallback, useRef, useState } from "react";
import { Chat, Message } from "@/lib/types";
import { useChatStore } from "@/stores/chatStore";
import { sendChat, getNameForNewChat } from "@/lib/api";
import { init_message, init_message_meeting_minutes } from "@/lib/prompts";
import { useToast } from "@/hooks/use-toast";

export const useChatLogic = (
  selectedChat: Chat | null,
  selectedChatId: string | null,
  scrollToBottom: () => void
) => {
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const { toast } = useToast();

  const { sendMessage, removeMessage, loadChat, updateChatName } =
    useChatStore();

  const handleSubmit = useCallback(
    async (inputValue: string) => {
      const currentInput = inputValue.trim();
      if (!currentInput || isLoading || !selectedChatId || !selectedChat)
        return;

      setIsLoading(true);
      let userMessageId = "";

      try {
        const userMessage: Message = {
          content: currentInput,
          transcripts: [],
          role: "user",
          timestamp: new Date(),
          id: crypto.randomUUID(),
        };
        // if (selectedChat.messages.length === 0) {
        //   // getting the initial message from the environment variable
        //   const initial_message =
        //     process.env.NEXT_PUBLIC_INITIAL_MESSAGE == "CLE"
        //       ? init_message_meeting_minutes
        //       : process.env.NEXT_PUBLIC_INITIAL_MESSAGE == "CSPE"
        //       ? init_message
        //       : init_message_meeting_minutes;
        //   await sendMessage(initial_message);
        // }

        userMessageId = await sendMessage(userMessage);
        const chat = await loadChat(selectedChatId);
        const aiResponse = await sendChat(chat.messages, userMessage);

        if (!aiResponse?.ok) {
          throw new Error("Failed to send message");
        }

        const aiResponseData = await aiResponse.json();
        const aiMessage: Message = {
          content: aiResponseData.response,
          transcripts: aiResponseData.timestamps,
          role: "assistant",
          timestamp: new Date(),
          id: crypto.randomUUID(),
        };

        await sendMessage(aiMessage);
        scrollToBottom();

        const chatLength = (await loadChat(selectedChatId)).messages.length;
        if (chatLength === 3) {
          const name = await getNameForNewChat(
            userMessage.content,
            aiMessage.content
          );
          if (name) updateChatName(selectedChatId, name);
        }
      } catch (error) {
        console.error("Error in chat submission:", error);
        removeMessage(userMessageId);
        toast({
          title: "Error",
          description: "Failed to send message. Please try again.",
          variant: "destructive",
        });
      } finally {
        setIsLoading(false);
      }
    },
    [
      isLoading,
      selectedChatId,
      selectedChat,
      sendMessage,
      loadChat,
      updateChatName,
      removeMessage,
      scrollToBottom,
      toast,
    ]
  );

  return { isLoading, handleSubmit };
};