Add comprehensive .gitignore

This commit is contained in:
2025-10-01 19:01:52 +00:00
commit f3ff07c0ef
254 changed files with 88254 additions and 0 deletions

View File

@@ -0,0 +1,221 @@
'use client';
import { useState } from 'react';
import { useRouter } from 'next/navigation';
import {
Box,
TextField,
Button,
Typography,
Paper,
InputAdornment,
IconButton,
Divider,
Alert,
CircularProgress,
Link as MuiLink,
} from '@mui/material';
import { Visibility, VisibilityOff, Google, Apple } from '@mui/icons-material';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { motion } from 'framer-motion';
import * as z from 'zod';
import { useAuth } from '@/lib/auth/AuthContext';
import Link from 'next/link';
const loginSchema = z.object({
email: z.string().email('Invalid email address'),
password: z.string().min(8, 'Password must be at least 8 characters'),
});
type LoginFormData = z.infer<typeof loginSchema>;
export default function LoginPage() {
const [showPassword, setShowPassword] = useState(false);
const [error, setError] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(false);
const { login } = useAuth();
const router = useRouter();
const {
register,
handleSubmit,
formState: { errors },
} = useForm<LoginFormData>({
resolver: zodResolver(loginSchema),
});
const onSubmit = async (data: LoginFormData) => {
setError(null);
setIsLoading(true);
try {
await login(data);
// Navigation is handled in the login function
} catch (err: any) {
setError(err.message || 'Failed to login. Please check your credentials.');
} finally {
setIsLoading(false);
}
};
return (
<Box
sx={{
minHeight: '100vh',
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
px: 3,
py: 6,
background: 'linear-gradient(135deg, #FFE4E1 0%, #FFDAB9 100%)',
}}
>
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.5 }}
>
<Paper
elevation={0}
sx={{
p: 4,
borderRadius: 4,
maxWidth: 440,
mx: 'auto',
background: 'rgba(255, 255, 255, 0.95)',
backdropFilter: 'blur(10px)',
}}
>
<Typography
variant="h4"
gutterBottom
align="center"
fontWeight="600"
color="primary.main"
>
Welcome Back 👋
</Typography>
<Typography
variant="body2"
align="center"
color="text.secondary"
sx={{ mb: 3 }}
>
Sign in to continue tracking your child's journey
</Typography>
{error && (
<Alert severity="error" sx={{ mb: 3, borderRadius: 2 }}>
{error}
</Alert>
)}
<Box component="form" onSubmit={handleSubmit(onSubmit)}>
<TextField
fullWidth
label="Email"
type="email"
margin="normal"
error={!!errors.email}
helperText={errors.email?.message}
{...register('email')}
disabled={isLoading}
inputProps={{ autoComplete: 'username' }}
InputProps={{
sx: { borderRadius: 3 },
}}
/>
<TextField
fullWidth
label="Password"
type={showPassword ? 'text' : 'password'}
margin="normal"
error={!!errors.password}
helperText={errors.password?.message}
{...register('password')}
disabled={isLoading}
inputProps={{ autoComplete: 'current-password' }}
InputProps={{
sx: { borderRadius: 3 },
endAdornment: (
<InputAdornment position="end">
<IconButton
onClick={() => setShowPassword(!showPassword)}
edge="end"
disabled={isLoading}
>
{showPassword ? <VisibilityOff /> : <Visibility />}
</IconButton>
</InputAdornment>
),
}}
/>
<Box sx={{ textAlign: 'right', mt: 1 }}>
<Link href="/forgot-password" passHref legacyBehavior>
<MuiLink variant="body2" sx={{ cursor: 'pointer' }}>
Forgot password?
</MuiLink>
</Link>
</Box>
<Button
fullWidth
type="submit"
variant="contained"
size="large"
disabled={isLoading}
sx={{ mt: 3, mb: 2 }}
>
{isLoading ? (
<CircularProgress size={24} color="inherit" />
) : (
'Sign In'
)}
</Button>
</Box>
<Divider sx={{ my: 3 }}>
<Typography variant="body2" color="text.secondary">
OR
</Typography>
</Divider>
<Button
fullWidth
variant="outlined"
startIcon={<Google />}
size="large"
disabled={isLoading}
sx={{ mb: 2 }}
>
Continue with Google
</Button>
<Button
fullWidth
variant="outlined"
startIcon={<Apple />}
size="large"
disabled={isLoading}
>
Continue with Apple
</Button>
<Box sx={{ mt: 3, textAlign: 'center' }}>
<Typography variant="body2" color="text.secondary">
Don't have an account?{' '}
<Link href="/register" passHref legacyBehavior>
<MuiLink sx={{ cursor: 'pointer', fontWeight: 600 }}>
Sign up
</MuiLink>
</Link>
</Typography>
</Box>
</Paper>
</motion.div>
</Box>
);
}

View File

@@ -0,0 +1,315 @@
'use client';
import { useState } from 'react';
import {
Box,
Stepper,
Step,
StepLabel,
Button,
Typography,
Paper,
TextField,
Avatar,
IconButton,
Alert,
CircularProgress,
MenuItem,
} from '@mui/material';
import { ArrowBack, ArrowForward, Check } from '@mui/icons-material';
import { motion, AnimatePresence } from 'framer-motion';
import { useRouter } from 'next/navigation';
import { useAuth } from '@/lib/auth/AuthContext';
import { childrenApi } from '@/lib/api/children';
const steps = ['Welcome', 'Add Child', 'Invite Family', 'Notifications'];
export default function OnboardingPage() {
const [activeStep, setActiveStep] = useState(0);
const [childName, setChildName] = useState('');
const [childBirthDate, setChildBirthDate] = useState('');
const [childGender, setChildGender] = useState<'male' | 'female' | 'other'>('other');
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const router = useRouter();
const { user } = useAuth();
const handleNext = async () => {
// Validate and save child data on step 1 (Add Child)
if (activeStep === 1) {
if (!childName.trim() || !childBirthDate) {
setError('Please enter child name and birth date');
return;
}
const familyId = user?.families?.[0]?.familyId;
if (!familyId) {
setError('No family found. Please try logging out and back in.');
return;
}
try {
setLoading(true);
setError('');
await childrenApi.createChild(familyId, {
name: childName.trim(),
birthDate: childBirthDate,
gender: childGender,
});
setActiveStep((prevActiveStep) => prevActiveStep + 1);
} catch (err: any) {
console.error('Failed to create child:', err);
setError(err.response?.data?.message || 'Failed to save child. Please try again.');
} finally {
setLoading(false);
}
return;
}
if (activeStep === steps.length - 1) {
// Complete onboarding
router.push('/');
} else {
setActiveStep((prevActiveStep) => prevActiveStep + 1);
}
};
const handleBack = () => {
setActiveStep((prevActiveStep) => prevActiveStep - 1);
};
const handleSkip = () => {
router.push('/');
};
return (
<Box
sx={{
minHeight: '100vh',
display: 'flex',
flexDirection: 'column',
px: 3,
py: 4,
background: 'linear-gradient(135deg, #FFE4E1 0%, #FFDAB9 100%)',
}}
>
<Paper
elevation={0}
sx={{
maxWidth: 600,
mx: 'auto',
width: '100%',
p: 4,
borderRadius: 4,
background: 'rgba(255, 255, 255, 0.95)',
backdropFilter: 'blur(10px)',
}}
>
<Stepper activeStep={activeStep} sx={{ mb: 4 }}>
{steps.map((label) => (
<Step key={label}>
<StepLabel>{label}</StepLabel>
</Step>
))}
</Stepper>
<AnimatePresence mode="wait">
<motion.div
key={activeStep}
initial={{ opacity: 0, x: 20 }}
animate={{ opacity: 1, x: 0 }}
exit={{ opacity: 0, x: -20 }}
transition={{ duration: 0.3 }}
>
{activeStep === 0 && (
<Box sx={{ textAlign: 'center', py: 4 }}>
<Typography variant="h4" gutterBottom fontWeight="600" color="primary.main">
Welcome to Maternal! 🎉
</Typography>
<Typography variant="body1" color="text.secondary" sx={{ mt: 2, mb: 4 }}>
We're excited to help you track and understand your child's development, sleep patterns, feeding schedules, and more.
</Typography>
<Box sx={{ display: 'flex', gap: 2, justifyContent: 'center', flexWrap: 'wrap' }}>
<Paper sx={{ p: 2, flex: 1, minWidth: 150 }}>
<Typography variant="h6" fontWeight="600">📊</Typography>
<Typography variant="body2">Track Activities</Typography>
</Paper>
<Paper sx={{ p: 2, flex: 1, minWidth: 150 }}>
<Typography variant="h6" fontWeight="600">🤖</Typography>
<Typography variant="body2">AI Insights</Typography>
</Paper>
<Paper sx={{ p: 2, flex: 1, minWidth: 150 }}>
<Typography variant="h6" fontWeight="600">👨👩👧</Typography>
<Typography variant="body2">Family Sharing</Typography>
</Paper>
</Box>
</Box>
)}
{activeStep === 1 && (
<Box sx={{ py: 4 }}>
<Typography variant="h5" gutterBottom fontWeight="600">
Add Your First Child
</Typography>
<Typography variant="body2" color="text.secondary" sx={{ mb: 3 }}>
Let's start by adding some basic information about your child.
</Typography>
{error && (
<Alert severity="error" sx={{ mb: 2, borderRadius: 2 }}>
{error}
</Alert>
)}
<TextField
fullWidth
label="Child's Name"
value={childName}
onChange={(e) => setChildName(e.target.value)}
margin="normal"
required
disabled={loading}
InputProps={{
sx: { borderRadius: 3 },
}}
/>
<TextField
fullWidth
label="Birth Date"
type="date"
value={childBirthDate}
onChange={(e) => setChildBirthDate(e.target.value)}
margin="normal"
required
disabled={loading}
InputLabelProps={{
shrink: true,
}}
InputProps={{
sx: { borderRadius: 3 },
}}
/>
<TextField
fullWidth
select
label="Gender"
value={childGender}
onChange={(e) => setChildGender(e.target.value as 'male' | 'female' | 'other')}
margin="normal"
disabled={loading}
InputProps={{
sx: { borderRadius: 3 },
}}
>
<MenuItem value="male">Male</MenuItem>
<MenuItem value="female">Female</MenuItem>
<MenuItem value="other">Prefer not to say</MenuItem>
</TextField>
<Alert severity="info" sx={{ mt: 3, borderRadius: 2 }}>
You can add more children and details later from settings.
</Alert>
</Box>
)}
{activeStep === 2 && (
<Box sx={{ py: 4 }}>
<Typography variant="h5" gutterBottom fontWeight="600">
Invite Family Members
</Typography>
<Typography variant="body2" color="text.secondary" sx={{ mb: 3 }}>
Share your child's progress with family members. They can view activities and add their own entries.
</Typography>
<TextField
fullWidth
label="Email Address"
type="email"
margin="normal"
placeholder="partner@example.com"
InputProps={{
sx: { borderRadius: 3 },
}}
/>
<Button
variant="outlined"
fullWidth
sx={{ mt: 2 }}
>
Send Invitation
</Button>
<Alert severity="info" sx={{ mt: 3, borderRadius: 2 }}>
You can skip this step and invite family members later.
</Alert>
</Box>
)}
{activeStep === 3 && (
<Box sx={{ textAlign: 'center', py: 4 }}>
<Avatar
sx={{
width: 80,
height: 80,
bgcolor: 'primary.main',
mx: 'auto',
mb: 3,
}}
>
<Check sx={{ fontSize: 48 }} />
</Avatar>
<Typography variant="h5" gutterBottom fontWeight="600">
You're All Set! 🎉
</Typography>
<Typography variant="body1" color="text.secondary" sx={{ mb: 4 }}>
Start tracking your child's activities and get personalized insights.
</Typography>
<Paper sx={{ p: 3, bgcolor: 'primary.light', mb: 3 }}>
<Typography variant="body2" fontWeight="600" gutterBottom>
Next Steps:
</Typography>
<Typography variant="body2" align="left" component="div">
• Track your first feeding, sleep, or diaper change<br />
• Chat with our AI assistant for parenting tips<br />
• Explore insights and predictions based on your data
</Typography>
</Paper>
</Box>
)}
</motion.div>
</AnimatePresence>
<Box sx={{ display: 'flex', justifyContent: 'space-between', mt: 4 }}>
<Button
onClick={handleBack}
disabled={activeStep === 0}
startIcon={<ArrowBack />}
>
Back
</Button>
<Box sx={{ flex: 1 }} />
{activeStep < steps.length - 1 && activeStep > 0 && (
<Button onClick={handleSkip} sx={{ mr: 2 }}>
Skip
</Button>
)}
<Button
variant="contained"
onClick={handleNext}
disabled={loading}
endIcon={loading ? <CircularProgress size={20} /> : (activeStep === steps.length - 1 ? <Check /> : <ArrowForward />)}
>
{activeStep === steps.length - 1 ? 'Get Started' : 'Next'}
</Button>
</Box>
</Paper>
</Box>
);
}

View File

@@ -0,0 +1,268 @@
'use client';
import { useState } from 'react';
import {
Box,
TextField,
Button,
Typography,
Paper,
InputAdornment,
IconButton,
Alert,
CircularProgress,
Link as MuiLink,
Checkbox,
FormControlLabel,
} from '@mui/material';
import { Visibility, VisibilityOff } from '@mui/icons-material';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { motion } from 'framer-motion';
import * as z from 'zod';
import { useAuth } from '@/lib/auth/AuthContext';
import Link from 'next/link';
const registerSchema = z.object({
name: z.string().min(2, 'Name must be at least 2 characters'),
email: z.string().email('Invalid email address'),
password: z.string()
.min(8, 'Password must be at least 8 characters')
.regex(/[A-Z]/, 'Password must contain at least one uppercase letter')
.regex(/[a-z]/, 'Password must contain at least one lowercase letter')
.regex(/[0-9]/, 'Password must contain at least one number'),
confirmPassword: z.string(),
agreeToTerms: z.boolean().refine(val => val === true, {
message: 'You must agree to the terms and conditions',
}),
}).refine((data) => data.password === data.confirmPassword, {
message: 'Passwords do not match',
path: ['confirmPassword'],
});
type RegisterFormData = z.infer<typeof registerSchema>;
export default function RegisterPage() {
const [showPassword, setShowPassword] = useState(false);
const [showConfirmPassword, setShowConfirmPassword] = useState(false);
const [error, setError] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(false);
const { register: registerUser } = useAuth();
const {
register,
handleSubmit,
formState: { errors },
} = useForm<RegisterFormData>({
resolver: zodResolver(registerSchema),
});
const onSubmit = async (data: RegisterFormData) => {
setError(null);
setIsLoading(true);
try {
await registerUser({
name: data.name,
email: data.email,
password: data.password,
});
// Navigation to onboarding is handled in the register function
} catch (err: any) {
setError(err.message || 'Failed to register. Please try again.');
} finally {
setIsLoading(false);
}
};
return (
<Box
sx={{
minHeight: '100vh',
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
px: 3,
py: 6,
background: 'linear-gradient(135deg, #FFE4E1 0%, #FFDAB9 100%)',
}}
>
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.5 }}
>
<Paper
elevation={0}
sx={{
p: 4,
borderRadius: 4,
maxWidth: 440,
mx: 'auto',
background: 'rgba(255, 255, 255, 0.95)',
backdropFilter: 'blur(10px)',
}}
>
<Typography
variant="h4"
gutterBottom
align="center"
fontWeight="600"
color="primary.main"
>
Create Account
</Typography>
<Typography
variant="body2"
align="center"
color="text.secondary"
sx={{ mb: 3 }}
>
Start your journey to organized parenting
</Typography>
{error && (
<Alert severity="error" sx={{ mb: 3, borderRadius: 2 }}>
{error}
</Alert>
)}
<Box component="form" onSubmit={handleSubmit(onSubmit)}>
<TextField
fullWidth
label="Full Name"
margin="normal"
error={!!errors.name}
helperText={errors.name?.message}
{...register('name')}
disabled={isLoading}
InputProps={{
sx: { borderRadius: 3 },
}}
/>
<TextField
fullWidth
label="Email"
type="email"
margin="normal"
error={!!errors.email}
helperText={errors.email?.message}
{...register('email')}
disabled={isLoading}
inputProps={{ autoComplete: 'username' }}
InputProps={{
sx: { borderRadius: 3 },
}}
/>
<TextField
fullWidth
label="Password"
type={showPassword ? 'text' : 'password'}
margin="normal"
error={!!errors.password}
helperText={errors.password?.message}
{...register('password')}
disabled={isLoading}
inputProps={{ autoComplete: 'new-password' }}
InputProps={{
sx: { borderRadius: 3 },
endAdornment: (
<InputAdornment position="end">
<IconButton
onClick={() => setShowPassword(!showPassword)}
edge="end"
disabled={isLoading}
>
{showPassword ? <VisibilityOff /> : <Visibility />}
</IconButton>
</InputAdornment>
),
}}
/>
<TextField
fullWidth
label="Confirm Password"
type={showConfirmPassword ? 'text' : 'password'}
margin="normal"
error={!!errors.confirmPassword}
helperText={errors.confirmPassword?.message}
{...register('confirmPassword')}
disabled={isLoading}
inputProps={{ autoComplete: 'new-password' }}
InputProps={{
sx: { borderRadius: 3 },
endAdornment: (
<InputAdornment position="end">
<IconButton
onClick={() => setShowConfirmPassword(!showConfirmPassword)}
edge="end"
disabled={isLoading}
>
{showConfirmPassword ? <VisibilityOff /> : <Visibility />}
</IconButton>
</InputAdornment>
),
}}
/>
<FormControlLabel
control={
<Checkbox
{...register('agreeToTerms')}
disabled={isLoading}
/>
}
label={
<Typography variant="body2" color="text.secondary">
I agree to the{' '}
<MuiLink href="/terms" target="_blank">
Terms of Service
</MuiLink>{' '}
and{' '}
<MuiLink href="/privacy" target="_blank">
Privacy Policy
</MuiLink>
</Typography>
}
sx={{ mt: 2 }}
/>
{errors.agreeToTerms && (
<Typography variant="caption" color="error" sx={{ display: 'block', mt: 1 }}>
{errors.agreeToTerms.message}
</Typography>
)}
<Button
fullWidth
type="submit"
variant="contained"
size="large"
disabled={isLoading}
sx={{ mt: 3, mb: 2 }}
>
{isLoading ? (
<CircularProgress size={24} color="inherit" />
) : (
'Create Account'
)}
</Button>
</Box>
<Box sx={{ mt: 3, textAlign: 'center' }}>
<Typography variant="body2" color="text.secondary">
Already have an account?{' '}
<Link href="/login" passHref legacyBehavior>
<MuiLink sx={{ cursor: 'pointer', fontWeight: 600 }}>
Sign in
</MuiLink>
</Link>
</Typography>
</Box>
</Paper>
</motion.div>
</Box>
);
}

View File

@@ -0,0 +1,25 @@
'use client';
import { lazy, Suspense } from 'react';
import { AppShell } from '@/components/layouts/AppShell/AppShell';
import { ProtectedRoute } from '@/components/common/ProtectedRoute';
import { LoadingFallback } from '@/components/common/LoadingFallback';
// Lazy load the AI chat interface component
const AIChatInterface = lazy(() =>
import('@/components/features/ai-chat/AIChatInterface').then((mod) => ({
default: mod.AIChatInterface,
}))
);
export default function AIAssistantPage() {
return (
<ProtectedRoute>
<AppShell>
<Suspense fallback={<LoadingFallback variant="chat" />}>
<AIChatInterface />
</Suspense>
</AppShell>
</ProtectedRoute>
);
}

View File

@@ -0,0 +1,263 @@
'use client';
import { useState, useEffect } from 'react';
import {
Box,
Typography,
Paper,
Grid,
Card,
CardContent,
Button,
CircularProgress,
Tabs,
Tab,
Alert,
} from '@mui/material';
import { AppShell } from '@/components/layouts/AppShell/AppShell';
import { ProtectedRoute } from '@/components/common/ProtectedRoute';
import {
TrendingUp,
Hotel,
Restaurant,
BabyChangingStation,
Download,
} from '@mui/icons-material';
import { motion } from 'framer-motion';
import apiClient from '@/lib/api/client';
import WeeklySleepChart from '@/components/analytics/WeeklySleepChart';
import FeedingFrequencyGraph from '@/components/analytics/FeedingFrequencyGraph';
import GrowthCurve from '@/components/analytics/GrowthCurve';
import PatternInsights from '@/components/analytics/PatternInsights';
interface TabPanelProps {
children?: React.ReactNode;
index: number;
value: number;
}
function TabPanel(props: TabPanelProps) {
const { children, value, index, ...other } = props;
return (
<div
role="tabpanel"
hidden={value !== index}
id={`analytics-tabpanel-${index}`}
aria-labelledby={`analytics-tab-${index}`}
{...other}
>
{value === index && <Box sx={{ pt: 3 }}>{children}</Box>}
</div>
);
}
export default function AnalyticsPage() {
const [tabValue, setTabValue] = useState(0);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [insights, setInsights] = useState<any>(null);
useEffect(() => {
fetchAnalytics();
}, []);
const fetchAnalytics = async () => {
try {
setIsLoading(true);
const response = await apiClient.get('/api/v1/analytics/insights');
setInsights(response.data.data);
} catch (err: any) {
console.error('Failed to fetch analytics:', err);
setError(err.response?.data?.message || 'Failed to load analytics');
} finally {
setIsLoading(false);
}
};
const handleExportReport = async () => {
try {
const response = await apiClient.get('/api/v1/analytics/reports/weekly', {
responseType: 'blob',
});
const blob = new Blob([response.data], { type: 'application/pdf' });
const url = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = `weekly-report-${new Date().toISOString().split('T')[0]}.pdf`;
link.click();
window.URL.revokeObjectURL(url);
} catch (err) {
console.error('Failed to export report:', err);
}
};
const handleTabChange = (event: React.SyntheticEvent, newValue: number) => {
setTabValue(newValue);
};
if (isLoading) {
return (
<ProtectedRoute>
<AppShell>
<Box
sx={{
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
minHeight: '60vh',
}}
>
<CircularProgress />
</Box>
</AppShell>
</ProtectedRoute>
);
}
return (
<ProtectedRoute>
<AppShell>
<Box>
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.5 }}
>
{/* Header */}
<Box
sx={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
mb: 3,
}}
>
<Box>
<Typography variant="h4" gutterBottom fontWeight="600">
Analytics & Insights 📊
</Typography>
<Typography variant="body1" color="text.secondary">
Track patterns and get personalized insights
</Typography>
</Box>
<Button
variant="contained"
startIcon={<Download />}
onClick={handleExportReport}
sx={{ borderRadius: 3 }}
>
Export Report
</Button>
</Box>
{error && (
<Alert severity="error" sx={{ mb: 3, borderRadius: 2 }}>
{error}
</Alert>
)}
{/* Summary Cards */}
<Grid container spacing={2} sx={{ mb: 4 }}>
<Grid item xs={12} sm={4}>
<Card
sx={{
background: 'linear-gradient(135deg, #B6D7FF 0%, #A5C9FF 100%)',
color: 'white',
}}
>
<CardContent>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 1 }}>
<Hotel sx={{ fontSize: 32 }} />
<Typography variant="h5" fontWeight="600">
{insights?.sleep?.averageHours || '0'}h
</Typography>
</Box>
<Typography variant="body2">Avg Sleep (7 days)</Typography>
</CardContent>
</Card>
</Grid>
<Grid item xs={12} sm={4}>
<Card
sx={{
background: 'linear-gradient(135deg, #FFB6C1 0%, #FFA5B0 100%)',
color: 'white',
}}
>
<CardContent>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 1 }}>
<Restaurant sx={{ fontSize: 32 }} />
<Typography variant="h5" fontWeight="600">
{insights?.feeding?.averagePerDay || '0'}
</Typography>
</Box>
<Typography variant="body2">Avg Feedings (7 days)</Typography>
</CardContent>
</Card>
</Grid>
<Grid item xs={12} sm={4}>
<Card
sx={{
background: 'linear-gradient(135deg, #FFE4B5 0%, #FFD9A0 100%)',
color: 'white',
}}
>
<CardContent>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 1 }}>
<BabyChangingStation sx={{ fontSize: 32 }} />
<Typography variant="h5" fontWeight="600">
{insights?.diaper?.averagePerDay || '0'}
</Typography>
</Box>
<Typography variant="body2">Avg Diapers (7 days)</Typography>
</CardContent>
</Card>
</Grid>
</Grid>
{/* Tabs */}
<Paper sx={{ borderRadius: 3, overflow: 'hidden' }}>
<Box sx={{ borderBottom: 1, borderColor: 'divider' }}>
<Tabs
value={tabValue}
onChange={handleTabChange}
aria-label="analytics tabs"
sx={{ px: 2 }}
>
<Tab label="Sleep Patterns" />
<Tab label="Feeding Patterns" />
<Tab label="Growth Curve" />
<Tab label="Insights" />
</Tabs>
</Box>
<TabPanel value={tabValue} index={0}>
<Box sx={{ p: 3 }}>
<WeeklySleepChart />
</Box>
</TabPanel>
<TabPanel value={tabValue} index={1}>
<Box sx={{ p: 3 }}>
<FeedingFrequencyGraph />
</Box>
</TabPanel>
<TabPanel value={tabValue} index={2}>
<Box sx={{ p: 3 }}>
<GrowthCurve />
</Box>
</TabPanel>
<TabPanel value={tabValue} index={3}>
<Box sx={{ p: 3 }}>
<PatternInsights insights={insights} />
</Box>
</TabPanel>
</Paper>
</motion.div>
</Box>
</AppShell>
</ProtectedRoute>
);
}

View File

@@ -0,0 +1,306 @@
'use client';
import { useState, useEffect } from 'react';
import {
Box,
Typography,
Grid,
Card,
CardContent,
Button,
Avatar,
IconButton,
CircularProgress,
Alert,
Chip,
CardActions,
} from '@mui/material';
import { Add, ChildCare, Edit, Delete, Cake } from '@mui/icons-material';
import { AppShell } from '@/components/layouts/AppShell/AppShell';
import { ProtectedRoute } from '@/components/common/ProtectedRoute';
import { useAuth } from '@/lib/auth/AuthContext';
import { childrenApi, Child, CreateChildData } from '@/lib/api/children';
import { ChildDialog } from '@/components/children/ChildDialog';
import { DeleteConfirmDialog } from '@/components/children/DeleteConfirmDialog';
import { motion } from 'framer-motion';
export default function ChildrenPage() {
const { user } = useAuth();
const [children, setChildren] = useState<Child[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string>('');
const [dialogOpen, setDialogOpen] = useState(false);
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
const [selectedChild, setSelectedChild] = useState<Child | null>(null);
const [childToDelete, setChildToDelete] = useState<Child | null>(null);
const [actionLoading, setActionLoading] = useState(false);
// Get familyId from user
const familyId = user?.families?.[0]?.familyId;
useEffect(() => {
if (familyId) {
fetchChildren();
} else {
setLoading(false);
setError('No family found. Please complete onboarding first.');
}
}, [familyId]);
const fetchChildren = async () => {
if (!familyId) return;
try {
setLoading(true);
setError('');
const data = await childrenApi.getChildren(familyId);
setChildren(data);
} catch (err: any) {
console.error('Failed to fetch children:', err);
setError(err.response?.data?.message || 'Failed to load children');
} finally {
setLoading(false);
}
};
const handleAddChild = () => {
setSelectedChild(null);
setDialogOpen(true);
};
const handleEditChild = (child: Child) => {
setSelectedChild(child);
setDialogOpen(true);
};
const handleDeleteClick = (child: Child) => {
setChildToDelete(child);
setDeleteDialogOpen(true);
};
const handleSubmit = async (data: CreateChildData) => {
if (!familyId) {
throw new Error('No family ID found');
}
try {
setActionLoading(true);
if (selectedChild) {
await childrenApi.updateChild(selectedChild.id, data);
} else {
await childrenApi.createChild(familyId, data);
}
await fetchChildren();
setDialogOpen(false);
} catch (err: any) {
console.error('Failed to save child:', err);
throw new Error(err.response?.data?.message || 'Failed to save child');
} finally {
setActionLoading(false);
}
};
const handleDeleteConfirm = async () => {
if (!childToDelete) return;
try {
setActionLoading(true);
await childrenApi.deleteChild(childToDelete.id);
await fetchChildren();
setDeleteDialogOpen(false);
setChildToDelete(null);
} catch (err: any) {
console.error('Failed to delete child:', err);
setError(err.response?.data?.message || 'Failed to delete child');
} finally {
setActionLoading(false);
}
};
const calculateAge = (birthDate: string): string => {
const birth = new Date(birthDate);
const today = new Date();
let years = today.getFullYear() - birth.getFullYear();
let months = today.getMonth() - birth.getMonth();
if (months < 0) {
years--;
months += 12;
}
if (today.getDate() < birth.getDate()) {
months--;
if (months < 0) {
years--;
months += 12;
}
}
if (years === 0) {
return `${months} month${months !== 1 ? 's' : ''}`;
} else if (months === 0) {
return `${years} year${years !== 1 ? 's' : ''}`;
} else {
return `${years} year${years !== 1 ? 's' : ''}, ${months} month${months !== 1 ? 's' : ''}`;
}
};
return (
<ProtectedRoute>
<AppShell>
<Box>
<Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 4 }}>
<Box>
<Typography variant="h4" fontWeight="600" gutterBottom>
Children
</Typography>
<Typography variant="body1" color="text.secondary">
Manage your family's children profiles
</Typography>
</Box>
<Button
variant="contained"
startIcon={<Add />}
onClick={handleAddChild}
disabled={loading || !familyId}
>
Add Child
</Button>
</Box>
{error && (
<Alert severity="error" sx={{ mb: 3 }} onClose={() => setError('')}>
{error}
</Alert>
)}
{loading ? (
<Box sx={{ display: 'flex', justifyContent: 'center', py: 8 }}>
<CircularProgress />
</Box>
) : children.length === 0 ? (
<Grid container spacing={3}>
<Grid item xs={12}>
<Card>
<CardContent sx={{ textAlign: 'center', py: 8 }}>
<ChildCare sx={{ fontSize: 64, color: 'text.secondary', mb: 2 }} />
<Typography variant="h6" color="text.secondary" gutterBottom>
No children added yet
</Typography>
<Typography variant="body2" color="text.secondary" sx={{ mb: 3 }}>
Add your first child to start tracking their activities
</Typography>
<Button
variant="contained"
startIcon={<Add />}
onClick={handleAddChild}
disabled={!familyId}
>
Add First Child
</Button>
</CardContent>
</Card>
</Grid>
</Grid>
) : (
<Grid container spacing={3}>
{children.map((child, index) => (
<Grid item xs={12} sm={6} md={4} key={child.id}>
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.3, delay: index * 0.1 }}
>
<Card
sx={{
height: '100%',
display: 'flex',
flexDirection: 'column',
}}
>
<CardContent sx={{ flexGrow: 1 }}>
<Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
<Avatar
src={child.photoUrl}
sx={{
width: 60,
height: 60,
bgcolor: child.gender === 'male' ? '#B6D7FF' : '#FFB6C1',
mr: 2,
}}
>
<ChildCare sx={{ fontSize: 32 }} />
</Avatar>
<Box sx={{ flexGrow: 1 }}>
<Typography variant="h6" fontWeight="600">
{child.name}
</Typography>
<Chip
label={child.gender}
size="small"
sx={{ textTransform: 'capitalize', mt: 0.5 }}
/>
</Box>
</Box>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 1 }}>
<Cake sx={{ fontSize: 20, color: 'text.secondary' }} />
<Typography variant="body2" color="text.secondary">
{new Date(child.birthDate).toLocaleDateString()}
</Typography>
</Box>
<Typography
variant="body2"
color="primary"
fontWeight="600"
sx={{ mt: 1 }}
>
Age: {calculateAge(child.birthDate)}
</Typography>
</CardContent>
<CardActions sx={{ justifyContent: 'flex-end', pt: 0 }}>
<IconButton
size="small"
onClick={() => handleEditChild(child)}
color="primary"
>
<Edit />
</IconButton>
<IconButton
size="small"
onClick={() => handleDeleteClick(child)}
color="error"
>
<Delete />
</IconButton>
</CardActions>
</Card>
</motion.div>
</Grid>
))}
</Grid>
)}
</Box>
<ChildDialog
open={dialogOpen}
onClose={() => setDialogOpen(false)}
onSubmit={handleSubmit}
child={selectedChild}
isLoading={actionLoading}
/>
<DeleteConfirmDialog
open={deleteDialogOpen}
onClose={() => setDeleteDialogOpen(false)}
onConfirm={handleDeleteConfirm}
childName={childToDelete?.name || ''}
isLoading={actionLoading}
/>
</AppShell>
</ProtectedRoute>
);
}

View File

@@ -0,0 +1,355 @@
'use client';
import { useState, useEffect } from 'react';
import {
Box,
Typography,
Grid,
Card,
CardContent,
Button,
Avatar,
Chip,
CircularProgress,
Alert,
IconButton,
Divider,
Snackbar,
} from '@mui/material';
import { PersonAdd, ContentCopy, People, Delete, GroupAdd } from '@mui/icons-material';
import { useAuth } from '@/lib/auth/AuthContext';
import { AppShell } from '@/components/layouts/AppShell/AppShell';
import { ProtectedRoute } from '@/components/common/ProtectedRoute';
import { familiesApi, Family, FamilyMember, InviteMemberData, JoinFamilyData } from '@/lib/api/families';
import { InviteMemberDialog } from '@/components/family/InviteMemberDialog';
import { JoinFamilyDialog } from '@/components/family/JoinFamilyDialog';
import { RemoveMemberDialog } from '@/components/family/RemoveMemberDialog';
import { motion } from 'framer-motion';
export default function FamilyPage() {
const { user, refreshUser } = useAuth();
const [family, setFamily] = useState<Family | null>(null);
const [members, setMembers] = useState<FamilyMember[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string>('');
const [inviteDialogOpen, setInviteDialogOpen] = useState(false);
const [joinDialogOpen, setJoinDialogOpen] = useState(false);
const [removeDialogOpen, setRemoveDialogOpen] = useState(false);
const [memberToRemove, setMemberToRemove] = useState<FamilyMember | null>(null);
const [actionLoading, setActionLoading] = useState(false);
const [snackbar, setSnackbar] = useState({ open: false, message: '' });
// Get familyId from user
const familyId = user?.families?.[0]?.familyId;
useEffect(() => {
if (familyId) {
fetchFamilyData();
} else {
setLoading(false);
setError('No family found. Please complete onboarding first.');
}
}, [familyId]);
const fetchFamilyData = async () => {
if (!familyId) return;
try {
setLoading(true);
setError('');
const [familyData, membersData] = await Promise.all([
familiesApi.getFamily(familyId),
familiesApi.getFamilyMembers(familyId),
]);
setFamily(familyData);
setMembers(membersData);
} catch (err: any) {
console.error('Failed to fetch family data:', err);
setError(err.response?.data?.message || 'Failed to load family information');
} finally {
setLoading(false);
}
};
const handleCopyCode = async () => {
if (!family?.shareCode) return;
try {
await navigator.clipboard.writeText(family.shareCode);
setSnackbar({ open: true, message: 'Share code copied to clipboard!' });
} catch (err) {
setSnackbar({ open: true, message: 'Failed to copy share code' });
}
};
const handleInviteMember = async (data: InviteMemberData) => {
if (!familyId) {
throw new Error('No family ID found');
}
try {
setActionLoading(true);
await familiesApi.inviteMember(familyId, data);
setSnackbar({ open: true, message: 'Invitation sent successfully!' });
await fetchFamilyData();
setInviteDialogOpen(false);
} catch (err: any) {
console.error('Failed to invite member:', err);
throw new Error(err.response?.data?.message || 'Failed to send invitation');
} finally {
setActionLoading(false);
}
};
const handleJoinFamily = async (data: JoinFamilyData) => {
try {
setActionLoading(true);
await familiesApi.joinFamily(data);
setSnackbar({ open: true, message: 'Successfully joined family!' });
await refreshUser();
await fetchFamilyData();
setJoinDialogOpen(false);
} catch (err: any) {
console.error('Failed to join family:', err);
throw new Error(err.response?.data?.message || 'Failed to join family');
} finally {
setActionLoading(false);
}
};
const handleRemoveClick = (member: FamilyMember) => {
setMemberToRemove(member);
setRemoveDialogOpen(true);
};
const handleRemoveConfirm = async () => {
if (!familyId || !memberToRemove) return;
try {
setActionLoading(true);
await familiesApi.removeMember(familyId, memberToRemove.userId);
setSnackbar({ open: true, message: 'Member removed successfully' });
await fetchFamilyData();
setRemoveDialogOpen(false);
setMemberToRemove(null);
} catch (err: any) {
console.error('Failed to remove member:', err);
setError(err.response?.data?.message || 'Failed to remove member');
} finally {
setActionLoading(false);
}
};
const getRoleColor = (role: string): 'primary' | 'secondary' | 'default' | 'success' | 'warning' | 'info' => {
switch (role) {
case 'parent':
return 'primary';
case 'caregiver':
return 'secondary';
case 'viewer':
return 'info';
default:
return 'default';
}
};
const isCurrentUser = (userId: string) => {
return user?.id === userId;
};
return (
<ProtectedRoute>
<AppShell>
<Box>
<Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 4 }}>
<Box>
<Typography variant="h4" fontWeight="600" gutterBottom>
Family
</Typography>
<Typography variant="body1" color="text.secondary">
Manage your family members and share access
</Typography>
</Box>
<Box sx={{ display: 'flex', gap: 1 }}>
<Button
variant="outlined"
startIcon={<GroupAdd />}
onClick={() => setJoinDialogOpen(true)}
disabled={loading}
>
Join Family
</Button>
<Button
variant="contained"
startIcon={<PersonAdd />}
onClick={() => setInviteDialogOpen(true)}
disabled={loading || !familyId}
>
Invite Member
</Button>
</Box>
</Box>
{error && (
<Alert severity="error" sx={{ mb: 3 }} onClose={() => setError('')}>
{error}
</Alert>
)}
{loading ? (
<Box sx={{ display: 'flex', justifyContent: 'center', py: 8 }}>
<CircularProgress />
</Box>
) : (
<Grid container spacing={3}>
{/* Family Share Code */}
{family && (
<Grid item xs={12}>
<Card>
<CardContent>
<Typography variant="h6" fontWeight="600" gutterBottom>
Family Share Code
</Typography>
<Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
Share this code with family members to give them access to your family's data
</Typography>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 2, flexWrap: 'wrap' }}>
<Chip
label={family.shareCode}
sx={{
fontSize: '1.1rem',
fontWeight: 600,
py: 2.5,
px: 1,
}}
color="primary"
/>
<Button
variant="outlined"
startIcon={<ContentCopy />}
onClick={handleCopyCode}
>
Copy Code
</Button>
</Box>
</CardContent>
</Card>
</Grid>
)}
{/* Family Members */}
<Grid item xs={12}>
<Card>
<CardContent>
<Typography variant="h6" fontWeight="600" gutterBottom sx={{ mb: 3 }}>
Family Members ({members.length})
</Typography>
{members.length === 0 ? (
<Box sx={{ textAlign: 'center', py: 4 }}>
<People sx={{ fontSize: 48, color: 'text.secondary', mb: 2 }} />
<Typography variant="body2" color="text.secondary" gutterBottom>
No family members yet
</Typography>
<Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
Invite family members to collaborate on child care
</Typography>
<Button
variant="outlined"
startIcon={<PersonAdd />}
onClick={() => setInviteDialogOpen(true)}
>
Invite First Member
</Button>
</Box>
) : (
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
{members.map((member, index) => (
<motion.div
key={member.id}
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.2, delay: index * 0.05 }}
>
<Box>
{index > 0 && <Divider sx={{ mb: 2 }} />}
<Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
<Avatar
sx={{
bgcolor: isCurrentUser(member.userId) ? 'primary.main' : 'secondary.main',
}}
>
{member.user?.name?.charAt(0).toUpperCase() || 'U'}
</Avatar>
<Box sx={{ flex: 1 }}>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
<Typography variant="body1" fontWeight="600">
{member.user?.name || 'Unknown User'}
</Typography>
{isCurrentUser(member.userId) && (
<Chip label="You" size="small" color="success" />
)}
</Box>
<Typography variant="body2" color="text.secondary">
{member.user?.email || 'No email'}
</Typography>
</Box>
<Chip
label={member.role.charAt(0).toUpperCase() + member.role.slice(1)}
color={getRoleColor(member.role)}
size="small"
/>
{!isCurrentUser(member.userId) && (
<IconButton
size="small"
onClick={() => handleRemoveClick(member)}
color="error"
>
<Delete />
</IconButton>
)}
</Box>
</Box>
</motion.div>
))}
</Box>
)}
</CardContent>
</Card>
</Grid>
</Grid>
)}
</Box>
<InviteMemberDialog
open={inviteDialogOpen}
onClose={() => setInviteDialogOpen(false)}
onSubmit={handleInviteMember}
isLoading={actionLoading}
/>
<JoinFamilyDialog
open={joinDialogOpen}
onClose={() => setJoinDialogOpen(false)}
onSubmit={handleJoinFamily}
isLoading={actionLoading}
/>
<RemoveMemberDialog
open={removeDialogOpen}
onClose={() => setRemoveDialogOpen(false)}
onConfirm={handleRemoveConfirm}
memberName={memberToRemove?.user?.name || ''}
isLoading={actionLoading}
/>
<Snackbar
open={snackbar.open}
autoHideDuration={4000}
onClose={() => setSnackbar({ ...snackbar, open: false })}
message={snackbar.message}
/>
</AppShell>
</ProtectedRoute>
);
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

View File

@@ -0,0 +1,33 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
:root {
--foreground-rgb: 0, 0, 0;
--background-start-rgb: 214, 219, 220;
--background-end-rgb: 255, 255, 255;
}
@media (prefers-color-scheme: dark) {
:root {
--foreground-rgb: 255, 255, 255;
--background-start-rgb: 0, 0, 0;
--background-end-rgb: 0, 0, 0;
}
}
body {
color: rgb(var(--foreground-rgb));
background: linear-gradient(
to bottom,
transparent,
rgb(var(--background-end-rgb))
)
rgb(var(--background-start-rgb));
}
@layer utilities {
.text-balance {
text-wrap: balance;
}
}

View File

@@ -0,0 +1,220 @@
'use client';
import { useState } from 'react';
import {
Box,
Typography,
Paper,
List,
ListItem,
ListItemAvatar,
ListItemText,
Avatar,
Chip,
IconButton,
Tabs,
Tab,
Button,
} from '@mui/material';
import {
Restaurant,
Hotel,
BabyChangingStation,
Delete,
Edit,
FilterList,
} from '@mui/icons-material';
import { AppShell } from '@/components/layouts/AppShell/AppShell';
import { ProtectedRoute } from '@/components/common/ProtectedRoute';
import { motion } from 'framer-motion';
import { formatDistanceToNow } from 'date-fns';
// Mock data - will be replaced with API calls
const mockActivities = [
{
id: '1',
type: 'feeding',
timestamp: new Date(Date.now() - 2 * 60 * 60 * 1000),
details: 'Breast feeding - Left, 15 minutes',
icon: <Restaurant />,
color: '#FFB6C1',
},
{
id: '2',
type: 'diaper',
timestamp: new Date(Date.now() - 3 * 60 * 60 * 1000),
details: 'Diaper change - Wet',
icon: <BabyChangingStation />,
color: '#FFE4B5',
},
{
id: '3',
type: 'sleep',
timestamp: new Date(Date.now() - 5 * 60 * 60 * 1000),
details: 'Sleep - 2h 30m, Good quality',
icon: <Hotel />,
color: '#B6D7FF',
},
{
id: '4',
type: 'feeding',
timestamp: new Date(Date.now() - 6 * 60 * 60 * 1000),
details: 'Bottle - 120ml',
icon: <Restaurant />,
color: '#FFB6C1',
},
{
id: '5',
type: 'diaper',
timestamp: new Date(Date.now() - 7 * 60 * 60 * 1000),
details: 'Diaper change - Both',
icon: <BabyChangingStation />,
color: '#FFE4B5',
},
];
export default function HistoryPage() {
const [filter, setFilter] = useState<string>('all');
const [activities, setActivities] = useState(mockActivities);
const filteredActivities =
filter === 'all'
? activities
: activities.filter((activity) => activity.type === filter);
const handleDelete = (id: string) => {
// TODO: Call API to delete activity
setActivities(activities.filter((activity) => activity.id !== id));
};
return (
<ProtectedRoute>
<AppShell>
<Box>
<Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
<Typography variant="h4" fontWeight="600">
Activity History
</Typography>
<IconButton>
<FilterList />
</IconButton>
</Box>
{/* Filter Tabs */}
<Paper sx={{ mb: 3 }}>
<Tabs
value={filter}
onChange={(_, newValue) => setFilter(newValue)}
variant="scrollable"
scrollButtons="auto"
>
<Tab label="All" value="all" />
<Tab label="Feeding" value="feeding" icon={<Restaurant />} iconPosition="start" />
<Tab label="Sleep" value="sleep" icon={<Hotel />} iconPosition="start" />
<Tab label="Diaper" value="diaper" icon={<BabyChangingStation />} iconPosition="start" />
</Tabs>
</Paper>
{/* Activity Timeline */}
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 0.3 }}
>
<Paper>
<List>
{filteredActivities.length === 0 ? (
<Box sx={{ p: 4, textAlign: 'center' }}>
<Typography variant="body1" color="text.secondary">
No activities found
</Typography>
</Box>
) : (
filteredActivities.map((activity, index) => (
<motion.div
key={activity.id}
initial={{ opacity: 0, x: -20 }}
animate={{ opacity: 1, x: 0 }}
transition={{ duration: 0.3, delay: index * 0.05 }}
>
<ListItem
sx={{
borderBottom: index < filteredActivities.length - 1 ? '1px solid' : 'none',
borderColor: 'divider',
py: 2,
}}
secondaryAction={
<Box>
<IconButton edge="end" aria-label="edit" sx={{ mr: 1 }}>
<Edit />
</IconButton>
<IconButton
edge="end"
aria-label="delete"
onClick={() => handleDelete(activity.id)}
>
<Delete />
</IconButton>
</Box>
}
>
<ListItemAvatar>
<Avatar sx={{ bgcolor: activity.color }}>
{activity.icon}
</Avatar>
</ListItemAvatar>
<ListItemText
primary={activity.details}
secondary={
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mt: 0.5 }}>
<Typography variant="caption" color="text.secondary">
{formatDistanceToNow(activity.timestamp, { addSuffix: true })}
</Typography>
<Chip
label={activity.type}
size="small"
sx={{
height: 20,
fontSize: '0.7rem',
textTransform: 'capitalize',
}}
/>
</Box>
}
/>
</ListItem>
</motion.div>
))
)}
</List>
</Paper>
</motion.div>
{/* Daily Summary */}
<Paper sx={{ p: 3, mt: 3 }}>
<Typography variant="h6" fontWeight="600" gutterBottom>
Today's Summary
</Typography>
<Box sx={{ display: 'flex', gap: 2, flexWrap: 'wrap', mt: 2 }}>
<Chip
icon={<Restaurant />}
label={`${activities.filter((a) => a.type === 'feeding').length} Feedings`}
sx={{ bgcolor: '#FFB6C1', color: 'white' }}
/>
<Chip
icon={<Hotel />}
label={`${activities.filter((a) => a.type === 'sleep').length} Sleep Sessions`}
sx={{ bgcolor: '#B6D7FF', color: 'white' }}
/>
<Chip
icon={<BabyChangingStation />}
label={`${activities.filter((a) => a.type === 'diaper').length} Diaper Changes`}
sx={{ bgcolor: '#FFE4B5', color: 'white' }}
/>
</Box>
</Paper>
</Box>
</AppShell>
</ProtectedRoute>
);
}

View File

@@ -0,0 +1,25 @@
'use client';
import { lazy, Suspense } from 'react';
import { AppShell } from '@/components/layouts/AppShell/AppShell';
import { ProtectedRoute } from '@/components/common/ProtectedRoute';
import { LoadingFallback } from '@/components/common/LoadingFallback';
// Lazy load the insights dashboard component
const InsightsDashboard = lazy(() =>
import('@/components/features/analytics/InsightsDashboard').then((mod) => ({
default: mod.InsightsDashboard,
}))
);
export default function InsightsPage() {
return (
<ProtectedRoute>
<AppShell>
<Suspense fallback={<LoadingFallback variant="page" />}>
<InsightsDashboard />
</Suspense>
</AppShell>
</ProtectedRoute>
);
}

View File

@@ -0,0 +1,47 @@
import type { Metadata } from 'next';
import { Inter } from 'next/font/google';
import { ThemeRegistry } from '@/components/ThemeRegistry';
// import { PerformanceMonitor } from '@/components/common/PerformanceMonitor'; // Temporarily disabled
import './globals.css';
const inter = Inter({ subsets: ['latin'] });
export const metadata: Metadata = {
title: 'Maternal - AI-Powered Child Care Assistant',
description: 'Track, analyze, and get AI-powered insights for your child\'s development, sleep, feeding, and more.',
manifest: '/manifest.json',
themeColor: '#FFB6C1',
viewport: {
width: 'device-width',
initialScale: 1,
maximumScale: 1,
userScalable: false,
},
appleWebApp: {
capable: true,
statusBarStyle: 'default',
title: 'Maternal',
},
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en">
<head>
<link rel="manifest" href="/manifest.json" />
<meta name="theme-color" content="#FFB6C1" />
<link rel="apple-touch-icon" href="/icon-192x192.png" />
</head>
<body className={inter.className}>
<ThemeRegistry>
{/* <PerformanceMonitor /> */}
{children}
</ThemeRegistry>
</body>
</html>
);
}

View File

@@ -0,0 +1,34 @@
'use client';
import { useEffect } from 'react';
import { useAuth } from '@/lib/auth/AuthContext';
import { Box, CircularProgress, Typography } from '@mui/material';
export default function LogoutPage() {
const { logout } = useAuth();
useEffect(() => {
const performLogout = async () => {
await logout();
};
performLogout();
}, [logout]);
return (
<Box
sx={{
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
minHeight: '100vh',
gap: 2,
}}
>
<CircularProgress />
<Typography variant="body1" color="text.secondary">
Logging out...
</Typography>
</Box>
);
}

212
maternal-web/app/page.tsx Normal file
View File

@@ -0,0 +1,212 @@
'use client';
import { useState, useEffect } from 'react';
import { Box, Typography, Button, Paper, Grid, CircularProgress } from '@mui/material';
import { AppShell } from '@/components/layouts/AppShell/AppShell';
import { ProtectedRoute } from '@/components/common/ProtectedRoute';
import {
Restaurant,
Hotel,
BabyChangingStation,
Insights,
SmartToy,
Analytics,
} from '@mui/icons-material';
import { motion } from 'framer-motion';
import { useAuth } from '@/lib/auth/AuthContext';
import { useRouter } from 'next/navigation';
import { trackingApi, DailySummary } from '@/lib/api/tracking';
import { childrenApi, Child } from '@/lib/api/children';
import { format } from 'date-fns';
export default function HomePage() {
const { user } = useAuth();
const router = useRouter();
const [children, setChildren] = useState<Child[]>([]);
const [selectedChild, setSelectedChild] = useState<Child | null>(null);
const [dailySummary, setDailySummary] = useState<DailySummary | null>(null);
const [loading, setLoading] = useState(true);
const familyId = user?.families?.[0]?.familyId;
// Load children and daily summary
useEffect(() => {
const loadData = async () => {
if (!familyId) {
setLoading(false);
return;
}
try {
// Load children
const childrenData = await childrenApi.getChildren(familyId);
setChildren(childrenData);
if (childrenData.length > 0) {
const firstChild = childrenData[0];
setSelectedChild(firstChild);
// Load today's summary for first child
const today = format(new Date(), 'yyyy-MM-dd');
const summary = await trackingApi.getDailySummary(firstChild.id, today);
setDailySummary(summary);
}
} catch (error) {
console.error('Failed to load data:', error);
} finally {
setLoading(false);
}
};
loadData();
}, [familyId]);
const quickActions = [
{ icon: <Restaurant />, label: 'Feeding', color: '#FFB6C1', path: '/track/feeding' },
{ icon: <Hotel />, label: 'Sleep', color: '#B6D7FF', path: '/track/sleep' },
{ icon: <BabyChangingStation />, label: 'Diaper', color: '#FFE4B5', path: '/track/diaper' },
{ icon: <SmartToy />, label: 'AI Assistant', color: '#FFD3B6', path: '/ai-assistant' },
{ icon: <Analytics />, label: 'Analytics', color: '#D4B5FF', path: '/analytics' },
];
const formatSleepHours = (minutes: number) => {
const hours = Math.floor(minutes / 60);
const mins = minutes % 60;
if (hours > 0 && mins > 0) {
return `${hours}h ${mins}m`;
} else if (hours > 0) {
return `${hours}h`;
} else {
return `${mins}m`;
}
};
return (
<ProtectedRoute>
<AppShell>
<Box>
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.5 }}
>
<Typography variant="h4" gutterBottom fontWeight="600" sx={{ mb: 1 }}>
Welcome Back{user?.name ? `, ${user.name}` : ''}! 👋
</Typography>
<Typography variant="body1" color="text.secondary" sx={{ mb: 4 }}>
Track your child's activities and get AI-powered insights
</Typography>
{/* Quick Actions */}
<Typography variant="h6" gutterBottom fontWeight="600" sx={{ mb: 2 }}>
Quick Actions
</Typography>
<Grid container spacing={2} sx={{ mb: 4 }}>
{quickActions.map((action, index) => (
<Grid item xs={6} sm={2.4} key={action.label}>
<motion.div
initial={{ opacity: 0, scale: 0.9 }}
animate={{ opacity: 1, scale: 1 }}
transition={{ duration: 0.3, delay: index * 0.1 }}
>
<Paper
onClick={() => router.push(action.path)}
sx={{
p: 3,
textAlign: 'center',
cursor: 'pointer',
bgcolor: action.color,
color: 'white',
transition: 'transform 0.2s',
'&:hover': {
transform: 'scale(1.05)',
},
}}
>
<Box sx={{ fontSize: 48, mb: 1 }}>{action.icon}</Box>
<Typography variant="body1" fontWeight="600">
{action.label}
</Typography>
</Paper>
</motion.div>
</Grid>
))}
</Grid>
{/* Today's Summary */}
<Typography variant="h6" gutterBottom fontWeight="600" sx={{ mb: 2 }}>
Today's Summary{selectedChild ? ` - ${selectedChild.name}` : ''}
</Typography>
<Paper sx={{ p: 3 }}>
{loading ? (
<Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}>
<CircularProgress />
</Box>
) : !dailySummary ? (
<Box sx={{ textAlign: 'center', py: 4 }}>
<Typography variant="body2" color="text.secondary">
{children.length === 0
? 'Add a child to start tracking'
: 'No activities tracked today'}
</Typography>
</Box>
) : (
<Grid container spacing={3}>
<Grid item xs={4}>
<Box textAlign="center">
<Restaurant sx={{ fontSize: 32, color: 'primary.main', mb: 1 }} />
<Typography variant="h5" fontWeight="600">
{dailySummary.feedingCount || 0}
</Typography>
<Typography variant="body2" color="text.secondary">
Feedings
</Typography>
</Box>
</Grid>
<Grid item xs={4}>
<Box textAlign="center">
<Hotel sx={{ fontSize: 32, color: 'info.main', mb: 1 }} />
<Typography variant="h5" fontWeight="600">
{dailySummary.sleepTotalMinutes
? formatSleepHours(dailySummary.sleepTotalMinutes)
: '0m'}
</Typography>
<Typography variant="body2" color="text.secondary">
Sleep
</Typography>
</Box>
</Grid>
<Grid item xs={4}>
<Box textAlign="center">
<BabyChangingStation sx={{ fontSize: 32, color: 'warning.main', mb: 1 }} />
<Typography variant="h5" fontWeight="600">
{dailySummary.diaperCount || 0}
</Typography>
<Typography variant="body2" color="text.secondary">
Diapers
</Typography>
</Box>
</Grid>
</Grid>
)}
</Paper>
{/* Next Predicted Activity */}
<Box sx={{ mt: 4 }}>
<Paper sx={{ p: 3, bgcolor: 'primary.light' }}>
<Typography variant="body2" color="text.secondary" gutterBottom>
Next Predicted Activity
</Typography>
<Typography variant="h6" fontWeight="600" gutterBottom>
Nap time in 45 minutes
</Typography>
<Typography variant="body2" color="text.secondary">
Based on your child's sleep patterns
</Typography>
</Paper>
</Box>
</motion.div>
</Box>
</AppShell>
</ProtectedRoute>
);
}

View File

@@ -0,0 +1,260 @@
'use client';
import { Box, Typography, Card, CardContent, TextField, Button, Divider, Switch, FormControlLabel, Alert, CircularProgress, Snackbar } from '@mui/material';
import { Save, Logout } from '@mui/icons-material';
import { useAuth } from '@/lib/auth/AuthContext';
import { useState, useEffect } from 'react';
import { AppShell } from '@/components/layouts/AppShell/AppShell';
import { ProtectedRoute } from '@/components/common/ProtectedRoute';
import { usersApi } from '@/lib/api/users';
import { motion } from 'framer-motion';
export default function SettingsPage() {
const { user, logout, refreshUser } = useAuth();
const [name, setName] = useState(user?.name || '');
const [settings, setSettings] = useState({
notifications: true,
emailUpdates: false,
darkMode: false,
});
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [successMessage, setSuccessMessage] = useState<string | null>(null);
const [nameError, setNameError] = useState<string | null>(null);
// Load preferences from user object when it changes
useEffect(() => {
if (user?.preferences) {
setSettings({
notifications: user.preferences.notifications ?? true,
emailUpdates: user.preferences.emailUpdates ?? false,
darkMode: user.preferences.darkMode ?? false,
});
}
}, [user?.preferences]);
// Sync name state when user data changes
useEffect(() => {
if (user?.name) {
setName(user.name);
}
}, [user]);
const handleSave = async () => {
// Validate name
if (!name || name.trim() === '') {
setNameError('Name cannot be empty');
return;
}
setIsLoading(true);
setError(null);
setNameError(null);
try {
const response = await usersApi.updateProfile({
name: name.trim(),
preferences: settings
});
console.log('✅ Profile updated successfully:', response);
// Refresh user to get latest data from server
await refreshUser();
setSuccessMessage('Profile updated successfully!');
} catch (err: any) {
console.error('❌ Failed to update profile:', err);
console.error('Error response:', err.response);
setError(err.response?.data?.message || err.message || 'Failed to update profile. Please try again.');
} finally {
setIsLoading(false);
}
};
const handleLogout = async () => {
await logout();
};
return (
<ProtectedRoute>
<AppShell>
<Box sx={{ maxWidth: 'md', mx: 'auto' }}>
<Typography variant="h4" fontWeight="600" gutterBottom>
Settings
</Typography>
<Typography variant="body1" color="text.secondary" sx={{ mb: 4 }}>
Manage your account settings and preferences
</Typography>
{/* Error Alert */}
{error && (
<motion.div
initial={{ opacity: 0, y: -10 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.3 }}
>
<Alert severity="error" sx={{ mb: 3 }} onClose={() => setError(null)}>
{error}
</Alert>
</motion.div>
)}
{/* Profile Settings */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.4 }}
>
<Card sx={{ mb: 3 }}>
<CardContent>
<Typography variant="h6" fontWeight="600" gutterBottom>
Profile Information
</Typography>
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 2, mt: 2 }}>
<TextField
label="Name"
value={name}
onChange={(e) => {
setName(e.target.value);
if (nameError) setNameError(null);
}}
fullWidth
error={!!nameError}
helperText={nameError}
disabled={isLoading}
/>
<TextField
label="Email"
value={user?.email || ''}
fullWidth
disabled
helperText="Email cannot be changed"
/>
<Button
variant="contained"
startIcon={isLoading ? <CircularProgress size={20} color="inherit" /> : <Save />}
onClick={handleSave}
disabled={isLoading}
sx={{ alignSelf: 'flex-start' }}
>
{isLoading ? 'Saving...' : 'Save Changes'}
</Button>
</Box>
</CardContent>
</Card>
</motion.div>
{/* Notification Settings */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.4, delay: 0.1 }}
>
<Card sx={{ mb: 3 }}>
<CardContent>
<Typography variant="h6" fontWeight="600" gutterBottom>
Notifications
</Typography>
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 1, mt: 2 }}>
<FormControlLabel
control={
<Switch
checked={settings.notifications}
onChange={(e) => setSettings({ ...settings, notifications: e.target.checked })}
disabled={isLoading}
/>
}
label="Push Notifications"
/>
<FormControlLabel
control={
<Switch
checked={settings.emailUpdates}
onChange={(e) => setSettings({ ...settings, emailUpdates: e.target.checked })}
disabled={isLoading}
/>
}
label="Email Updates"
/>
</Box>
<Button
variant="contained"
startIcon={isLoading ? <CircularProgress size={20} color="inherit" /> : <Save />}
onClick={handleSave}
disabled={isLoading}
sx={{ mt: 2, alignSelf: 'flex-start' }}
>
{isLoading ? 'Saving...' : 'Save Preferences'}
</Button>
</CardContent>
</Card>
</motion.div>
{/* Appearance Settings */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.4, delay: 0.2 }}
>
<Card sx={{ mb: 3 }}>
<CardContent>
<Typography variant="h6" fontWeight="600" gutterBottom>
Appearance
</Typography>
<Box sx={{ mt: 2 }}>
<FormControlLabel
control={
<Switch
checked={settings.darkMode}
onChange={(e) => setSettings({ ...settings, darkMode: e.target.checked })}
/>
}
label="Dark Mode (Coming Soon)"
disabled
/>
</Box>
</CardContent>
</Card>
</motion.div>
{/* Account Actions */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.4, delay: 0.3 }}
>
<Card>
<CardContent>
<Typography variant="h6" fontWeight="600" gutterBottom>
Account Actions
</Typography>
<Divider sx={{ my: 2 }} />
<Button
variant="outlined"
color="error"
startIcon={<Logout />}
onClick={handleLogout}
fullWidth
>
Logout
</Button>
</CardContent>
</Card>
</motion.div>
{/* Success Snackbar */}
<Snackbar
open={!!successMessage}
autoHideDuration={4000}
onClose={() => setSuccessMessage(null)}
anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
>
<Alert onClose={() => setSuccessMessage(null)} severity="success" sx={{ width: '100%' }}>
{successMessage}
</Alert>
</Snackbar>
</Box>
</AppShell>
</ProtectedRoute>
);
}

View File

@@ -0,0 +1,663 @@
'use client';
import { useState, useEffect } from 'react';
import {
Box,
Typography,
Button,
Paper,
TextField,
FormControl,
InputLabel,
Select,
MenuItem,
IconButton,
Alert,
CircularProgress,
Card,
CardContent,
Dialog,
DialogTitle,
DialogContent,
DialogContentText,
DialogActions,
Chip,
Snackbar,
ToggleButtonGroup,
ToggleButton,
FormLabel,
} from '@mui/material';
import {
ArrowBack,
Refresh,
Save,
Delete,
BabyChangingStation,
Warning,
CheckCircle,
ChildCare,
Add,
} from '@mui/icons-material';
import { useRouter } from 'next/navigation';
import { AppShell } from '@/components/layouts/AppShell/AppShell';
import { ProtectedRoute } from '@/components/common/ProtectedRoute';
import { useAuth } from '@/lib/auth/AuthContext';
import { trackingApi, Activity } from '@/lib/api/tracking';
import { childrenApi, Child } from '@/lib/api/children';
import { motion } from 'framer-motion';
import { formatDistanceToNow, format } from 'date-fns';
interface DiaperData {
diaperType: 'wet' | 'dirty' | 'both' | 'dry';
conditions: string[];
hasRash: boolean;
rashSeverity?: 'mild' | 'moderate' | 'severe';
}
export default function DiaperTrackPage() {
const router = useRouter();
const { user } = useAuth();
const [children, setChildren] = useState<Child[]>([]);
const [selectedChild, setSelectedChild] = useState<string>('');
// Diaper state
const [timestamp, setTimestamp] = useState<string>(
format(new Date(), "yyyy-MM-dd'T'HH:mm")
);
const [diaperType, setDiaperType] = useState<'wet' | 'dirty' | 'both' | 'dry'>('wet');
const [conditions, setConditions] = useState<string[]>(['normal']);
const [hasRash, setHasRash] = useState<boolean>(false);
const [rashSeverity, setRashSeverity] = useState<'mild' | 'moderate' | 'severe'>('mild');
// Common state
const [notes, setNotes] = useState<string>('');
const [recentDiapers, setRecentDiapers] = useState<Activity[]>([]);
const [loading, setLoading] = useState(false);
const [childrenLoading, setChildrenLoading] = useState(true);
const [diapersLoading, setDiapersLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [successMessage, setSuccessMessage] = useState<string | null>(null);
// Delete confirmation dialog
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
const [activityToDelete, setActivityToDelete] = useState<string | null>(null);
const familyId = user?.families?.[0]?.familyId;
const availableConditions = [
'normal',
'soft',
'hard',
'watery',
'mucus',
'blood',
];
// Load children
useEffect(() => {
if (familyId) {
loadChildren();
}
}, [familyId]);
// Load recent diapers when child is selected
useEffect(() => {
if (selectedChild) {
loadRecentDiapers();
}
}, [selectedChild]);
const loadChildren = async () => {
if (!familyId) return;
try {
setChildrenLoading(true);
const childrenData = await childrenApi.getChildren(familyId);
setChildren(childrenData);
if (childrenData.length > 0) {
setSelectedChild(childrenData[0].id);
}
} catch (err: any) {
console.error('Failed to load children:', err);
setError(err.response?.data?.message || 'Failed to load children');
} finally {
setChildrenLoading(false);
}
};
const loadRecentDiapers = async () => {
if (!selectedChild) return;
try {
setDiapersLoading(true);
const activities = await trackingApi.getActivities(selectedChild, 'diaper');
// Sort by timestamp descending and take last 10
const sorted = activities.sort((a, b) =>
new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime()
).slice(0, 10);
setRecentDiapers(sorted);
} catch (err: any) {
console.error('Failed to load recent diapers:', err);
} finally {
setDiapersLoading(false);
}
};
const setTimeNow = () => {
setTimestamp(format(new Date(), "yyyy-MM-dd'T'HH:mm"));
};
const handleConditionToggle = (condition: string) => {
setConditions((prev) => {
if (prev.includes(condition)) {
// Remove condition, but ensure at least one remains
if (prev.length === 1) return prev;
return prev.filter((c) => c !== condition);
} else {
return [...prev, condition];
}
});
};
const handleSubmit = async () => {
if (!selectedChild) {
setError('Please select a child');
return;
}
// Validation
if (!timestamp) {
setError('Please enter timestamp');
return;
}
if (conditions.length === 0) {
setError('Please select at least one condition');
return;
}
try {
setLoading(true);
setError(null);
const data: DiaperData = {
diaperType,
conditions,
hasRash,
};
if (hasRash) {
data.rashSeverity = rashSeverity;
}
await trackingApi.createActivity(selectedChild, {
type: 'diaper',
timestamp,
data,
notes: notes || undefined,
});
setSuccessMessage('Diaper change logged successfully!');
// Reset form
resetForm();
// Reload recent diapers
await loadRecentDiapers();
} catch (err: any) {
console.error('Failed to save diaper:', err);
setError(err.response?.data?.message || 'Failed to save diaper change');
} finally {
setLoading(false);
}
};
const resetForm = () => {
setTimestamp(format(new Date(), "yyyy-MM-dd'T'HH:mm"));
setDiaperType('wet');
setConditions(['normal']);
setHasRash(false);
setRashSeverity('mild');
setNotes('');
};
const handleDeleteClick = (activityId: string) => {
setActivityToDelete(activityId);
setDeleteDialogOpen(true);
};
const handleDeleteConfirm = async () => {
if (!activityToDelete) return;
try {
setLoading(true);
await trackingApi.deleteActivity(activityToDelete);
setSuccessMessage('Diaper change deleted successfully');
setDeleteDialogOpen(false);
setActivityToDelete(null);
await loadRecentDiapers();
} catch (err: any) {
console.error('Failed to delete diaper:', err);
setError(err.response?.data?.message || 'Failed to delete diaper change');
} finally {
setLoading(false);
}
};
const getDiaperTypeColor = (type: string) => {
switch (type) {
case 'wet':
return '#2196f3'; // blue
case 'dirty':
return '#795548'; // brown
case 'both':
return '#ff9800'; // orange
case 'dry':
return '#4caf50'; // green
default:
return '#757575'; // grey
}
};
const getDiaperTypeIcon = (type: string) => {
switch (type) {
case 'wet':
return '💧';
case 'dirty':
return '💩';
case 'both':
return '💧💩';
case 'dry':
return '✨';
default:
return '🍼';
}
};
const getDiaperDetails = (activity: Activity) => {
const data = activity.data as DiaperData;
const typeLabel = data.diaperType.charAt(0).toUpperCase() + data.diaperType.slice(1);
const conditionsLabel = data.conditions.join(', ');
let details = `${typeLabel} - ${conditionsLabel}`;
if (data.hasRash) {
details += ` - Rash (${data.rashSeverity})`;
}
return details;
};
const getRashSeverityColor = (severity: string) => {
switch (severity) {
case 'mild':
return 'warning';
case 'moderate':
return 'error';
case 'severe':
return 'error';
default:
return 'default';
}
};
if (childrenLoading) {
return (
<ProtectedRoute>
<AppShell>
<Box sx={{ display: 'flex', justifyContent: 'center', py: 8 }}>
<CircularProgress />
</Box>
</AppShell>
</ProtectedRoute>
);
}
if (!familyId || children.length === 0) {
return (
<ProtectedRoute>
<AppShell>
<Card>
<CardContent sx={{ textAlign: 'center', py: 8 }}>
<ChildCare sx={{ fontSize: 64, color: 'text.secondary', mb: 2 }} />
<Typography variant="h6" color="text.secondary" gutterBottom>
No Children Added
</Typography>
<Typography variant="body2" color="text.secondary" sx={{ mb: 3 }}>
You need to add a child before you can track diaper changes
</Typography>
<Button
variant="contained"
startIcon={<Add />}
onClick={() => router.push('/children')}
>
Add Child
</Button>
</CardContent>
</Card>
</AppShell>
</ProtectedRoute>
);
}
return (
<ProtectedRoute>
<AppShell>
<Box>
<Box sx={{ display: 'flex', alignItems: 'center', mb: 3 }}>
<IconButton onClick={() => router.back()} sx={{ mr: 2 }}>
<ArrowBack />
</IconButton>
<Typography variant="h4" fontWeight="600">
Track Diaper Change
</Typography>
</Box>
{error && (
<Alert severity="error" sx={{ mb: 3 }} onClose={() => setError(null)}>
{error}
</Alert>
)}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.3 }}
>
{/* Child Selector */}
{children.length > 1 && (
<Paper sx={{ p: 2, mb: 3 }}>
<FormControl fullWidth>
<InputLabel>Select Child</InputLabel>
<Select
value={selectedChild}
onChange={(e) => setSelectedChild(e.target.value)}
label="Select Child"
>
{children.map((child) => (
<MenuItem key={child.id} value={child.id}>
{child.name}
</MenuItem>
))}
</Select>
</FormControl>
</Paper>
)}
{/* Main Form */}
<Paper sx={{ p: 3, mb: 3 }}>
{/* Icon Header */}
<Box sx={{ display: 'flex', justifyContent: 'center', mb: 3 }}>
<BabyChangingStation sx={{ fontSize: 64, color: 'primary.main' }} />
</Box>
{/* Timestamp */}
<Box sx={{ mb: 3 }}>
<Typography variant="subtitle1" fontWeight="600" sx={{ mb: 1 }}>
Time
</Typography>
<Box sx={{ display: 'flex', gap: 2, alignItems: 'flex-start' }}>
<TextField
fullWidth
type="datetime-local"
value={timestamp}
onChange={(e) => setTimestamp(e.target.value)}
InputLabelProps={{ shrink: true }}
/>
<Button variant="outlined" onClick={setTimeNow} sx={{ minWidth: 100 }}>
Now
</Button>
</Box>
</Box>
{/* Diaper Type */}
<Box sx={{ mb: 3 }}>
<Typography variant="subtitle1" fontWeight="600" sx={{ mb: 2 }}>
Diaper Type
</Typography>
<ToggleButtonGroup
value={diaperType}
exclusive
onChange={(_, value) => {
if (value !== null) {
setDiaperType(value);
}
}}
fullWidth
>
<ToggleButton value="wet" sx={{ py: 2 }}>
<Box sx={{ textAlign: 'center' }}>
<Typography variant="h5">💧</Typography>
<Typography variant="body2">Wet</Typography>
</Box>
</ToggleButton>
<ToggleButton value="dirty" sx={{ py: 2 }}>
<Box sx={{ textAlign: 'center' }}>
<Typography variant="h5">💩</Typography>
<Typography variant="body2">Dirty</Typography>
</Box>
</ToggleButton>
<ToggleButton value="both" sx={{ py: 2 }}>
<Box sx={{ textAlign: 'center' }}>
<Typography variant="h5">💧💩</Typography>
<Typography variant="body2">Both</Typography>
</Box>
</ToggleButton>
<ToggleButton value="dry" sx={{ py: 2 }}>
<Box sx={{ textAlign: 'center' }}>
<Typography variant="h5"></Typography>
<Typography variant="body2">Dry</Typography>
</Box>
</ToggleButton>
</ToggleButtonGroup>
</Box>
{/* Condition Selector */}
<Box sx={{ mb: 3 }}>
<Typography variant="subtitle1" fontWeight="600" sx={{ mb: 1 }}>
Condition (select all that apply)
</Typography>
<Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 1 }}>
{availableConditions.map((condition) => (
<Chip
key={condition}
label={condition.charAt(0).toUpperCase() + condition.slice(1)}
onClick={() => handleConditionToggle(condition)}
color={conditions.includes(condition) ? 'primary' : 'default'}
variant={conditions.includes(condition) ? 'filled' : 'outlined'}
sx={{ cursor: 'pointer' }}
/>
))}
</Box>
</Box>
{/* Rash Indicator */}
<FormControl fullWidth sx={{ mb: 3 }}>
<InputLabel>Diaper Rash?</InputLabel>
<Select
value={hasRash ? 'yes' : 'no'}
onChange={(e) => setHasRash(e.target.value === 'yes')}
label="Diaper Rash?"
>
<MenuItem value="no">No</MenuItem>
<MenuItem value="yes">Yes</MenuItem>
</Select>
</FormControl>
{/* Rash Severity */}
{hasRash && (
<Box sx={{ mb: 3 }}>
<Alert severity="warning" sx={{ mb: 2 }}>
<Typography variant="body2" sx={{ mb: 1 }}>
Diaper rash detected. Consider applying diaper rash cream and consulting your pediatrician if it persists.
</Typography>
</Alert>
<FormControl fullWidth>
<InputLabel>Rash Severity</InputLabel>
<Select
value={rashSeverity}
onChange={(e) => setRashSeverity(e.target.value as 'mild' | 'moderate' | 'severe')}
label="Rash Severity"
>
<MenuItem value="mild">Mild</MenuItem>
<MenuItem value="moderate">Moderate</MenuItem>
<MenuItem value="severe">Severe</MenuItem>
</Select>
</FormControl>
</Box>
)}
{/* Notes Field */}
<TextField
fullWidth
label="Notes (optional)"
multiline
rows={3}
value={notes}
onChange={(e) => setNotes(e.target.value)}
sx={{ mb: 3 }}
placeholder="Color, consistency, or any concerns..."
/>
{/* Submit Button */}
<Button
fullWidth
type="button"
variant="contained"
size="large"
startIcon={<Save />}
onClick={handleSubmit}
disabled={loading}
>
{loading ? 'Saving...' : 'Save Diaper Change'}
</Button>
</Paper>
{/* Recent Diapers */}
<Paper sx={{ p: 3 }}>
<Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
<Typography variant="h6" fontWeight="600">
Recent Diaper Changes
</Typography>
<IconButton onClick={loadRecentDiapers} disabled={diapersLoading}>
<Refresh />
</IconButton>
</Box>
{diapersLoading ? (
<Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}>
<CircularProgress size={30} />
</Box>
) : recentDiapers.length === 0 ? (
<Box sx={{ textAlign: 'center', py: 4 }}>
<Typography variant="body2" color="text.secondary">
No diaper changes yet
</Typography>
</Box>
) : (
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
{recentDiapers.map((activity, index) => {
const data = activity.data as DiaperData;
return (
<motion.div
key={activity.id}
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.2, delay: index * 0.05 }}
>
<Card variant="outlined">
<CardContent>
<Box sx={{ display: 'flex', alignItems: 'flex-start', gap: 2 }}>
<Box sx={{ mt: 0.5, fontSize: '2rem' }}>
{getDiaperTypeIcon(data.diaperType)}
</Box>
<Box sx={{ flex: 1 }}>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 0.5, flexWrap: 'wrap' }}>
<Typography variant="body1" fontWeight="600">
Diaper Change
</Typography>
<Chip
label={data.diaperType.charAt(0).toUpperCase() + data.diaperType.slice(1)}
size="small"
sx={{
bgcolor: getDiaperTypeColor(data.diaperType),
color: 'white'
}}
/>
{data.hasRash && (
<Chip
icon={<Warning sx={{ fontSize: 16 }} />}
label={`Rash: ${data.rashSeverity}`}
size="small"
color={getRashSeverityColor(data.rashSeverity || 'mild') as any}
/>
)}
<Chip
label={formatDistanceToNow(new Date(activity.timestamp), { addSuffix: true })}
size="small"
variant="outlined"
/>
</Box>
<Typography variant="body2" color="text.secondary" sx={{ mb: 1 }}>
{getDiaperDetails(activity)}
</Typography>
{activity.notes && (
<Typography variant="body2" color="text.secondary" sx={{ fontStyle: 'italic' }}>
{activity.notes}
</Typography>
)}
</Box>
<Box sx={{ display: 'flex', gap: 0.5 }}>
<IconButton
size="small"
color="error"
onClick={() => handleDeleteClick(activity.id)}
disabled={loading}
>
<Delete />
</IconButton>
</Box>
</Box>
</CardContent>
</Card>
</motion.div>
);
})}
</Box>
)}
</Paper>
</motion.div>
</Box>
{/* Delete Confirmation Dialog */}
<Dialog
open={deleteDialogOpen}
onClose={() => setDeleteDialogOpen(false)}
>
<DialogTitle>Delete Diaper Change?</DialogTitle>
<DialogContent>
<DialogContentText>
Are you sure you want to delete this diaper change? This action cannot be undone.
</DialogContentText>
</DialogContent>
<DialogActions>
<Button onClick={() => setDeleteDialogOpen(false)} disabled={loading}>
Cancel
</Button>
<Button onClick={handleDeleteConfirm} color="error" disabled={loading}>
{loading ? 'Deleting...' : 'Delete'}
</Button>
</DialogActions>
</Dialog>
{/* Success Snackbar */}
<Snackbar
open={!!successMessage}
autoHideDuration={3000}
onClose={() => setSuccessMessage(null)}
message={successMessage}
/>
</AppShell>
</ProtectedRoute>
);
}

View File

@@ -0,0 +1,656 @@
'use client';
import { useState, useEffect } from 'react';
import {
Box,
Typography,
Button,
Paper,
TextField,
FormControl,
InputLabel,
Select,
MenuItem,
IconButton,
Alert,
Tabs,
Tab,
CircularProgress,
Card,
CardContent,
Divider,
Dialog,
DialogTitle,
DialogContent,
DialogContentText,
DialogActions,
Chip,
Snackbar,
} from '@mui/material';
import {
ArrowBack,
PlayArrow,
Stop,
Refresh,
Save,
Restaurant,
LocalCafe,
Fastfood,
Delete,
Edit,
ChildCare,
Add,
} from '@mui/icons-material';
import { useRouter } from 'next/navigation';
import { AppShell } from '@/components/layouts/AppShell/AppShell';
import { ProtectedRoute } from '@/components/common/ProtectedRoute';
import { useAuth } from '@/lib/auth/AuthContext';
import { trackingApi, Activity } from '@/lib/api/tracking';
import { childrenApi, Child } from '@/lib/api/children';
import { motion } from 'framer-motion';
import { formatDistanceToNow } from 'date-fns';
interface FeedingData {
feedingType: 'breast' | 'bottle' | 'solid';
side?: 'left' | 'right' | 'both';
duration?: number;
amount?: number;
bottleType?: 'formula' | 'breastmilk' | 'other';
foodDescription?: string;
amountDescription?: string;
}
export default function FeedingTrackPage() {
const router = useRouter();
const { user } = useAuth();
const [children, setChildren] = useState<Child[]>([]);
const [selectedChild, setSelectedChild] = useState<string>('');
const [feedingType, setFeedingType] = useState<'breast' | 'bottle' | 'solid'>('breast');
// Breastfeeding state
const [side, setSide] = useState<'left' | 'right' | 'both'>('left');
const [duration, setDuration] = useState<number>(0);
const [isTimerRunning, setIsTimerRunning] = useState(false);
const [timerSeconds, setTimerSeconds] = useState(0);
// Bottle feeding state
const [amount, setAmount] = useState<string>('');
const [bottleType, setBottleType] = useState<'formula' | 'breastmilk' | 'other'>('formula');
// Solid food state
const [foodDescription, setFoodDescription] = useState<string>('');
const [amountDescription, setAmountDescription] = useState<string>('');
// Common state
const [notes, setNotes] = useState<string>('');
const [recentFeedings, setRecentFeedings] = useState<Activity[]>([]);
const [loading, setLoading] = useState(false);
const [childrenLoading, setChildrenLoading] = useState(true);
const [feedingsLoading, setFeedingsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [successMessage, setSuccessMessage] = useState<string | null>(null);
// Delete confirmation dialog
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
const [activityToDelete, setActivityToDelete] = useState<string | null>(null);
const familyId = user?.families?.[0]?.familyId;
// Load children
useEffect(() => {
if (familyId) {
loadChildren();
}
}, [familyId]);
// Load recent feedings when child is selected
useEffect(() => {
if (selectedChild) {
loadRecentFeedings();
}
}, [selectedChild]);
// Timer effect
useEffect(() => {
let interval: NodeJS.Timeout;
if (isTimerRunning) {
interval = setInterval(() => {
setTimerSeconds((prev) => prev + 1);
}, 1000);
}
return () => clearInterval(interval);
}, [isTimerRunning]);
const loadChildren = async () => {
if (!familyId) return;
try {
setChildrenLoading(true);
const childrenData = await childrenApi.getChildren(familyId);
setChildren(childrenData);
if (childrenData.length > 0) {
setSelectedChild(childrenData[0].id);
}
} catch (err: any) {
console.error('Failed to load children:', err);
setError(err.response?.data?.message || 'Failed to load children');
} finally {
setChildrenLoading(false);
}
};
const loadRecentFeedings = async () => {
if (!selectedChild) return;
try {
setFeedingsLoading(true);
const activities = await trackingApi.getActivities(selectedChild, 'feeding');
// Sort by timestamp descending and take last 10
const sorted = activities.sort((a, b) =>
new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime()
).slice(0, 10);
setRecentFeedings(sorted);
} catch (err: any) {
console.error('Failed to load recent feedings:', err);
} finally {
setFeedingsLoading(false);
}
};
const formatDuration = (seconds: number) => {
const mins = Math.floor(seconds / 60);
const secs = seconds % 60;
return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
};
const startTimer = () => {
setIsTimerRunning(true);
};
const stopTimer = () => {
setIsTimerRunning(false);
setDuration(Math.floor(timerSeconds / 60));
};
const resetTimer = () => {
setIsTimerRunning(false);
setTimerSeconds(0);
setDuration(0);
};
const handleSubmit = async () => {
if (!selectedChild) {
setError('Please select a child');
return;
}
// Validation
if (feedingType === 'breast' && duration === 0 && timerSeconds === 0) {
setError('Please enter duration or use the timer');
return;
}
if (feedingType === 'bottle' && !amount) {
setError('Please enter amount');
return;
}
if (feedingType === 'solid' && !foodDescription) {
setError('Please enter food description');
return;
}
try {
setLoading(true);
setError(null);
const data: FeedingData = {
feedingType,
};
if (feedingType === 'breast') {
data.side = side;
data.duration = duration || Math.floor(timerSeconds / 60);
} else if (feedingType === 'bottle') {
data.amount = parseFloat(amount);
data.bottleType = bottleType;
} else if (feedingType === 'solid') {
data.foodDescription = foodDescription;
data.amountDescription = amountDescription;
}
await trackingApi.createActivity(selectedChild, {
type: 'feeding',
timestamp: new Date().toISOString(),
data,
notes: notes || undefined,
});
setSuccessMessage('Feeding logged successfully!');
// Reset form
resetForm();
// Reload recent feedings
await loadRecentFeedings();
} catch (err: any) {
console.error('Failed to save feeding:', err);
setError(err.response?.data?.message || 'Failed to save feeding');
} finally {
setLoading(false);
}
};
const resetForm = () => {
setSide('left');
setDuration(0);
setTimerSeconds(0);
setIsTimerRunning(false);
setAmount('');
setBottleType('formula');
setFoodDescription('');
setAmountDescription('');
setNotes('');
};
const handleDeleteClick = (activityId: string) => {
setActivityToDelete(activityId);
setDeleteDialogOpen(true);
};
const handleDeleteConfirm = async () => {
if (!activityToDelete) return;
try {
setLoading(true);
await trackingApi.deleteActivity(activityToDelete);
setSuccessMessage('Feeding deleted successfully');
setDeleteDialogOpen(false);
setActivityToDelete(null);
await loadRecentFeedings();
} catch (err: any) {
console.error('Failed to delete feeding:', err);
setError(err.response?.data?.message || 'Failed to delete feeding');
} finally {
setLoading(false);
}
};
const getFeedingTypeIcon = (type: string) => {
switch (type) {
case 'breast':
return <LocalCafe />;
case 'bottle':
return <Restaurant />;
case 'solid':
return <Fastfood />;
default:
return <Restaurant />;
}
};
const getFeedingDetails = (activity: Activity) => {
const data = activity.data as FeedingData;
if (data.feedingType === 'breast') {
return `${data.side?.toUpperCase()} - ${data.duration || 0} min`;
} else if (data.feedingType === 'bottle') {
return `${data.amount || 0} ml - ${data.bottleType}`;
} else if (data.feedingType === 'solid') {
return `${data.foodDescription}${data.amountDescription ? ` - ${data.amountDescription}` : ''}`;
}
return '';
};
if (childrenLoading) {
return (
<ProtectedRoute>
<AppShell>
<Box sx={{ display: 'flex', justifyContent: 'center', py: 8 }}>
<CircularProgress />
</Box>
</AppShell>
</ProtectedRoute>
);
}
if (!familyId || children.length === 0) {
return (
<ProtectedRoute>
<AppShell>
<Card>
<CardContent sx={{ textAlign: 'center', py: 8 }}>
<ChildCare sx={{ fontSize: 64, color: 'text.secondary', mb: 2 }} />
<Typography variant="h6" color="text.secondary" gutterBottom>
No Children Added
</Typography>
<Typography variant="body2" color="text.secondary" sx={{ mb: 3 }}>
You need to add a child before you can track feeding activities
</Typography>
<Button
variant="contained"
startIcon={<Add />}
onClick={() => router.push('/children')}
>
Add Child
</Button>
</CardContent>
</Card>
</AppShell>
</ProtectedRoute>
);
}
return (
<ProtectedRoute>
<AppShell>
<Box>
<Box sx={{ display: 'flex', alignItems: 'center', mb: 3 }}>
<IconButton onClick={() => router.back()} sx={{ mr: 2 }}>
<ArrowBack />
</IconButton>
<Typography variant="h4" fontWeight="600">
Track Feeding
</Typography>
</Box>
{error && (
<Alert severity="error" sx={{ mb: 3 }} onClose={() => setError(null)}>
{error}
</Alert>
)}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.3 }}
>
{/* Child Selector */}
{children.length > 1 && (
<Paper sx={{ p: 2, mb: 3 }}>
<FormControl fullWidth>
<InputLabel>Select Child</InputLabel>
<Select
value={selectedChild}
onChange={(e) => setSelectedChild(e.target.value)}
label="Select Child"
>
{children.map((child) => (
<MenuItem key={child.id} value={child.id}>
{child.name}
</MenuItem>
))}
</Select>
</FormControl>
</Paper>
)}
{/* Main Form */}
<Paper sx={{ p: 3, mb: 3 }}>
{/* Feeding Type Tabs */}
<Tabs
value={feedingType}
onChange={(_, newValue) => setFeedingType(newValue)}
sx={{ mb: 3 }}
variant="fullWidth"
>
<Tab label="Breastfeeding" value="breast" icon={<LocalCafe />} iconPosition="start" />
<Tab label="Bottle" value="bottle" icon={<Restaurant />} iconPosition="start" />
<Tab label="Solid Food" value="solid" icon={<Fastfood />} iconPosition="start" />
</Tabs>
{/* Breastfeeding Form */}
{feedingType === 'breast' && (
<Box>
{/* Timer Display */}
<Box sx={{ textAlign: 'center', mb: 4 }}>
<Typography variant="h2" fontWeight="600" sx={{ mb: 2 }}>
{formatDuration(timerSeconds)}
</Typography>
<Box sx={{ display: 'flex', gap: 2, justifyContent: 'center' }}>
{!isTimerRunning ? (
<Button
variant="contained"
size="large"
startIcon={<PlayArrow />}
onClick={startTimer}
>
Start Timer
</Button>
) : (
<Button
variant="contained"
color="error"
size="large"
startIcon={<Stop />}
onClick={stopTimer}
>
Stop Timer
</Button>
)}
<Button
variant="outlined"
size="large"
startIcon={<Refresh />}
onClick={resetTimer}
>
Reset
</Button>
</Box>
</Box>
{/* Side Selector */}
<FormControl fullWidth sx={{ mb: 3 }}>
<InputLabel>Side</InputLabel>
<Select
value={side}
onChange={(e) => setSide(e.target.value as 'left' | 'right' | 'both')}
label="Side"
>
<MenuItem value="left">Left</MenuItem>
<MenuItem value="right">Right</MenuItem>
<MenuItem value="both">Both</MenuItem>
</Select>
</FormControl>
{/* Manual Duration Input */}
<TextField
fullWidth
label="Duration (minutes)"
type="number"
value={duration || ''}
onChange={(e) => setDuration(parseInt(e.target.value) || 0)}
sx={{ mb: 3 }}
helperText="Or use the timer above"
/>
</Box>
)}
{/* Bottle Form */}
{feedingType === 'bottle' && (
<Box>
<TextField
fullWidth
label="Amount (ml)"
type="number"
value={amount}
onChange={(e) => setAmount(e.target.value)}
sx={{ mb: 3 }}
/>
<FormControl fullWidth sx={{ mb: 3 }}>
<InputLabel>Type</InputLabel>
<Select
value={bottleType}
onChange={(e) => setBottleType(e.target.value as 'formula' | 'breastmilk' | 'other')}
label="Type"
>
<MenuItem value="formula">Formula</MenuItem>
<MenuItem value="breastmilk">Breast Milk</MenuItem>
<MenuItem value="other">Other</MenuItem>
</Select>
</FormControl>
</Box>
)}
{/* Solid Food Form */}
{feedingType === 'solid' && (
<Box>
<TextField
fullWidth
label="Food Description"
value={foodDescription}
onChange={(e) => setFoodDescription(e.target.value)}
sx={{ mb: 3 }}
placeholder="e.g., Mashed banana, Rice cereal"
/>
<TextField
fullWidth
label="Amount (optional)"
value={amountDescription}
onChange={(e) => setAmountDescription(e.target.value)}
sx={{ mb: 3 }}
placeholder="e.g., 2 tablespoons, Half bowl"
/>
</Box>
)}
{/* Common Notes Field */}
<TextField
fullWidth
label="Notes (optional)"
multiline
rows={3}
value={notes}
onChange={(e) => setNotes(e.target.value)}
sx={{ mb: 3 }}
placeholder="Any additional notes..."
/>
{/* Submit Button */}
<Button
fullWidth
type="button"
variant="contained"
size="large"
startIcon={<Save />}
onClick={handleSubmit}
disabled={loading}
>
{loading ? 'Saving...' : 'Save Feeding'}
</Button>
</Paper>
{/* Recent Feedings */}
<Paper sx={{ p: 3 }}>
<Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
<Typography variant="h6" fontWeight="600">
Recent Feedings
</Typography>
<IconButton onClick={loadRecentFeedings} disabled={feedingsLoading}>
<Refresh />
</IconButton>
</Box>
{feedingsLoading ? (
<Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}>
<CircularProgress size={30} />
</Box>
) : recentFeedings.length === 0 ? (
<Box sx={{ textAlign: 'center', py: 4 }}>
<Typography variant="body2" color="text.secondary">
No feeding activities yet
</Typography>
</Box>
) : (
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
{recentFeedings.map((activity, index) => {
const data = activity.data as FeedingData;
return (
<motion.div
key={activity.id}
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.2, delay: index * 0.05 }}
>
<Card variant="outlined">
<CardContent>
<Box sx={{ display: 'flex', alignItems: 'flex-start', gap: 2 }}>
<Box sx={{ mt: 0.5 }}>
{getFeedingTypeIcon(data.feedingType)}
</Box>
<Box sx={{ flex: 1 }}>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 0.5 }}>
<Typography variant="body1" fontWeight="600">
{data.feedingType.charAt(0).toUpperCase() + data.feedingType.slice(1)}
</Typography>
<Chip
label={formatDistanceToNow(new Date(activity.timestamp), { addSuffix: true })}
size="small"
variant="outlined"
/>
</Box>
<Typography variant="body2" color="text.secondary" sx={{ mb: 1 }}>
{getFeedingDetails(activity)}
</Typography>
{activity.notes && (
<Typography variant="body2" color="text.secondary" sx={{ fontStyle: 'italic' }}>
{activity.notes}
</Typography>
)}
</Box>
<Box sx={{ display: 'flex', gap: 0.5 }}>
<IconButton
size="small"
color="error"
onClick={() => handleDeleteClick(activity.id)}
disabled={loading}
>
<Delete />
</IconButton>
</Box>
</Box>
</CardContent>
</Card>
</motion.div>
);
})}
</Box>
)}
</Paper>
</motion.div>
</Box>
{/* Delete Confirmation Dialog */}
<Dialog
open={deleteDialogOpen}
onClose={() => setDeleteDialogOpen(false)}
>
<DialogTitle>Delete Feeding Activity?</DialogTitle>
<DialogContent>
<DialogContentText>
Are you sure you want to delete this feeding activity? This action cannot be undone.
</DialogContentText>
</DialogContent>
<DialogActions>
<Button onClick={() => setDeleteDialogOpen(false)} disabled={loading}>
Cancel
</Button>
<Button onClick={handleDeleteConfirm} color="error" disabled={loading}>
{loading ? 'Deleting...' : 'Delete'}
</Button>
</DialogActions>
</Dialog>
{/* Success Snackbar */}
<Snackbar
open={!!successMessage}
autoHideDuration={3000}
onClose={() => setSuccessMessage(null)}
message={successMessage}
/>
</AppShell>
</ProtectedRoute>
);
}

View File

@@ -0,0 +1,89 @@
'use client';
import { Box, Typography, Grid, Card, CardContent, CardActionArea } from '@mui/material';
import { Restaurant, Hotel, BabyChangingStation, ChildCare } from '@mui/icons-material';
import { useRouter } from 'next/navigation';
import { AppShell } from '@/components/layouts/AppShell/AppShell';
import { ProtectedRoute } from '@/components/common/ProtectedRoute';
export default function TrackPage() {
const router = useRouter();
const trackingOptions = [
{
title: 'Feeding',
icon: <Restaurant sx={{ fontSize: 48, color: 'primary.main' }} />,
path: '/track/feeding',
color: '#FFE4E1',
},
{
title: 'Sleep',
icon: <Hotel sx={{ fontSize: 48, color: 'info.main' }} />,
path: '/track/sleep',
color: '#E1F5FF',
},
{
title: 'Diaper',
icon: <BabyChangingStation sx={{ fontSize: 48, color: 'warning.main' }} />,
path: '/track/diaper',
color: '#FFF4E1',
},
{
title: 'Activity',
icon: <ChildCare sx={{ fontSize: 48, color: 'success.main' }} />,
path: '/track/activity',
color: '#E8F5E9',
},
];
return (
<ProtectedRoute>
<AppShell>
<Box>
<Typography variant="h4" fontWeight="600" gutterBottom>
Track Activity
</Typography>
<Typography variant="body1" color="text.secondary" sx={{ mb: 4 }}>
Select an activity to track
</Typography>
<Grid container spacing={3}>
{trackingOptions.map((option) => (
<Grid item xs={12} sm={6} md={3} key={option.title}>
<Card
sx={{
height: '100%',
bgcolor: option.color,
'&:hover': {
transform: 'translateY(-4px)',
transition: 'transform 0.2s',
},
}}
>
<CardActionArea
onClick={() => router.push(option.path)}
sx={{
height: '100%',
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
py: 4,
}}
>
<CardContent sx={{ textAlign: 'center' }}>
{option.icon}
<Typography variant="h6" fontWeight="600" sx={{ mt: 2 }}>
{option.title}
</Typography>
</CardContent>
</CardActionArea>
</Card>
</Grid>
))}
</Grid>
</Box>
</AppShell>
</ProtectedRoute>
);
}

View File

@@ -0,0 +1,643 @@
'use client';
import { useState, useEffect } from 'react';
import {
Box,
Typography,
Button,
Paper,
TextField,
FormControl,
InputLabel,
Select,
MenuItem,
IconButton,
Alert,
CircularProgress,
Card,
CardContent,
Dialog,
DialogTitle,
DialogContent,
DialogContentText,
DialogActions,
Chip,
Snackbar,
} from '@mui/material';
import {
ArrowBack,
Refresh,
Save,
Delete,
Bedtime,
Hotel,
DirectionsCar,
Chair,
Home,
ChildCare,
Add,
} from '@mui/icons-material';
import { useRouter } from 'next/navigation';
import { AppShell } from '@/components/layouts/AppShell/AppShell';
import { ProtectedRoute } from '@/components/common/ProtectedRoute';
import { useAuth } from '@/lib/auth/AuthContext';
import { trackingApi, Activity } from '@/lib/api/tracking';
import { childrenApi, Child } from '@/lib/api/children';
import { motion } from 'framer-motion';
import { formatDistanceToNow, format } from 'date-fns';
interface SleepData {
startTime: string;
endTime?: string;
quality: 'excellent' | 'good' | 'fair' | 'poor';
location: string;
isOngoing?: boolean;
}
export default function SleepTrackPage() {
const router = useRouter();
const { user } = useAuth();
const [children, setChildren] = useState<Child[]>([]);
const [selectedChild, setSelectedChild] = useState<string>('');
// Sleep state
const [startTime, setStartTime] = useState<string>(
format(new Date(), "yyyy-MM-dd'T'HH:mm")
);
const [endTime, setEndTime] = useState<string>(
format(new Date(), "yyyy-MM-dd'T'HH:mm")
);
const [quality, setQuality] = useState<'excellent' | 'good' | 'fair' | 'poor'>('good');
const [location, setLocation] = useState<string>('crib');
const [isOngoing, setIsOngoing] = useState<boolean>(false);
// Common state
const [notes, setNotes] = useState<string>('');
const [recentSleeps, setRecentSleeps] = useState<Activity[]>([]);
const [loading, setLoading] = useState(false);
const [childrenLoading, setChildrenLoading] = useState(true);
const [sleepsLoading, setSleepsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [successMessage, setSuccessMessage] = useState<string | null>(null);
// Delete confirmation dialog
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
const [activityToDelete, setActivityToDelete] = useState<string | null>(null);
const familyId = user?.families?.[0]?.familyId;
// Load children
useEffect(() => {
if (familyId) {
loadChildren();
}
}, [familyId]);
// Load recent sleeps when child is selected
useEffect(() => {
if (selectedChild) {
loadRecentSleeps();
}
}, [selectedChild]);
const loadChildren = async () => {
if (!familyId) return;
try {
setChildrenLoading(true);
const childrenData = await childrenApi.getChildren(familyId);
setChildren(childrenData);
if (childrenData.length > 0) {
setSelectedChild(childrenData[0].id);
}
} catch (err: any) {
console.error('Failed to load children:', err);
setError(err.response?.data?.message || 'Failed to load children');
} finally {
setChildrenLoading(false);
}
};
const loadRecentSleeps = async () => {
if (!selectedChild) return;
try {
setSleepsLoading(true);
const activities = await trackingApi.getActivities(selectedChild, 'sleep');
// Sort by timestamp descending and take last 10
const sorted = activities.sort((a, b) =>
new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime()
).slice(0, 10);
setRecentSleeps(sorted);
} catch (err: any) {
console.error('Failed to load recent sleeps:', err);
} finally {
setSleepsLoading(false);
}
};
const formatDuration = (start: string, end?: string) => {
const startDate = new Date(start);
const endDate = end ? new Date(end) : new Date();
const diffMs = endDate.getTime() - startDate.getTime();
if (diffMs < 0) return 'Invalid duration';
const hours = Math.floor(diffMs / (1000 * 60 * 60));
const minutes = Math.floor((diffMs % (1000 * 60 * 60)) / (1000 * 60));
if (hours === 0) {
return `${minutes} minute${minutes !== 1 ? 's' : ''}`;
} else if (minutes === 0) {
return `${hours} hour${hours !== 1 ? 's' : ''}`;
} else {
return `${hours} hour${hours !== 1 ? 's' : ''} ${minutes} minute${minutes !== 1 ? 's' : ''}`;
}
};
const calculateDuration = () => {
if (!startTime) return null;
if (isOngoing) {
return formatDuration(startTime);
}
if (!endTime) return null;
const start = new Date(startTime);
const end = new Date(endTime);
if (end <= start) return null;
return formatDuration(startTime, endTime);
};
const setStartNow = () => {
setStartTime(format(new Date(), "yyyy-MM-dd'T'HH:mm"));
};
const setEndNow = () => {
setEndTime(format(new Date(), "yyyy-MM-dd'T'HH:mm"));
};
const handleSubmit = async () => {
if (!selectedChild) {
setError('Please select a child');
return;
}
// Validation
if (!startTime) {
setError('Please enter start time');
return;
}
if (!isOngoing && !endTime) {
setError('Please enter end time or mark as ongoing');
return;
}
if (!isOngoing && endTime) {
const start = new Date(startTime);
const end = new Date(endTime);
if (end <= start) {
setError('End time must be after start time');
return;
}
}
try {
setLoading(true);
setError(null);
const data: SleepData = {
startTime,
quality,
location,
isOngoing,
};
if (!isOngoing && endTime) {
data.endTime = endTime;
}
await trackingApi.createActivity(selectedChild, {
type: 'sleep',
timestamp: startTime,
data,
notes: notes || undefined,
});
setSuccessMessage('Sleep logged successfully!');
// Reset form
resetForm();
// Reload recent sleeps
await loadRecentSleeps();
} catch (err: any) {
console.error('Failed to save sleep:', err);
setError(err.response?.data?.message || 'Failed to save sleep');
} finally {
setLoading(false);
}
};
const resetForm = () => {
setStartTime(format(new Date(), "yyyy-MM-dd'T'HH:mm"));
setEndTime(format(new Date(), "yyyy-MM-dd'T'HH:mm"));
setQuality('good');
setLocation('crib');
setIsOngoing(false);
setNotes('');
};
const handleDeleteClick = (activityId: string) => {
setActivityToDelete(activityId);
setDeleteDialogOpen(true);
};
const handleDeleteConfirm = async () => {
if (!activityToDelete) return;
try {
setLoading(true);
await trackingApi.deleteActivity(activityToDelete);
setSuccessMessage('Sleep deleted successfully');
setDeleteDialogOpen(false);
setActivityToDelete(null);
await loadRecentSleeps();
} catch (err: any) {
console.error('Failed to delete sleep:', err);
setError(err.response?.data?.message || 'Failed to delete sleep');
} finally {
setLoading(false);
}
};
const getLocationIcon = (loc: string) => {
switch (loc) {
case 'crib':
return <Hotel />;
case 'bed':
return <Bedtime />;
case 'stroller':
return <DirectionsCar />;
case 'carrier':
return <Chair />;
case 'other':
return <Home />;
default:
return <Hotel />;
}
};
const getQualityColor = (qual: string) => {
switch (qual) {
case 'excellent':
return 'success';
case 'good':
return 'primary';
case 'fair':
return 'warning';
case 'poor':
return 'error';
default:
return 'default';
}
};
const getSleepDetails = (activity: Activity) => {
const data = activity.data as SleepData;
const duration = data.endTime
? formatDuration(data.startTime, data.endTime)
: data.isOngoing
? `Ongoing - ${formatDuration(data.startTime)}`
: 'No end time';
return `${duration} - ${data.location.charAt(0).toUpperCase() + data.location.slice(1)}`;
};
if (childrenLoading) {
return (
<ProtectedRoute>
<AppShell>
<Box sx={{ display: 'flex', justifyContent: 'center', py: 8 }}>
<CircularProgress />
</Box>
</AppShell>
</ProtectedRoute>
);
}
if (!familyId || children.length === 0) {
return (
<ProtectedRoute>
<AppShell>
<Card>
<CardContent sx={{ textAlign: 'center', py: 8 }}>
<ChildCare sx={{ fontSize: 64, color: 'text.secondary', mb: 2 }} />
<Typography variant="h6" color="text.secondary" gutterBottom>
No Children Added
</Typography>
<Typography variant="body2" color="text.secondary" sx={{ mb: 3 }}>
You need to add a child before you can track sleep activities
</Typography>
<Button
variant="contained"
startIcon={<Add />}
onClick={() => router.push('/children')}
>
Add Child
</Button>
</CardContent>
</Card>
</AppShell>
</ProtectedRoute>
);
}
return (
<ProtectedRoute>
<AppShell>
<Box>
<Box sx={{ display: 'flex', alignItems: 'center', mb: 3 }}>
<IconButton onClick={() => router.back()} sx={{ mr: 2 }}>
<ArrowBack />
</IconButton>
<Typography variant="h4" fontWeight="600">
Track Sleep
</Typography>
</Box>
{error && (
<Alert severity="error" sx={{ mb: 3 }} onClose={() => setError(null)}>
{error}
</Alert>
)}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.3 }}
>
{/* Child Selector */}
{children.length > 1 && (
<Paper sx={{ p: 2, mb: 3 }}>
<FormControl fullWidth>
<InputLabel>Select Child</InputLabel>
<Select
value={selectedChild}
onChange={(e) => setSelectedChild(e.target.value)}
label="Select Child"
>
{children.map((child) => (
<MenuItem key={child.id} value={child.id}>
{child.name}
</MenuItem>
))}
</Select>
</FormControl>
</Paper>
)}
{/* Main Form */}
<Paper sx={{ p: 3, mb: 3 }}>
{/* Start Time */}
<Box sx={{ mb: 3 }}>
<Typography variant="subtitle1" fontWeight="600" sx={{ mb: 1 }}>
Sleep Start Time
</Typography>
<Box sx={{ display: 'flex', gap: 2, alignItems: 'flex-start' }}>
<TextField
fullWidth
type="datetime-local"
value={startTime}
onChange={(e) => setStartTime(e.target.value)}
InputLabelProps={{ shrink: true }}
/>
<Button variant="outlined" onClick={setStartNow} sx={{ minWidth: 100 }}>
Now
</Button>
</Box>
</Box>
{/* Ongoing Checkbox */}
<Box sx={{ mb: 3 }}>
<FormControl fullWidth>
<InputLabel>Sleep Status</InputLabel>
<Select
value={isOngoing ? 'ongoing' : 'completed'}
onChange={(e) => setIsOngoing(e.target.value === 'ongoing')}
label="Sleep Status"
>
<MenuItem value="completed">Completed (has end time)</MenuItem>
<MenuItem value="ongoing">Ongoing (still sleeping)</MenuItem>
</Select>
</FormControl>
</Box>
{/* End Time */}
{!isOngoing && (
<Box sx={{ mb: 3 }}>
<Typography variant="subtitle1" fontWeight="600" sx={{ mb: 1 }}>
Wake Up Time
</Typography>
<Box sx={{ display: 'flex', gap: 2, alignItems: 'flex-start' }}>
<TextField
fullWidth
type="datetime-local"
value={endTime}
onChange={(e) => setEndTime(e.target.value)}
InputLabelProps={{ shrink: true }}
/>
<Button variant="outlined" onClick={setEndNow} sx={{ minWidth: 100 }}>
Now
</Button>
</Box>
</Box>
)}
{/* Duration Display */}
{calculateDuration() && (
<Box sx={{ mb: 3, textAlign: 'center' }}>
<Chip
label={`Duration: ${calculateDuration()}`}
color="primary"
sx={{ fontSize: '1rem', py: 3 }}
/>
</Box>
)}
{/* Sleep Quality */}
<FormControl fullWidth sx={{ mb: 3 }}>
<InputLabel>Sleep Quality</InputLabel>
<Select
value={quality}
onChange={(e) => setQuality(e.target.value as 'excellent' | 'good' | 'fair' | 'poor')}
label="Sleep Quality"
>
<MenuItem value="excellent">Excellent</MenuItem>
<MenuItem value="good">Good</MenuItem>
<MenuItem value="fair">Fair</MenuItem>
<MenuItem value="poor">Poor</MenuItem>
</Select>
</FormControl>
{/* Location */}
<FormControl fullWidth sx={{ mb: 3 }}>
<InputLabel>Location</InputLabel>
<Select
value={location}
onChange={(e) => setLocation(e.target.value)}
label="Location"
>
<MenuItem value="crib">Crib</MenuItem>
<MenuItem value="bed">Bed</MenuItem>
<MenuItem value="stroller">Stroller</MenuItem>
<MenuItem value="carrier">Carrier</MenuItem>
<MenuItem value="other">Other</MenuItem>
</Select>
</FormControl>
{/* Common Notes Field */}
<TextField
fullWidth
label="Notes (optional)"
multiline
rows={3}
value={notes}
onChange={(e) => setNotes(e.target.value)}
sx={{ mb: 3 }}
placeholder="Any disruptions, dreams, or observations..."
/>
{/* Submit Button */}
<Button
fullWidth
type="button"
variant="contained"
size="large"
startIcon={<Save />}
onClick={handleSubmit}
disabled={loading}
>
{loading ? 'Saving...' : 'Save Sleep'}
</Button>
</Paper>
{/* Recent Sleeps */}
<Paper sx={{ p: 3 }}>
<Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
<Typography variant="h6" fontWeight="600">
Recent Sleep Activities
</Typography>
<IconButton onClick={loadRecentSleeps} disabled={sleepsLoading}>
<Refresh />
</IconButton>
</Box>
{sleepsLoading ? (
<Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}>
<CircularProgress size={30} />
</Box>
) : recentSleeps.length === 0 ? (
<Box sx={{ textAlign: 'center', py: 4 }}>
<Typography variant="body2" color="text.secondary">
No sleep activities yet
</Typography>
</Box>
) : (
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
{recentSleeps.map((activity, index) => {
const data = activity.data as SleepData;
return (
<motion.div
key={activity.id}
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.2, delay: index * 0.05 }}
>
<Card variant="outlined">
<CardContent>
<Box sx={{ display: 'flex', alignItems: 'flex-start', gap: 2 }}>
<Box sx={{ mt: 0.5 }}>
{getLocationIcon(data.location)}
</Box>
<Box sx={{ flex: 1 }}>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 0.5, flexWrap: 'wrap' }}>
<Typography variant="body1" fontWeight="600">
Sleep
</Typography>
<Chip
label={data.quality.charAt(0).toUpperCase() + data.quality.slice(1)}
size="small"
color={getQualityColor(data.quality) as any}
/>
<Chip
label={formatDistanceToNow(new Date(activity.timestamp), { addSuffix: true })}
size="small"
variant="outlined"
/>
</Box>
<Typography variant="body2" color="text.secondary" sx={{ mb: 1 }}>
{getSleepDetails(activity)}
</Typography>
{activity.notes && (
<Typography variant="body2" color="text.secondary" sx={{ fontStyle: 'italic' }}>
{activity.notes}
</Typography>
)}
</Box>
<Box sx={{ display: 'flex', gap: 0.5 }}>
<IconButton
size="small"
color="error"
onClick={() => handleDeleteClick(activity.id)}
disabled={loading}
>
<Delete />
</IconButton>
</Box>
</Box>
</CardContent>
</Card>
</motion.div>
);
})}
</Box>
)}
</Paper>
</motion.div>
</Box>
{/* Delete Confirmation Dialog */}
<Dialog
open={deleteDialogOpen}
onClose={() => setDeleteDialogOpen(false)}
>
<DialogTitle>Delete Sleep Activity?</DialogTitle>
<DialogContent>
<DialogContentText>
Are you sure you want to delete this sleep activity? This action cannot be undone.
</DialogContentText>
</DialogContent>
<DialogActions>
<Button onClick={() => setDeleteDialogOpen(false)} disabled={loading}>
Cancel
</Button>
<Button onClick={handleDeleteConfirm} color="error" disabled={loading}>
{loading ? 'Deleting...' : 'Delete'}
</Button>
</DialogActions>
</Dialog>
{/* Success Snackbar */}
<Snackbar
open={!!successMessage}
autoHideDuration={3000}
onClose={() => setSuccessMessage(null)}
message={successMessage}
/>
</AppShell>
</ProtectedRoute>
);
}