'use client'; import React, { useState, useEffect } from 'react'; import { useAuth } from '@/lib/auth/AuthContext'; import { childrenApi, Child } from '@/lib/api/children'; import { analyticsApi, CircadianRhythm, AnomalyDetection, GrowthAnalysis, CorrelationAnalysis, TrendAnalysis, } from '@/lib/api/analytics'; import { CircadianRhythmCard } from '@/components/analytics/CircadianRhythmCard'; import { AnomalyAlertsPanel } from '@/components/analytics/AnomalyAlertsPanel'; import { GrowthPercentileChart } from '@/components/analytics/GrowthPercentileChart'; import { CorrelationInsights } from '@/components/analytics/CorrelationInsights'; import { TrendAnalysisChart } from '@/components/analytics/TrendAnalysisChart'; import { Card, CardContent, CardHeader, Button, Alert, AlertTitle, Tabs, Tab, Box, Select, MenuItem, FormControl, InputLabel, } from '@mui/material'; import { Loader2, RefreshCw, Activity, Brain, TrendingUp, Baby, Link } from 'lucide-react'; import { AppShell } from '@/components/layouts/AppShell/AppShell'; import { ProtectedRoute } from '@/components/common/ProtectedRoute'; import { extractError } from '@/lib/utils/errorHandler'; export default function AdvancedAnalyticsPage() { const { user } = useAuth(); const [children, setChildren] = useState([]); const [selectedChildId, setSelectedChildId] = useState(''); const [loading, setLoading] = useState(true); const [error, setError] = useState(''); const [activeTab, setActiveTab] = useState(0); // Analytics data states const [circadianData, setCircadianData] = useState(null); const [anomalyData, setAnomalyData] = useState(null); const [growthData, setGrowthData] = useState(null); const [correlationData, setCorrelationData] = useState(null); const [sleepTrendData, setSleepTrendData] = useState(null); const [feedingTrendData, setFeedingTrendData] = useState(null); // Loading states for each component const [circadianLoading, setCircadianLoading] = useState(false); const [anomalyLoading, setAnomalyLoading] = useState(false); const [growthLoading, setGrowthLoading] = useState(false); const [correlationLoading, setCorrelationLoading] = useState(false); const [trendLoading, setTrendLoading] = useState(false); // Error states for each component const [circadianError, setCircadianError] = useState(null); const [anomalyError, setAnomalyError] = useState(null); const [growthError, setGrowthError] = useState(null); const [correlationError, setCorrelationError] = useState(null); const [trendError, setTrendError] = useState(null); const familyId = user?.families?.[0]?.familyId; useEffect(() => { if (familyId) { loadChildren(); } }, [familyId]); useEffect(() => { if (selectedChildId && children.length > 0) { const childExists = children.some(child => child.id === selectedChildId); if (childExists) { loadAllAnalytics(); } else { console.warn('[AdvancedAnalytics] Selected child not found, resetting'); setSelectedChildId(children[0].id); } } }, [selectedChildId, children]); const loadChildren = async () => { if (!familyId) { setLoading(false); setError('No family found'); return; } try { console.log('[AdvancedAnalytics] Loading children for familyId:', familyId); const data = await childrenApi.getChildren(familyId); console.log('[AdvancedAnalytics] Loaded children:', data); setChildren(data); if (data.length > 0) { const existingChildStillValid = data.some(child => child.id === selectedChildId); if (!selectedChildId || !existingChildStillValid) { setSelectedChildId(data[0].id); } } setError(''); } catch (error: any) { console.error('[AdvancedAnalytics] Failed to load children:', error); const errorData = extractError(error); setError(errorData.userMessage || errorData.message); } finally { setLoading(false); } }; const loadAllAnalytics = () => { loadCircadianRhythm(); loadAnomalies(); loadGrowthAnalysis(); loadCorrelations(); loadTrends(); }; const loadCircadianRhythm = async () => { if (!selectedChildId) return; setCircadianLoading(true); setCircadianError(null); try { const data = await analyticsApi.getCircadianRhythm(selectedChildId, 14); setCircadianData(data); } catch (error: any) { console.error('[AdvancedAnalytics] Failed to load circadian rhythm:', error); console.error("Circadian error:", extractError(error).message); setCircadianError(error as Error); } finally { setCircadianLoading(false); } }; const loadAnomalies = async () => { if (!selectedChildId) return; setAnomalyLoading(true); setAnomalyError(null); try { const data = await analyticsApi.getAnomalies(selectedChildId, 30); setAnomalyData(data); } catch (error: any) { console.error('[AdvancedAnalytics] Failed to load anomalies:', error); console.error("Anomalies error:", extractError(error).message); setAnomalyError(error as Error); } finally { setAnomalyLoading(false); } }; const loadGrowthAnalysis = async () => { if (!selectedChildId) return; setGrowthLoading(true); setGrowthError(null); try { const data = await analyticsApi.getGrowthAnalysis(selectedChildId); setGrowthData(data); } catch (error: any) { console.error('[AdvancedAnalytics] Failed to load growth analysis:', error); console.error("Growth error:", extractError(error).message); setGrowthError(error as Error); } finally { setGrowthLoading(false); } }; const loadCorrelations = async () => { if (!selectedChildId) return; setCorrelationLoading(true); setCorrelationError(null); try { const data = await analyticsApi.getCorrelations(selectedChildId, 14); setCorrelationData(data); } catch (error: any) { console.error('[AdvancedAnalytics] Failed to load correlations:', error); console.error("Correlations error:", extractError(error).message); setCorrelationError(error as Error); } finally { setCorrelationLoading(false); } }; const loadTrends = async () => { if (!selectedChildId) return; setTrendLoading(true); setTrendError(null); try { const [sleepTrend, feedingTrend] = await Promise.all([ analyticsApi.getTrends(selectedChildId, 'sleep'), analyticsApi.getTrends(selectedChildId, 'feeding'), ]); setSleepTrendData(sleepTrend); setFeedingTrendData(feedingTrend); } catch (error: any) { console.error('[AdvancedAnalytics] Failed to load trends:', error); console.error("Trends error:", extractError(error).message); setTrendError(error as Error); } finally { setTrendLoading(false); } }; if (loading) { return (
); } if (children.length === 0) { return (
No Children Found Add a child to your family to view advanced analytics.
); } return (
{/* Header */}

Advanced Analytics

AI-powered insights and deep analysis of your child's patterns

{/* Child Selector */}
{error && ( Error {error} )} {/* Analytics Tabs */} setActiveTab(newValue)} variant="scrollable" scrollButtons="auto" > } iconPosition="start" label="Sleep Rhythm" /> } iconPosition="start" label="Anomalies" /> } iconPosition="start" label="Growth" /> } iconPosition="start" label="Correlations" /> } iconPosition="start" label="Trends" /> {activeTab === 0 && ( )} {activeTab === 1 && ( )} {activeTab === 2 && ( )} {activeTab === 3 && ( )} {activeTab === 4 && (
)}
); }