|
| 1 | +import { useEffect, useState } from "react"; |
| 2 | + |
| 3 | +import { Button, Input } from "@/components/ui"; |
| 4 | + |
| 5 | +export function ChatBot() { |
| 6 | + const [messages, setMessages] = useState<string[]>([ |
| 7 | + "🤖: Hola! En que puedo ayudarte?", |
| 8 | + ]); |
| 9 | + const [input, setInput] = useState(""); |
| 10 | + const [sessionid, setSessionId] = useState<null | string>(null); |
| 11 | + const [loading, setLoading] = useState(false); |
| 12 | + |
| 13 | + useEffect(() => { |
| 14 | + const currentSessionId = sessionStorage.getItem("sessionid"); |
| 15 | + if (currentSessionId) { |
| 16 | + setSessionId(currentSessionId); |
| 17 | + } else { |
| 18 | + const newSessionId = crypto.randomUUID(); |
| 19 | + sessionStorage.setItem("sessionid", newSessionId); |
| 20 | + setSessionId(newSessionId); |
| 21 | + } |
| 22 | + }, []); |
| 23 | + |
| 24 | + const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => { |
| 25 | + e.preventDefault(); |
| 26 | + setInput(""); |
| 27 | + setMessages((prev) => [...prev, `👤: ${input}`]); |
| 28 | + |
| 29 | + setLoading(true); |
| 30 | + const response = await fetch("/chat", { |
| 31 | + method: "POST", |
| 32 | + headers: { |
| 33 | + "Content-Type": "application/json", |
| 34 | + }, |
| 35 | + body: JSON.stringify({ message: input, sessionid }), |
| 36 | + }); |
| 37 | + |
| 38 | + const { message } = await response.json(); |
| 39 | + |
| 40 | + setMessages((prev) => [...prev, `🤖: ${message}`]); |
| 41 | + setLoading(false); |
| 42 | + }; |
| 43 | + |
| 44 | + return ( |
| 45 | + <div className="p-4 border rounded shadow-lg bg-background text-foreground w-96 max-h-96"> |
| 46 | + <div className="overflow-y-auto max-h-60 mb-4"> |
| 47 | + {messages.map((msg, index) => ( |
| 48 | + <p className="mb-2" key={index}> |
| 49 | + {msg} |
| 50 | + </p> |
| 51 | + ))} |
| 52 | + </div> |
| 53 | + <form className="flex flex-col gap-2" onSubmit={handleSubmit}> |
| 54 | + <Input |
| 55 | + type="text" |
| 56 | + name="message" |
| 57 | + value={input} |
| 58 | + onChange={(e) => setInput(e.target.value)} |
| 59 | + autoComplete="off" |
| 60 | + /> |
| 61 | + <Button size="lg" type="submit" disabled={!input.trim() || loading}> |
| 62 | + {loading ? "Pensando..." : "Enviar"} |
| 63 | + </Button> |
| 64 | + </form> |
| 65 | + </div> |
| 66 | + ); |
| 67 | +} |
0 commit comments