'use client'; import { useState, useEffect } from 'react'; import { Box, Paper, Typography, FormControl, InputLabel, Select, MenuItem, CircularProgress, Alert, Grid, Card, CardContent, Avatar, Chip, } from '@mui/material'; import { useSelector } from 'react-redux'; import { childrenSelectors, Child } from '@/store/slices/childrenSlice'; import { RootState } from '@/store/store'; import ChildSelector from '@/components/common/ChildSelector'; import { DatePicker } from '@mui/x-date-pickers/DatePicker'; import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider'; import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns'; import { LineChart, Line, BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts'; import { analyticsApi, ComparisonMetric } from '@/lib/api/analytics'; import { subDays } from 'date-fns'; const METRICS = [ { value: 'sleep-patterns', label: 'Sleep Patterns' }, { value: 'feeding-frequency', label: 'Feeding Frequency' }, { value: 'diaper-changes', label: 'Diaper Changes' }, { value: 'activities', label: 'Activities' }, ]; export default function ComparisonView() { const children = useSelector((state: RootState) => childrenSelectors.selectAll(state)); const [selectedChildIds, setSelectedChildIds] = useState([]); const [metric, setMetric] = useState('sleep-patterns' as ComparisonMetric); const [startDate, setStartDate] = useState(subDays(new Date(), 7)); const [endDate, setEndDate] = useState(new Date()); const [comparisonData, setComparisonData] = useState(null); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); useEffect(() => { if (selectedChildIds.length >= 2) { fetchComparison(); } }, [selectedChildIds, metric, startDate, endDate]); const fetchComparison = async () => { if (selectedChildIds.length < 2) { setError('Please select at least 2 children to compare'); return; } setLoading(true); setError(null); try { const result = await analyticsApi.compareChildren( selectedChildIds, metric, startDate.toISOString(), endDate.toISOString() ); setComparisonData(result); } catch (err: any) { console.error('Failed to fetch comparison:', err); setError(err.response?.data?.message || 'Failed to load comparison data'); } finally { setLoading(false); } }; const getChildById = (childId: string): Child | undefined => { return children.find(c => c.id === childId); }; const renderMetricSummary = () => { if (!comparisonData) return null; const { children: childrenData } = comparisonData; return ( {childrenData.map((childData: any) => { const child = getChildById(childData.childId); if (!child) return null; let summaryText = ''; if (metric === 'sleep-patterns') { summaryText = `${childData.data.averageHoursPerDay.toFixed(1)}h avg sleep`; } else if (metric === 'feeding-frequency') { summaryText = `${childData.data.averagePerDay.toFixed(1)} feeds/day`; } else if (metric === 'diaper-changes') { summaryText = `${childData.data.totalChanges} total changes`; } else if (metric === 'activities') { summaryText = `${childData.data.totalActivities} total activities`; } return ( {child.name[0]} {child.name} {child.nickname && ( {child.nickname} )} ); })} ); }; const renderChart = () => { if (!comparisonData) return null; const { children: childrenData } = comparisonData; // Transform data for charts const chartData: any[] = []; if (metric === 'sleep-patterns' || metric === 'feeding-frequency') { // Use daily breakdown data const days = childrenData[0]?.data?.dailyBreakdown || []; days.forEach((dayData: any, index: number) => { const dataPoint: any = { date: new Date(dayData.date).toLocaleDateString('en-US', { month: 'short', day: 'numeric' }), }; childrenData.forEach((childData: any) => { const child = getChildById(childData.childId); if (!child) return; const dayValue = childData.data.dailyBreakdown[index]; if (metric === 'sleep-patterns') { dataPoint[child.name] = dayValue?.hours || 0; } else if (metric === 'feeding-frequency') { dataPoint[child.name] = dayValue?.count || 0; } }); chartData.push(dataPoint); }); } return ( {childrenData.map((childData: any) => { const child = getChildById(childData.childId); if (!child) return null; return ( ); })} ); }; if (children.length < 2) { return ( You need at least 2 children to use the comparison view. Add more children to get started. ); } return ( {/* Filters */} Compare Children Metric date && setStartDate(date)} slotProps={{ textField: { fullWidth: true } }} /> date && setEndDate(date)} slotProps={{ textField: { fullWidth: true } }} /> {/* Error */} {error && ( setError(null)}> {error} )} {/* Loading */} {loading && ( )} {/* Results */} {!loading && comparisonData && ( <> {renderMetricSummary()} Comparison Chart {renderChart()} )} ); }