'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';
import { useTranslation } from '@/hooks/useTranslation';

export default function ChildrenPage() {
  const { t } = useTranslation('children');
  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(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 (
    <ProtectedRoute>
      <AppShell>
        <Box>
          <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 4 }}>
            <Box>
              <Typography variant="h4" component="h1" fontWeight="600" gutterBottom>
                {t('title')}
              </Typography>
              <Typography variant="body1" color="text.secondary">
                {t('subtitle')}
              </Typography>
            </Box>
            <Button
              variant="contained"
              startIcon={<Add />}
              onClick={handleAddChild}
              disabled={loading || !familyId}
            >
              {t('addChild')}
            </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" component="h2" color="text.secondary" gutterBottom>
                      {t('noChildren')}
                    </Typography>
                    <Typography variant="body2" color="text.secondary" sx={{ mb: 3 }}>
                      {t('noChildrenSubtitle')}
                    </Typography>
                    <Button
                      variant="contained"
                      startIcon={<Add />}
                      onClick={handleAddChild}
                      disabled={!familyId}
                    >
                      {t('addFirstChild')}
                    </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: '280px', // Fixed height for consistency
                        minHeight: '280px',
                        width: '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={t(`gender.${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 }}
                        >
                          {t('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>
  );
}
