|
| 1 | +import { useState, useRef, useEffect } from "react"; |
| 2 | +import { Dialog, DialogContent } from "@/components/ui/dialog"; |
| 3 | +import { Button } from "@/components/ui/button"; |
| 4 | +import { Input } from "@/components/ui/input"; |
| 5 | +import { ScrollArea } from "@/components/ui/scroll-area"; |
| 6 | +import { supabase } from "@/integrations/supabase/client"; |
| 7 | +import { toast } from "sonner"; |
| 8 | +import { Send, Mic, Image, Square, Loader2, Bot, User, Wrench } from "lucide-react"; |
| 9 | + |
| 10 | +interface Message { |
| 11 | + role: "user" | "assistant" | "status"; |
| 12 | + content: string; |
| 13 | + toolCalls?: { tool: string; args: any }[]; |
| 14 | +} |
| 15 | + |
| 16 | +interface ChatPanelProps { |
| 17 | + open: boolean; |
| 18 | + onOpenChange: (open: boolean) => void; |
| 19 | + onEventChanged?: () => void; |
| 20 | +} |
| 21 | + |
| 22 | +const ChatPanel = ({ open, onOpenChange, onEventChanged }: ChatPanelProps) => { |
| 23 | + const [messages, setMessages] = useState<Message[]>([ |
| 24 | + { role: "assistant", content: "Hey! I'm Maantis, your AI scheduling assistant. I can create events, check your schedule, resolve conflicts, and more. What can I help with?" } |
| 25 | + ]); |
| 26 | + const [input, setInput] = useState(""); |
| 27 | + const [isLoading, setIsLoading] = useState(false); |
| 28 | + const [isRecording, setIsRecording] = useState(false); |
| 29 | + const scrollRef = useRef<HTMLDivElement>(null); |
| 30 | + const fileInputRef = useRef<HTMLInputElement>(null); |
| 31 | + const mediaRecorder = useRef<MediaRecorder | null>(null); |
| 32 | + const audioChunks = useRef<Blob[]>([]); |
| 33 | + const conversationHistory = useRef<any[]>([]); |
| 34 | + |
| 35 | + useEffect(() => { |
| 36 | + if (scrollRef.current) { |
| 37 | + scrollRef.current.scrollTop = scrollRef.current.scrollHeight; |
| 38 | + } |
| 39 | + }, [messages]); |
| 40 | + |
| 41 | + const sendToAgent = async (userMessage: string, inputType: string = "text", fileData?: string) => { |
| 42 | + setIsLoading(true); |
| 43 | + setMessages(prev => [...prev, { role: "status", content: "Thinking..." }]); |
| 44 | + |
| 45 | + try { |
| 46 | + const { data: { user } } = await supabase.auth.getUser(); |
| 47 | + if (!user) { |
| 48 | + toast.error("Please log in first"); |
| 49 | + setIsLoading(false); |
| 50 | + return; |
| 51 | + } |
| 52 | + |
| 53 | + const { data, error } = await supabase.functions.invoke('agent', { |
| 54 | + body: { |
| 55 | + user_id: user.id, |
| 56 | + message: userMessage, |
| 57 | + input_type: inputType, |
| 58 | + file_data: fileData, |
| 59 | + conversation_history: conversationHistory.current.slice(-10), |
| 60 | + }, |
| 61 | + }); |
| 62 | + |
| 63 | + if (error) throw new Error(error.message); |
| 64 | + |
| 65 | + setMessages(prev => prev.filter(m => m.role !== "status")); |
| 66 | + |
| 67 | + if (data.transcription && inputType === "voice") { |
| 68 | + setMessages(prev => [...prev, { role: "status", content: `Heard: "${data.transcription}"` }]); |
| 69 | + } |
| 70 | + |
| 71 | + const assistantMsg: Message = { |
| 72 | + role: "assistant", |
| 73 | + content: data.response || "I processed your request.", |
| 74 | + toolCalls: data.tool_calls_made, |
| 75 | + }; |
| 76 | + setMessages(prev => [...prev, assistantMsg]); |
| 77 | + |
| 78 | + conversationHistory.current.push({ role: "user", content: userMessage }); |
| 79 | + conversationHistory.current.push({ role: "assistant", content: data.response }); |
| 80 | + |
| 81 | + if (data.tool_calls_made?.some((t: any) => ["create_event", "update_event", "delete_event"].includes(t.tool))) { |
| 82 | + onEventChanged?.(); |
| 83 | + } |
| 84 | + |
| 85 | + } catch (err: any) { |
| 86 | + setMessages(prev => prev.filter(m => m.role !== "status")); |
| 87 | + setMessages(prev => [...prev, { role: "assistant", content: `Error: ${err.message}` }]); |
| 88 | + } finally { |
| 89 | + setIsLoading(false); |
| 90 | + } |
| 91 | + }; |
| 92 | + |
| 93 | + const handleSubmit = async (e: React.FormEvent) => { |
| 94 | + e.preventDefault(); |
| 95 | + if (!input.trim() || isLoading) return; |
| 96 | + const msg = input.trim(); |
| 97 | + setInput(""); |
| 98 | + setMessages(prev => [...prev, { role: "user", content: msg }]); |
| 99 | + await sendToAgent(msg); |
| 100 | + }; |
| 101 | + |
| 102 | + const startRecording = async () => { |
| 103 | + try { |
| 104 | + const stream = await navigator.mediaDevices.getUserMedia({ audio: true }); |
| 105 | + mediaRecorder.current = new MediaRecorder(stream); |
| 106 | + audioChunks.current = []; |
| 107 | + |
| 108 | + mediaRecorder.current.ondataavailable = (e) => { |
| 109 | + if (e.data.size > 0) audioChunks.current.push(e.data); |
| 110 | + }; |
| 111 | + |
| 112 | + mediaRecorder.current.onstop = async () => { |
| 113 | + const audioBlob = new Blob(audioChunks.current, { type: 'audio/webm' }); |
| 114 | + stream.getTracks().forEach(track => track.stop()); |
| 115 | + |
| 116 | + const reader = new FileReader(); |
| 117 | + reader.onloadend = async () => { |
| 118 | + const base64 = (reader.result as string).split(',')[1]; |
| 119 | + setMessages(prev => [...prev, { role: "user", content: "Voice message" }]); |
| 120 | + await sendToAgent("", "voice", base64); |
| 121 | + }; |
| 122 | + reader.readAsDataURL(audioBlob); |
| 123 | + }; |
| 124 | + |
| 125 | + mediaRecorder.current.start(); |
| 126 | + setIsRecording(true); |
| 127 | + } catch (err) { |
| 128 | + toast.error("Could not access microphone."); |
| 129 | + } |
| 130 | + }; |
| 131 | + |
| 132 | + const stopRecording = () => { |
| 133 | + if (mediaRecorder.current && isRecording) { |
| 134 | + mediaRecorder.current.stop(); |
| 135 | + setIsRecording(false); |
| 136 | + } |
| 137 | + }; |
| 138 | + |
| 139 | + const handleImageUpload = async (e: React.ChangeEvent<HTMLInputElement>) => { |
| 140 | + const file = e.target.files?.[0]; |
| 141 | + if (!file) return; |
| 142 | + |
| 143 | + const reader = new FileReader(); |
| 144 | + reader.onloadend = async () => { |
| 145 | + const base64 = (reader.result as string).split(',')[1]; |
| 146 | + setMessages(prev => [...prev, { role: "user", content: `Image: ${file.name}` }]); |
| 147 | + await sendToAgent(input || "", "image", base64); |
| 148 | + setInput(""); |
| 149 | + }; |
| 150 | + reader.readAsDataURL(file); |
| 151 | + e.target.value = ""; |
| 152 | + }; |
| 153 | + |
| 154 | + return ( |
| 155 | + <Dialog open={open} onOpenChange={onOpenChange}> |
| 156 | + <DialogContent className="sm:max-w-[500px] h-[600px] flex flex-col p-0 gap-0"> |
| 157 | + <div className="flex items-center gap-3 p-4 border-b bg-primary/5"> |
| 158 | + <div className="w-9 h-9 rounded-full bg-primary flex items-center justify-center"> |
| 159 | + <Bot className="h-5 w-5 text-white" /> |
| 160 | + </div> |
| 161 | + <div> |
| 162 | + <h3 className="font-semibold text-sm">Maantis Agent</h3> |
| 163 | + <p className="text-xs text-muted-foreground">AI Scheduling Assistant</p> |
| 164 | + </div> |
| 165 | + </div> |
| 166 | + |
| 167 | + <ScrollArea className="flex-1 p-4" ref={scrollRef}> |
| 168 | + <div className="space-y-4"> |
| 169 | + {messages.map((msg, i) => ( |
| 170 | + <div key={i} className={`flex gap-2 ${msg.role === "user" ? "justify-end" : "justify-start"}`}> |
| 171 | + {msg.role === "assistant" && ( |
| 172 | + <div className="w-7 h-7 rounded-full bg-primary/10 flex items-center justify-center shrink-0 mt-0.5"> |
| 173 | + <Bot className="h-4 w-4 text-primary" /> |
| 174 | + </div> |
| 175 | + )} |
| 176 | + <div className={`max-w-[80%] rounded-2xl px-4 py-2.5 text-sm leading-relaxed ${ |
| 177 | + msg.role === "user" |
| 178 | + ? "bg-primary text-primary-foreground rounded-br-md" |
| 179 | + : msg.role === "status" |
| 180 | + ? "bg-muted text-muted-foreground italic text-xs py-1.5" |
| 181 | + : "bg-muted rounded-bl-md" |
| 182 | + }`}> |
| 183 | + <p className="whitespace-pre-wrap">{msg.content}</p> |
| 184 | + {msg.toolCalls && msg.toolCalls.length > 0 && ( |
| 185 | + <div className="mt-2 pt-2 border-t border-border/50"> |
| 186 | + <p className="text-[10px] uppercase tracking-wider text-muted-foreground mb-1 flex items-center gap-1"> |
| 187 | + <Wrench className="h-3 w-3" /> Tools used |
| 188 | + </p> |
| 189 | + {msg.toolCalls.map((tc, j) => ( |
| 190 | + <span key={j} className="inline-block text-[11px] bg-background rounded px-1.5 py-0.5 mr-1 mb-0.5 font-mono"> |
| 191 | + {tc.tool} |
| 192 | + </span> |
| 193 | + ))} |
| 194 | + </div> |
| 195 | + )} |
| 196 | + </div> |
| 197 | + {msg.role === "user" && ( |
| 198 | + <div className="w-7 h-7 rounded-full bg-primary flex items-center justify-center shrink-0 mt-0.5"> |
| 199 | + <User className="h-4 w-4 text-white" /> |
| 200 | + </div> |
| 201 | + )} |
| 202 | + </div> |
| 203 | + ))} |
| 204 | + {isLoading && ( |
| 205 | + <div className="flex gap-2"> |
| 206 | + <div className="w-7 h-7 rounded-full bg-primary/10 flex items-center justify-center shrink-0"> |
| 207 | + <Bot className="h-4 w-4 text-primary animate-pulse" /> |
| 208 | + </div> |
| 209 | + <div className="bg-muted rounded-2xl rounded-bl-md px-4 py-2.5"> |
| 210 | + <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" /> |
| 211 | + </div> |
| 212 | + </div> |
| 213 | + )} |
| 214 | + </div> |
| 215 | + </ScrollArea> |
| 216 | + |
| 217 | + <div className="p-3 border-t bg-background"> |
| 218 | + <form onSubmit={handleSubmit} className="flex items-center gap-2"> |
| 219 | + <input |
| 220 | + type="file" |
| 221 | + ref={fileInputRef} |
| 222 | + accept="image/*" |
| 223 | + className="hidden" |
| 224 | + onChange={handleImageUpload} |
| 225 | + /> |
| 226 | + <Button |
| 227 | + type="button" |
| 228 | + variant="ghost" |
| 229 | + size="icon" |
| 230 | + className="shrink-0 h-9 w-9" |
| 231 | + onClick={() => fileInputRef.current?.click()} |
| 232 | + disabled={isLoading} |
| 233 | + > |
| 234 | + <Image className="h-4 w-4 text-muted-foreground" /> |
| 235 | + </Button> |
| 236 | + |
| 237 | + {isRecording ? ( |
| 238 | + <Button |
| 239 | + type="button" |
| 240 | + variant="destructive" |
| 241 | + size="icon" |
| 242 | + className="shrink-0 h-9 w-9 animate-pulse" |
| 243 | + onClick={stopRecording} |
| 244 | + > |
| 245 | + <Square className="h-4 w-4" /> |
| 246 | + </Button> |
| 247 | + ) : ( |
| 248 | + <Button |
| 249 | + type="button" |
| 250 | + variant="ghost" |
| 251 | + size="icon" |
| 252 | + className="shrink-0 h-9 w-9" |
| 253 | + onClick={startRecording} |
| 254 | + disabled={isLoading} |
| 255 | + > |
| 256 | + <Mic className="h-4 w-4 text-muted-foreground" /> |
| 257 | + </Button> |
| 258 | + )} |
| 259 | + |
| 260 | + <Input |
| 261 | + value={input} |
| 262 | + onChange={(e) => setInput(e.target.value)} |
| 263 | + placeholder="Ask me anything..." |
| 264 | + disabled={isLoading || isRecording} |
| 265 | + className="h-9 text-sm" |
| 266 | + /> |
| 267 | + |
| 268 | + <Button |
| 269 | + type="submit" |
| 270 | + size="icon" |
| 271 | + className="shrink-0 h-9 w-9" |
| 272 | + disabled={isLoading || !input.trim()} |
| 273 | + > |
| 274 | + <Send className="h-4 w-4" /> |
| 275 | + </Button> |
| 276 | + </form> |
| 277 | + </div> |
| 278 | + </DialogContent> |
| 279 | + </Dialog> |
| 280 | + ); |
| 281 | +}; |
| 282 | + |
| 283 | +export default ChatPanel; |
0 commit comments