"use client"; import { useState, useEffect } from "react"; import { useFamily } from "../FamilyProvider"; interface AIChat { id: string; role: "user" | "assistant"; content: string; createdAt: string; } interface ChatSession { id: string; title: string; messages: AIChat[]; createdAt: string; updatedAt: string; } export default function AIChatPage() { const { childId } = useFamily(); const [sessions, setSessions] = useState([]); const [currentSessionId, setCurrentSessionId] = useState(""); const [input, setInput] = useState(""); const [loading, setLoading] = useState(false); const [sidebarOpen, setSidebarOpen] = useState(true); useEffect(() => { if (childId) { fetchSessions(); } }, [childId]); const fetchSessions = async () => { if (!childId) return; try { const res = await fetch(`/api/chat?childId=${childId}`); const data = await res.json(); setSessions(data.sessions || []); } catch (err) { console.error("Failed to fetch:", err); } }; const createNewSession = async () => { try { const res = await fetch("/api/chat", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ childId, title: "New conversation" }), }); const data = await res.json(); if (data.session) { setSessions([data.session, ...sessions]); setCurrentSessionId(data.session.id); } } catch (err) { console.error("Failed to create:", err); } }; const currentSession = sessions.find(s => s.id === currentSessionId); const handleSend = async () => { if (!input.trim() || loading || !currentSession) return; setLoading(true); const userContent = input.trim(); setInput(""); try { // Save user message await fetch("/api/chat", { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ sessionId: currentSessionId, role: "user", content: userContent }), }); // Get AI response const aiRes = await fetch("/api/ai", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ messages: currentSession.messages.concat({ id: "", role: "user", content: userContent, createdAt: "" }) }), }); const aiData = await aiRes.json(); // Save AI response if (aiData.reply) { await fetch("/api/chat", { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ sessionId: currentSessionId, role: "assistant", content: aiData.reply }), }); } // Refresh sessions fetchSessions(); } catch (err) { console.error("Failed to send:", err); } setLoading(false); }; const deleteSession = async (id: string) => { try { await fetch(`/api/chat?id=${id}`, { method: "DELETE" }); setSessions(sessions.filter(s => s.id !== id)); } catch (err) { console.error("Failed to delete:", err); } }; return (
{/* Sidebar */}

AI Chat

{sessions.map(session => (
setCurrentSessionId(session.id)} className={`p-2 rounded-lg cursor-pointer ${session.id === currentSessionId ? "bg-rose-100" : ""}`} >
{session.title}
{new Date(session.updatedAt).toLocaleDateString()}
))}
{/* Main chat */}
{currentSession?.title || "AI Chat"}
{currentSession?.messages.map((msg, i) => (
{msg.content}
))}
setInput(e.target.value)} onKeyDown={e => e.key === "Enter" && handleSend()} placeholder="Ask about your baby..." className="flex-1 p-3 border rounded-lg" disabled={loading} />
); }