'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, } 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([]); const [selectedChild, setSelectedChild] = useState(''); const [feedingType, setFeedingType] = useState<'breast' | 'bottle' | 'solid'>('breast'); // Breastfeeding state const [side, setSide] = useState<'left' | 'right' | 'both'>('left'); const [duration, setDuration] = useState(0); const [isTimerRunning, setIsTimerRunning] = useState(false); const [timerSeconds, setTimerSeconds] = useState(0); // Bottle feeding state const [amount, setAmount] = useState(''); const [bottleType, setBottleType] = useState<'formula' | 'breastmilk' | 'other'>('formula'); // Solid food state const [foodDescription, setFoodDescription] = useState(''); const [amountDescription, setAmountDescription] = useState(''); // Common state const [notes, setNotes] = useState(''); const [recentFeedings, setRecentFeedings] = useState([]); const [loading, setLoading] = useState(false); const [childrenLoading, setChildrenLoading] = useState(true); const [feedingsLoading, setFeedingsLoading] = useState(false); const [error, setError] = useState(null); const [successMessage, setSuccessMessage] = useState(null); // Delete confirmation dialog const [deleteDialogOpen, setDeleteDialogOpen] = useState(false); const [activityToDelete, setActivityToDelete] = useState(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 ; case 'bottle': return ; case 'solid': return ; default: return ; } }; 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 ( ); } if (!familyId || children.length === 0) { return ( Please add a child first before tracking feeding activities. ); } return ( router.back()} sx={{ mr: 2 }}> Track Feeding {error && ( setError(null)}> {error} )} {/* Child Selector */} {children.length > 1 && ( Select Child )} {/* Main Form */} {/* Feeding Type Tabs */} setFeedingType(newValue)} sx={{ mb: 3 }} variant="fullWidth" > } iconPosition="start" /> } iconPosition="start" /> } iconPosition="start" /> {/* Breastfeeding Form */} {feedingType === 'breast' && ( {/* Timer Display */} {formatDuration(timerSeconds)} {!isTimerRunning ? ( ) : ( )} {/* Side Selector */} Side {/* Manual Duration Input */} setDuration(parseInt(e.target.value) || 0)} sx={{ mb: 3 }} helperText="Or use the timer above" /> )} {/* Bottle Form */} {feedingType === 'bottle' && ( setAmount(e.target.value)} sx={{ mb: 3 }} /> Type )} {/* Solid Food Form */} {feedingType === 'solid' && ( setFoodDescription(e.target.value)} sx={{ mb: 3 }} placeholder="e.g., Mashed banana, Rice cereal" /> setAmountDescription(e.target.value)} sx={{ mb: 3 }} placeholder="e.g., 2 tablespoons, Half bowl" /> )} {/* Common Notes Field */} setNotes(e.target.value)} sx={{ mb: 3 }} placeholder="Any additional notes..." /> {/* Submit Button */} {/* Recent Feedings */} Recent Feedings {feedingsLoading ? ( ) : recentFeedings.length === 0 ? ( No feeding activities yet ) : ( {recentFeedings.map((activity, index) => { const data = activity.data as FeedingData; return ( {getFeedingTypeIcon(data.feedingType)} {data.feedingType.charAt(0).toUpperCase() + data.feedingType.slice(1)} {getFeedingDetails(activity)} {activity.notes && ( {activity.notes} )} handleDeleteClick(activity.id)} disabled={loading} > ); })} )} {/* Delete Confirmation Dialog */} setDeleteDialogOpen(false)} > Delete Feeding Activity? Are you sure you want to delete this feeding activity? This action cannot be undone. {/* Success Snackbar */} setSuccessMessage(null)} message={successMessage} /> ); }