'use client'; import { useState, useEffect } from 'react'; import { Box, Typography, Grid, Paper, Button, Avatar, IconButton, CircularProgress, Alert, Chip, Container, Card, CardContent, } from '@mui/material'; import { Add, ChildCare, Edit, Delete, CalendarToday } 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'; import { useTranslation } from '@/hooks/useTranslation'; import { useLocalizedDate } from '@/hooks/useLocalizedDate'; export default function ChildrenPage() { const { t } = useTranslation('children'); const { user } = useAuth(); const { format: formatDate } = useLocalizedDate(); const [children, setChildren] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(''); const [dialogOpen, setDialogOpen] = useState(false); const [deleteDialogOpen, setDeleteDialogOpen] = useState(false); const [selectedChild, setSelectedChild] = useState(null); const [childToDelete, setChildToDelete] = useState(null); const [actionLoading, setActionLoading] = useState(false); // Get familyId from user const familyId = user?.families?.[0]?.familyId; useEffect(() => { if (familyId) { fetchChildren(); } else { setLoading(false); setError(t('errors.noFamily')); } }, [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 || t('errors.loadFailed')); } 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(t('errors.noFamilyId')); } 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 || t('errors.saveFailed')); } 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 || t('errors.deleteFailed')); } 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} ${months !== 1 ? t('ageFormat.months') : t('ageFormat.month')}`; } else if (months === 0) { return `${years} ${years !== 1 ? t('ageFormat.years') : t('ageFormat.year')}`; } else { return `${years} ${years !== 1 ? t('ageFormat.years') : t('ageFormat.year')}, ${months} ${months !== 1 ? t('ageFormat.months') : t('ageFormat.month')}`; } }; return ( {t('title')} {t('subtitle')} {error && ( setError('')}> {error} )} {loading ? ( ) : children.length === 0 ? ( {t('noChildren')} {t('noChildrenSubtitle')} ) : ( {children.map((child, index) => ( {child.name[0]} {child.name} {t(`gender.${child.gender}`)} {formatDate(child.birthDate, 'PPP')} {t('age')}: {calculateAge(child.birthDate)} handleEditChild(child)}> handleDeleteClick(child)}> ))} )} setDialogOpen(false)} onSubmit={handleSubmit} child={selectedChild} isLoading={actionLoading} /> setDeleteDialogOpen(false)} onConfirm={handleDeleteConfirm} childName={childToDelete?.name || ''} isLoading={actionLoading} /> ); }