'use client'; import { useState, useEffect } from 'react'; import { Box, Typography, CircularProgress, Alert } from '@mui/material'; import { LineChart, Line, BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer, } from 'recharts'; import { format, subDays } from 'date-fns'; import apiClient from '@/lib/api/client'; interface SleepData { date: string; totalHours: number; nightSleep: number; naps: number; quality: number; } export default function WeeklySleepChart() { const [data, setData] = useState([]); const [isLoading, setIsLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { fetchSleepData(); }, []); const fetchSleepData = async () => { try { setIsLoading(true); const endDate = new Date(); const startDate = subDays(endDate, 6); const response = await apiClient.get('/api/v1/activities/sleep', { params: { startDate: startDate.toISOString(), endDate: endDate.toISOString(), }, }); // Process the data to aggregate by day const sleepActivities = response.data.data; const dailyData: { [key: string]: SleepData } = {}; // Initialize 7 days of data for (let i = 0; i < 7; i++) { const date = subDays(endDate, 6 - i); const dateStr = format(date, 'MMM dd'); dailyData[dateStr] = { date: dateStr, totalHours: 0, nightSleep: 0, naps: 0, quality: 0, }; } // Aggregate sleep data by day sleepActivities.forEach((activity: any) => { const dateStr = format(new Date(activity.startTime), 'MMM dd'); if (dailyData[dateStr]) { const duration = activity.duration || 0; const hours = duration / 60; // Convert minutes to hours dailyData[dateStr].totalHours += hours; // Determine if it's night sleep or nap based on time const hour = new Date(activity.startTime).getHours(); if (hour >= 18 || hour < 6) { dailyData[dateStr].nightSleep += hours; } else { dailyData[dateStr].naps += hours; } // Average quality if (activity.quality) { dailyData[dateStr].quality = (dailyData[dateStr].quality + activity.quality) / 2; } } }); // Round values for display const chartData = Object.values(dailyData).map((day) => ({ ...day, totalHours: Math.round(day.totalHours * 10) / 10, nightSleep: Math.round(day.nightSleep * 10) / 10, naps: Math.round(day.naps * 10) / 10, quality: Math.round(day.quality * 10) / 10, })); setData(chartData); } catch (err: any) { console.error('Failed to fetch sleep data:', err); setError(err.response?.data?.message || 'Failed to load sleep data'); } finally { setIsLoading(false); } }; if (isLoading) { return ( ); } if (error) { return ( {error} ); } return ( Weekly Sleep Patterns Track your child's sleep duration and quality over the past 7 days {/* Total Sleep Hours Chart */} Total Sleep Hours {/* Sleep Quality Trend */} Sleep Quality Trend ); }