'use client';

import { useRouter } from 'next/navigation';
import { useState, useEffect, useCallback } from 'react';

import Box from '@mui/material/Box';
import Card from '@mui/material/Card';
import Grid from '@mui/material/Grid';
import Stack from '@mui/material/Stack';
import Alert from '@mui/material/Alert';
import Avatar from '@mui/material/Avatar';
import Button from '@mui/material/Button';
import Typography from '@mui/material/Typography';
import CardContent from '@mui/material/CardContent';
import CardActions from '@mui/material/CardActions';
import CircularProgress from '@mui/material/CircularProgress';

import { paths } from 'src/routes/paths';

import axios from 'src/utils/axios';

import { DashboardContent } from 'src/layouts/dashboard';

import { Iconify } from 'src/components/iconify';
import { CustomBreadcrumbs } from 'src/components/custom-breadcrumbs';

// ----------------------------------------------------------------------

async function getChildren() {
  const res = await axios.get('/users/parents/children/');
  const {data} = res;
  if (Array.isArray(data)) return data;
  return data?.results ?? [];
}

// ----------------------------------------------------------------------

export function ChildrenView() {
  const router = useRouter();
  const [children, setChildren] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  const load = useCallback(async () => {
    try {
      setLoading(true);
      const list = await getChildren();
      setChildren(list);
    } catch (e) {
      setError(e?.response?.data?.detail || e?.message || 'Ошибка загрузки');
    } finally {
      setLoading(false);
    }
  }, []);

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

  return (
    <DashboardContent>
      <CustomBreadcrumbs
        heading="Мои дети"
        links={[{ name: 'Главная', href: paths.dashboard.root }, { name: 'Мои дети' }]}
        sx={{ mb: 3 }}
      />

      {error && (
        <Alert severity="error" sx={{ mb: 3 }}>
          {error}
        </Alert>
      )}

      {loading ? (
        <Box sx={{ display: 'flex', justifyContent: 'center', py: 8 }}>
          <CircularProgress />
        </Box>
      ) : children.length === 0 ? (
        <Box sx={{ textAlign: 'center', py: 8 }}>
          <Iconify icon="eva:people-outline" width={64} color="text.disabled" />
          <Typography variant="body1" color="text.secondary" sx={{ mt: 2 }}>
            Нет привязанных детей
          </Typography>
        </Box>
      ) : (
        <Grid container spacing={2}>
          {children.map((child) => {
            const name = `${child.first_name || ''} ${child.last_name || ''}`.trim() || child.email;
            return (
              <Grid key={child.id} item xs={12} sm={6} md={4}>
                <Card variant="outlined">
                  <CardContent>
                    <Stack direction="row" spacing={2} alignItems="center">
                      <Avatar sx={{ width: 48, height: 48, bgcolor: 'primary.lighter', color: 'primary.main' }}>
                        {name[0]?.toUpperCase()}
                      </Avatar>
                      <Box>
                        <Typography variant="subtitle1">{name}</Typography>
                        <Typography variant="body2" color="text.secondary">
                          {child.email}
                        </Typography>
                      </Box>
                    </Stack>
                  </CardContent>
                  <CardActions sx={{ px: 2, pb: 2 }}>
                    <Button
                      variant="contained"
                      fullWidth
                      startIcon={<Iconify icon="eva:trending-up-outline" />}
                      onClick={() => router.push(`${paths.dashboard.childrenProgress}?child=${child.id}`)}
                    >
                      Прогресс
                    </Button>
                  </CardActions>
                </Card>
              </Grid>
            );
          })}
        </Grid>
      )}
    </DashboardContent>
  );
}
