'use client';

import { useState, useEffect } from 'react';
import {
  Box,
  Card,
  CardContent,
  Typography,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  IconButton,
  Chip,
  Button,
  TextField,
  InputAdornment,
  TablePagination,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Avatar,
  AvatarGroup,
  List,
  ListItem,
  ListItemAvatar,
  ListItemText,
  Divider,
} from '@mui/material';
import {
  Search,
  Edit,
  Delete,
  Visibility,
  FamilyRestroom,
  PersonAdd,
  ChildCare,
  Group,
} from '@mui/icons-material';
import AdminLayout from '@/components/AdminLayout';
import apiClient from '@/lib/api-client';

interface FamilyMember {
  id: string;
  name: string;
  email: string;
  role: 'parent' | 'caregiver';
  joinedAt: string;
}

interface Child {
  id: string;
  name: string;
  birthDate: string;
  gender: 'male' | 'female' | 'other';
  displayColor: string;
}

interface Family {
  id: string;
  name: string;
  createdAt: string;
  memberCount: number;
  childrenCount: number;
  activityCount: number;
  lastActivityAt: string;
  members: FamilyMember[];
  children: Child[];
}

export default function FamiliesPage() {
  const [families, setFamilies] = useState<Family[]>([]);
  const [loading, setLoading] = useState(true);
  const [page, setPage] = useState(0);
  const [rowsPerPage, setRowsPerPage] = useState(10);
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedFamily, setSelectedFamily] = useState<Family | null>(null);
  const [viewDialogOpen, setViewDialogOpen] = useState(false);

  useEffect(() => {
    fetchFamilies();
  }, []);

  const fetchFamilies = async () => {
    try {
      setLoading(true);
      const response = await apiClient.get('/admin/families');
      setFamilies(response.data || []);
    } catch (error) {
      console.error('Failed to fetch families:', error);
      setFamilies([]);
    } finally {
      setLoading(false);
    }
  };

  const handleViewFamily = (family: Family) => {
    setSelectedFamily(family);
    setViewDialogOpen(true);
  };

  const handleDeleteFamily = async (familyId: string) => {
    if (window.confirm('Are you sure you want to delete this family? This action cannot be undone.')) {
      try {
        await apiClient.delete(`/admin/families/${familyId}`);
        fetchFamilies();
      } catch (error) {
        console.error('Failed to delete family:', error);
      }
    }
  };

  const filteredFamilies = families.filter((family) =>
    family.name.toLowerCase().includes(searchQuery.toLowerCase())
  );

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
    });
  };

  const calculateAge = (birthDate: string) => {
    const birth = new Date(birthDate);
    const now = new Date();
    const ageInMonths = (now.getFullYear() - birth.getFullYear()) * 12 +
                        (now.getMonth() - birth.getMonth());

    if (ageInMonths < 12) {
      return `${ageInMonths} months`;
    } else if (ageInMonths < 24) {
      const months = ageInMonths % 12;
      return months > 0 ? `1 year ${months} months` : '1 year';
    } else {
      const years = Math.floor(ageInMonths / 12);
      return `${years} years`;
    }
  };

  return (
    <AdminLayout>
      <Box sx={{ mb: 3 }}>
        <Typography variant="h4" gutterBottom sx={{ fontWeight: 600 }}>
          Family Management
        </Typography>
        <Typography variant="body1" color="text.secondary">
          View and manage family groups, members, and children
        </Typography>
      </Box>

      {/* Stats Cards */}
      <Box sx={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(250px, 1fr))', gap: 3, mb: 4 }}>
        <Card>
          <CardContent>
            <Typography color="text.secondary" gutterBottom>
              Total Families
            </Typography>
            <Typography variant="h3" sx={{ color: 'primary.main' }}>
              {families.length.toLocaleString()}
            </Typography>
          </CardContent>
        </Card>
        <Card>
          <CardContent>
            <Typography color="text.secondary" gutterBottom>
              Total Members
            </Typography>
            <Typography variant="h3" sx={{ color: 'success.main' }}>
              {families.reduce((sum, f) => sum + f.memberCount, 0).toLocaleString()}
            </Typography>
          </CardContent>
        </Card>
        <Card>
          <CardContent>
            <Typography color="text.secondary" gutterBottom>
              Total Children
            </Typography>
            <Typography variant="h3" sx={{ color: 'info.main' }}>
              {families.reduce((sum, f) => sum + f.childrenCount, 0).toLocaleString()}
            </Typography>
          </CardContent>
        </Card>
        <Card>
          <CardContent>
            <Typography color="text.secondary" gutterBottom>
              Total Activities
            </Typography>
            <Typography variant="h3" sx={{ color: 'secondary.main' }}>
              {families.reduce((sum, f) => sum + f.activityCount, 0).toLocaleString()}
            </Typography>
          </CardContent>
        </Card>
      </Box>

      {/* Search Bar */}
      <Box sx={{ mb: 3 }}>
        <TextField
          placeholder="Search families..."
          value={searchQuery}
          onChange={(e) => setSearchQuery(e.target.value)}
          fullWidth
          InputProps={{
            startAdornment: (
              <InputAdornment position="start">
                <Search />
              </InputAdornment>
            ),
          }}
        />
      </Box>

      {/* Families Table */}
      <TableContainer component={Paper}>
        <Table>
          <TableHead>
            <TableRow>
              <TableCell>Family Name</TableCell>
              <TableCell>Members</TableCell>
              <TableCell>Children</TableCell>
              <TableCell align="center">Activities</TableCell>
              <TableCell>Created</TableCell>
              <TableCell>Last Activity</TableCell>
              <TableCell align="right">Actions</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {filteredFamilies
              .slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
              .map((family) => (
                <TableRow key={family.id}>
                  <TableCell>
                    <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                      <FamilyRestroom sx={{ color: 'primary.main' }} />
                      <Typography variant="body1" sx={{ fontWeight: 500 }}>
                        {family.name}
                      </Typography>
                    </Box>
                  </TableCell>
                  <TableCell>
                    <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                      <AvatarGroup max={3}>
                        {family.members.map((member) => (
                          <Avatar
                            key={member.id}
                            sx={{ bgcolor: 'primary.light', width: 32, height: 32 }}
                          >
                            {member.name.charAt(0)}
                          </Avatar>
                        ))}
                      </AvatarGroup>
                      <Typography variant="body2">{family.memberCount}</Typography>
                    </Box>
                  </TableCell>
                  <TableCell>
                    <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                      <AvatarGroup max={3}>
                        {family.children.map((child) => (
                          <Avatar
                            key={child.id}
                            sx={{ bgcolor: child.displayColor, width: 32, height: 32 }}
                          >
                            {child.name.charAt(0)}
                          </Avatar>
                        ))}
                      </AvatarGroup>
                      <Typography variant="body2">{family.childrenCount}</Typography>
                    </Box>
                  </TableCell>
                  <TableCell align="center">
                    <Chip label={family.activityCount.toLocaleString()} size="small" />
                  </TableCell>
                  <TableCell>{formatDate(family.createdAt)}</TableCell>
                  <TableCell>{formatDate(family.lastActivityAt)}</TableCell>
                  <TableCell align="right">
                    <IconButton
                      size="small"
                      onClick={() => handleViewFamily(family)}
                      title="View Details"
                    >
                      <Visibility />
                    </IconButton>
                    <IconButton
                      size="small"
                      onClick={() => handleDeleteFamily(family.id)}
                      title="Delete"
                      color="error"
                    >
                      <Delete />
                    </IconButton>
                  </TableCell>
                </TableRow>
              ))}
          </TableBody>
        </Table>
        <TablePagination
          rowsPerPageOptions={[5, 10, 25]}
          component="div"
          count={filteredFamilies.length}
          rowsPerPage={rowsPerPage}
          page={page}
          onPageChange={(e, newPage) => setPage(newPage)}
          onRowsPerPageChange={(e) => {
            setRowsPerPage(parseInt(e.target.value, 10));
            setPage(0);
          }}
        />
      </TableContainer>

      {/* View Family Dialog */}
      <Dialog
        open={viewDialogOpen}
        onClose={() => setViewDialogOpen(false)}
        maxWidth="md"
        fullWidth
      >
        <DialogTitle>{selectedFamily?.name}</DialogTitle>
        <DialogContent>
          {selectedFamily && (
            <Box sx={{ pt: 2 }}>
              <Box sx={{ mb: 3 }}>
                <Typography variant="h6" gutterBottom>
                  Family Information
                </Typography>
                <Box sx={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 2 }}>
                  <Box>
                    <Typography variant="subtitle2" color="text.secondary">
                      Family ID
                    </Typography>
                    <Typography variant="body1">{selectedFamily.id}</Typography>
                  </Box>
                  <Box>
                    <Typography variant="subtitle2" color="text.secondary">
                      Created
                    </Typography>
                    <Typography variant="body1">
                      {formatDate(selectedFamily.createdAt)}
                    </Typography>
                  </Box>
                  <Box>
                    <Typography variant="subtitle2" color="text.secondary">
                      Total Activities
                    </Typography>
                    <Typography variant="body1">
                      {selectedFamily.activityCount.toLocaleString()}
                    </Typography>
                  </Box>
                  <Box>
                    <Typography variant="subtitle2" color="text.secondary">
                      Last Activity
                    </Typography>
                    <Typography variant="body1">
                      {formatDate(selectedFamily.lastActivityAt)}
                    </Typography>
                  </Box>
                </Box>
              </Box>

              <Divider sx={{ mb: 3 }} />

              <Box sx={{ display: 'grid', gridTemplateColumns: { xs: '1fr', md: '1fr 1fr' }, gap: 3 }}>
                {/* Members */}
                <Box>
                  <Typography variant="h6" gutterBottom>
                    Members ({selectedFamily.memberCount})
                  </Typography>
                  <List>
                    {selectedFamily.members.map((member) => (
                      <ListItem key={member.id} sx={{ px: 0 }}>
                        <ListItemAvatar>
                          <Avatar sx={{ bgcolor: 'primary.main' }}>
                            {member.name.charAt(0)}
                          </Avatar>
                        </ListItemAvatar>
                        <ListItemText
                          primary={member.name}
                          secondary={
                            <>
                              {member.email}
                              <br />
                              <Chip
                                label={member.role}
                                size="small"
                                sx={{ mt: 0.5 }}
                                color={member.role === 'parent' ? 'primary' : 'default'}
                              />
                            </>
                          }
                        />
                      </ListItem>
                    ))}
                  </List>
                </Box>

                {/* Children */}
                <Box>
                  <Typography variant="h6" gutterBottom>
                    Children ({selectedFamily.childrenCount})
                  </Typography>
                  <List>
                    {selectedFamily.children.map((child) => (
                      <ListItem key={child.id} sx={{ px: 0 }}>
                        <ListItemAvatar>
                          <Avatar sx={{ bgcolor: child.displayColor }}>
                            {child.name.charAt(0)}
                          </Avatar>
                        </ListItemAvatar>
                        <ListItemText
                          primary={child.name}
                          secondary={
                            <>
                              Age: {calculateAge(child.birthDate)}
                              <br />
                              Gender: {child.gender}
                              <br />
                              Born: {formatDate(child.birthDate)}
                            </>
                          }
                        />
                      </ListItem>
                    ))}
                  </List>
                </Box>
              </Box>
            </Box>
          )}
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setViewDialogOpen(false)}>Close</Button>
        </DialogActions>
      </Dialog>
    </AdminLayout>
  );
}