'use client';

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

import Box from '@mui/material/Box';
import Card from '@mui/material/Card';
import Stack from '@mui/material/Stack';
import Alert from '@mui/material/Alert';
import Button from '@mui/material/Button';
import Typography from '@mui/material/Typography';
import CardContent from '@mui/material/CardContent';
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 getChildProgress(childId) {
  const params = childId ? `?child_id=${childId}` : '';
  const res = await axios.get(`/users/student-progress/${params}`);
  return res.data;
}

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

function StatCard({ label, value, icon, color }) {
  return (
    <Card variant="outlined" sx={{ flex: 1, minWidth: 140 }}>
      <CardContent>
        <Stack direction="row" alignItems="center" spacing={1.5} sx={{ mb: 1 }}>
          <Box
            sx={{
              width: 40,
              height: 40,
              borderRadius: 1.5,
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              bgcolor: `${color}.lighter`,
            }}
          >
            <Iconify icon={icon} width={22} color={`${color}.main`} />
          </Box>
          <Typography variant="h5" fontWeight="bold">
            {value ?? 0}
          </Typography>
        </Stack>
        <Typography variant="caption" color="text.secondary">
          {label}
        </Typography>
      </CardContent>
    </Card>
  );
}

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

export function ChildrenProgressView() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const childId = searchParams.get('child');

  const [progress, setProgress] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  const load = useCallback(async () => {
    if (!childId) return;
    try {
      setLoading(true);
      const data = await getChildProgress(childId);
      setProgress(data);
    } catch (e) {
      setError(e?.response?.data?.detail || e?.message || 'Ошибка загрузки прогресса');
    } finally {
      setLoading(false);
    }
  }, [childId]);

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

  if (!childId) {
    return (
      <DashboardContent>
        <CustomBreadcrumbs
          heading="Прогресс ребёнка"
          links={[
            { name: 'Главная', href: paths.dashboard.root },
            { name: 'Мои дети', href: paths.dashboard.children },
            { name: 'Прогресс' },
          ]}
          sx={{ mb: 3 }}
        />
        <Box sx={{ textAlign: 'center', py: 8 }}>
          <Typography variant="body1" color="text.secondary">
            Выберите ребёнка для просмотра прогресса
          </Typography>
          <Button
            variant="outlined"
            sx={{ mt: 2 }}
            onClick={() => router.push(paths.dashboard.children)}
          >
            К списку детей
          </Button>
        </Box>
      </DashboardContent>
    );
  }

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

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

      {loading ? (
        <Box sx={{ display: 'flex', justifyContent: 'center', py: 8 }}>
          <CircularProgress />
        </Box>
      ) : progress ? (
        <Stack direction="row" flexWrap="wrap" gap={2}>
          <StatCard
            label="Завершено занятий"
            value={progress.completed_lessons}
            icon="eva:checkmark-circle-outline"
            color="success"
          />
          <StatCard
            label="Выполнено заданий"
            value={progress.completed_homework}
            icon="eva:book-outline"
            color="primary"
          />
          {progress.attendance_rate !== undefined && (
            <StatCard
              label="Посещаемость"
              value={`${Math.round(progress.attendance_rate)}%`}
              icon="eva:calendar-outline"
              color="info"
            />
          )}
          {progress.avg_grade !== undefined && progress.avg_grade > 0 && (
            <StatCard
              label="Средняя оценка"
              value={progress.avg_grade}
              icon="eva:star-outline"
              color="warning"
            />
          )}
        </Stack>
      ) : (
        <Typography variant="body1" color="text.secondary">
          Нет данных о прогрессе
        </Typography>
      )}
    </DashboardContent>
  );
}
