"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); const [error, setError] = useState(""); const [deleteConfirm, setDeleteConfirm] = useState(null); useEffect(() => { console.log("AI page: childId from useFamily:", childId); if (childId) { fetchSessions(); } }, [childId]); const fetchSessions = async () => { if (!childId) return; try { const res = await fetch(`/api/chat?childId=${childId}`); const data = await res.json(); if (data.error) { setError(data.error); console.error("API error:", data.error); return; } setSessions(data.sessions || []); setError(""); } 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) return; setLoading(true); const userContent = input.trim(); setInput(""); // Show user message immediately in UI const tempUserMsg = { id: "temp-" + Date.now(), role: "user" as const, content: userContent, createdAt: new Date().toISOString() }; if (currentSessionId) { const sessionIdx = sessions.findIndex(s => s.id === currentSessionId); if (sessionIdx >= 0) { const updatedSessions = [...sessions]; updatedSessions[sessionIdx] = { ...updatedSessions[sessionIdx], messages: [...(updatedSessions[sessionIdx].messages || []), tempUserMsg] }; setSessions(updatedSessions); } } // Auto-create session if none selected let sessionId = currentSessionId; if (!sessionId && childId) { try { const res = await fetch("/api/chat", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ childId, title: userContent.slice(0, 30) }), }); const data = await res.json(); if (data.session) { sessionId = data.session.id; const newSession = { ...data.session, messages: [tempUserMsg] }; setSessions([newSession, ...sessions]); setCurrentSessionId(sessionId); } } catch (err) { console.error("Failed to create session:", err); setLoading(false); return; } } if (!sessionId) { setLoading(false); return; } try { // Save user message await fetch("/api/chat", { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ sessionId, role: "user", content: userContent }), }); // Get AI response const aiRes = await fetch("/api/ai", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ messages: [{ role: "user", content: userContent }] }), }); 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, 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)); setDeleteConfirm(null); } catch (err) { console.error("Failed to delete:", err); } }; return (
{error && (
Error: {error}
)} {/* Header - same pattern as other pages */}

AI Chat

{/* Sidebar */}

Chats

{(sessions || []).map(session => (
setCurrentSessionId(session.id)} className={`p-2 rounded-lg cursor-pointer flex justify-between items-center dark:text-gray-100 ${session.id === currentSessionId ? "bg-rose-100 dark:bg-rose-900" : ""}`} >
{session.title}
{new Date(session.updatedAt).toLocaleDateString()}
{deleteConfirm === session.id && (

Delete this conversation?

)}
))}
{/* 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 dark:bg-gray-700 dark:text-white" disabled={loading} />
); }