'use client';

import dynamic from 'next/dynamic';
import { useMemo, useState, useEffect, useCallback } from 'react';

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 Select from '@mui/material/Select';
import MenuItem from '@mui/material/MenuItem';
import Typography from '@mui/material/Typography';
import InputLabel from '@mui/material/InputLabel';
import FormControl from '@mui/material/FormControl';
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';

import { useAuthContext } from 'src/auth/hooks';

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

const Chart = dynamic(() => import('react-apexcharts'), { ssr: false });

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

function getDatesInRange(startStr, endStr) {
  const dates = [];
  let d = new Date(startStr);
  const end = new Date(endStr);
  while (d <= end) {
    const y = d.getFullYear();
    const m = String(d.getMonth() + 1).padStart(2, '0');
    const day = String(d.getDate()).padStart(2, '0');
    dates.push(`${y}-${m}-${day}`);
    d = new Date(d.getTime() + 86400000);
  }
  return dates;
}

function formatDateLabel(d) {
  const [, m, day] = d.split('-');
  return `${day}.${m}`;
}

async function getLessons(params) {
  const q = new URLSearchParams();
  if (params?.start_date) q.append('start_date', params.start_date);
  if (params?.end_date) q.append('end_date', params.end_date);
  if (params?.child_id) q.append('child_id', params.child_id);
  const res = await axios.get(`/lessons/lessons/?${q.toString()}`);
  const {data} = res;
  if (Array.isArray(data)) return { results: data };
  return data;
}

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

function StatTile({ label, value, sub, icon, color }) {
  return (
    <Card variant="outlined" sx={{ flex: 1, minWidth: 120 }}>
      <CardContent sx={{ pb: '12px !important' }}>
        <Stack direction="row" alignItems="center" spacing={1} sx={{ mb: 0.5 }}>
          <Box
            sx={{
              width: 36,
              height: 36,
              borderRadius: 1.5,
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              bgcolor: `${color}.lighter`,
            }}
          >
            <Iconify icon={icon} width={20} color={`${color}.main`} />
          </Box>
          <Typography variant="h5" fontWeight="bold">
            {value}
          </Typography>
        </Stack>
        <Typography variant="caption" color="text.secondary" display="block">
          {label}
        </Typography>
        {sub && (
          <Typography variant="caption" color="text.disabled">
            {sub}
          </Typography>
        )}
      </CardContent>
    </Card>
  );
}

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

const TODAY = new Date().toISOString().slice(0, 10);
const WEEK_AGO = new Date(Date.now() - 7 * 86400000).toISOString().slice(0, 10);

export function MyProgressView() {
  const { user } = useAuthContext();
  const isParent = user?.role === 'parent';

  const [startDate, setStartDate] = useState(WEEK_AGO);
  const [endDate, setEndDate] = useState(TODAY);
  const [lessons, setLessons] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [subjects, setSubjects] = useState([]);
  const [selectedSubject, setSelectedSubject] = useState('');

  const childId = isParent
    ? typeof window !== 'undefined'
      ? localStorage.getItem('selected_child_id') || ''
      : ''
    : '';

  const loadSubjects = useCallback(async () => {
    const sixMonthsAgo = new Date(Date.now() - 180 * 86400000).toISOString().slice(0, 10);
    const res = await getLessons({
      start_date: sixMonthsAgo,
      end_date: TODAY,
      ...(childId ? { child_id: childId } : {}),
    });
    const set = new Set();
    (res.results || []).forEach((l) => {
      if (l.subject && typeof l.subject === 'string' && l.subject.trim()) {
        set.add(l.subject.trim());
      }
    });
    const list = Array.from(set).sort();
    setSubjects(list);
    if (list.length > 0) setSelectedSubject(list[0]);
  }, [childId]);

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

  const load = useCallback(async () => {
    try {
      setLoading(true);
      const res = await getLessons({
        start_date: startDate,
        end_date: endDate,
        ...(childId ? { child_id: childId } : {}),
      });
      const filtered = (res.results || []).filter((l) =>
        selectedSubject ? (l.subject || '').trim() === selectedSubject : true
      );
      filtered.sort((a, b) => new Date(a.start_time).getTime() - new Date(b.start_time).getTime());
      setLessons(filtered);
    } catch (e) {
      setError(e?.response?.data?.detail || e?.message || 'Ошибка загрузки');
    } finally {
      setLoading(false);
    }
  }, [startDate, endDate, selectedSubject, childId]);

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

  const stats = useMemo(() => {
    const completed = lessons.filter((l) => l.status === 'completed').length;
    const total = lessons.length;
    const attendanceRate = total > 0 ? Math.round((completed / total) * 100) : 0;
    let sum = 0;
    let count = 0;
    lessons.forEach((l) => {
      if (l.status === 'completed') {
        if (l.mentor_grade != null) {
          sum += l.mentor_grade;
          count += 1;
        }
        if (l.school_grade != null) {
          sum += l.school_grade;
          count += 1;
        }
      }
    });
    const avgGrade = count > 0 ? Math.round((sum / count) * 10) / 10 : 0;
    return { completed, total, attendanceRate, avgGrade };
  }, [lessons]);

  const chartData = useMemo(() => {
    const allDates = getDatesInRange(startDate, endDate);
    const categories = allDates.map(formatDateLabel);
    const byDate = {};
    lessons.forEach((l) => {
      if (l.status !== 'completed') return;
      const key = (l.start_time || '').slice(0, 10);
      if (!key) return;
      byDate[key] = (byDate[key] || 0) + 1;
    });
    const data = allDates.map((d) => byDate[d] || 0);
    const gradeByDate = {};
    lessons.forEach((l) => {
      if (l.status !== 'completed') return;
      const key = (l.start_time || '').slice(0, 10);
      if (!key) return;
      if (l.mentor_grade != null) gradeByDate[key] = l.mentor_grade;
    });
    const grades = allDates.map((d) => gradeByDate[d] ?? null);
    return { categories, attendanceSeries: [{ name: 'Занятия', data }], gradesSeries: [{ name: 'Оценка', data: grades }] };
  }, [lessons, startDate, endDate]);

  const chartOptionsBase = {
    chart: { toolbar: { show: false } },
    stroke: { curve: 'smooth', width: 2 },
    dataLabels: { enabled: false },
    grid: { borderColor: '#f0f0f0' },
    xaxis: { categories: chartData.categories, axisBorder: { show: false }, axisTicks: { show: false } },
  };

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

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

      {/* Controls */}
      <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2} sx={{ mb: 3 }} flexWrap="wrap">
        <FormControl size="small" sx={{ minWidth: 180 }}>
          <InputLabel>Предмет</InputLabel>
          <Select
            value={selectedSubject}
            onChange={(e) => setSelectedSubject(e.target.value)}
            label="Предмет"
            disabled={subjects.length === 0}
          >
            <MenuItem value="">Все предметы</MenuItem>
            {subjects.map((s) => (
              <MenuItem key={s} value={s}>
                {s}
              </MenuItem>
            ))}
          </Select>
        </FormControl>
        <Stack direction="row" spacing={1} alignItems="center">
          <Typography variant="body2" color="text.secondary">
            От:
          </Typography>
          <input
            type="date"
            value={startDate}
            onChange={(e) => setStartDate(e.target.value)}
            style={{ padding: '6px 10px', borderRadius: 8, border: '1px solid #ddd', fontSize: 14 }}
          />
          <Typography variant="body2" color="text.secondary">
            До:
          </Typography>
          <input
            type="date"
            value={endDate}
            onChange={(e) => setEndDate(e.target.value)}
            style={{ padding: '6px 10px', borderRadius: 8, border: '1px solid #ddd', fontSize: 14 }}
          />
        </Stack>
      </Stack>

      {loading ? (
        <Box sx={{ display: 'flex', justifyContent: 'center', py: 8 }}>
          <CircularProgress />
        </Box>
      ) : (
        <Stack spacing={3}>
          {/* Stats row */}
          <Stack direction="row" flexWrap="wrap" gap={2}>
            <StatTile
              label="Занятий проведено"
              value={stats.completed}
              sub={`из ${stats.total}`}
              icon="eva:checkmark-circle-outline"
              color="success"
            />
            <StatTile
              label="Посещаемость"
              value={`${stats.attendanceRate}%`}
              icon="eva:calendar-outline"
              color="primary"
            />
            <StatTile
              label="Средняя оценка"
              value={stats.avgGrade || '—'}
              icon="eva:star-outline"
              color="warning"
            />
          </Stack>

          {/* Attendance chart */}
          {typeof window !== 'undefined' && chartData.categories.length > 0 && (
            <Card variant="outlined">
              <CardContent>
                <Typography variant="subtitle1" sx={{ mb: 2 }}>
                  Посещаемость
                </Typography>
                <Chart
                  type="bar"
                  height={220}
                  series={chartData.attendanceSeries}
                  options={{ ...chartOptionsBase, colors: ['#5BE49B'] }}
                />
              </CardContent>
            </Card>
          )}

          {/* Grades chart */}
          {typeof window !== 'undefined' && chartData.categories.length > 0 && (
            <Card variant="outlined">
              <CardContent>
                <Typography variant="subtitle1" sx={{ mb: 2 }}>
                  Оценки
                </Typography>
                <Chart
                  type="line"
                  height={220}
                  series={chartData.gradesSeries}
                  options={{
                    ...chartOptionsBase,
                    colors: ['#00A76F'],
                    yaxis: { min: 1, max: 5 },
                    markers: { size: 4 },
                  }}
                />
              </CardContent>
            </Card>
          )}

          {lessons.length === 0 && (
            <Typography variant="body1" color="text.secondary">
              Нет занятий за выбранный период
            </Typography>
          )}
        </Stack>
      )}
    </DashboardContent>
  );
}
