'use client';

import { useState, useEffect, useMemo, useCallback } from 'react';
import Box from '@mui/material/Box';
import Card from '@mui/material/Card';
import Button from '@mui/material/Button';
import Avatar from '@mui/material/Avatar';
import Stack from '@mui/material/Stack';
import { useTheme } from '@mui/material/styles';
import { cardClasses } from '@mui/material/Card';
import Typography from '@mui/material/Typography';
import CircularProgress from '@mui/material/CircularProgress';

import { CONFIG } from 'src/config-global';
import { varAlpha } from 'src/theme/styles';
import { DashboardContent } from 'src/layouts/dashboard';
import { useAuthContext } from 'src/auth/hooks';
import { fDateTime } from 'src/utils/format-time';
import { fNumber } from 'src/utils/format-number';
import { AvatarShape } from 'src/assets/illustrations';
import { Image } from 'src/components/image';

// Статический импорт API
import { getMentorDashboard, getMentorIncome } from 'src/utils/dashboard-api';

import { CourseProgress } from '../course-progress';
import { CourseMyAccount } from '../course-my-account';
import { CourseHoursSpent } from '../course-hours-spent';
import { CourseWidgetSummary } from '../course-widget-summary';

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

export function OverviewCourseView() {
  const theme = useTheme();
  const { user } = useAuthContext();
  
  const [stats, setStats] = useState(null);
  const [incomeStats, setIncomeStats] = useState(null);
  const [loading, setLoading] = useState(true);
  const [period, setPeriod] = useState('Месяц');

  // Фильтр активных уроков
  const activeLessons = useMemo(() => {
    const upcoming = stats?.upcoming_lessons || [];
    const NOW = new Date();
    return upcoming.filter((lesson) => {
      const startTime = new Date(lesson.start_time);
      const diffInMinutes = (startTime.getTime() - NOW.getTime()) / 60000;
      return diffInMinutes <= 10 && diffInMinutes > -60;
    });
  }, [stats]);

  // Последние сданные ДЗ
  const recentSubmissions = stats?.recent_submissions || [];

  // Данные для графиков
  const prepareChart = useCallback((dataKey, label) => {
    if (!incomeStats?.chart_data) return null;
    const data = incomeStats.chart_data;
    const categories = data.map(d => d.date);
    const seriesData = data.map(d => Number(d[dataKey] || 0));

    const options = ['День', 'Неделя', 'Месяц'];
    return {
      series: options.map(opt => ({
        name: opt,
        data: [{ name: label, categories, data: seriesData }]
      }))
    };
  }, [incomeStats]);

  const incomeChart = useMemo(() => prepareChart('income', 'Сумма'), [prepareChart]);
  const lessonsChart = useMemo(() => prepareChart('lessons', 'Занятия'), [prepareChart]);

  const fetchData = useCallback(async (currentPeriod) => {
    try {
      const periodMap = { 'День': 'day', 'Неделя': 'week', 'Месяц': 'month' };
      const [dData, iData] = await Promise.all([
        getMentorDashboard(),
        getMentorIncome(periodMap[currentPeriod] || 'month')
      ]);
      if (dData) setStats(dData);
      if (iData) setIncomeStats(iData);
    } catch (err) {
      console.error('Fetch error:', err);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchData(period);
  }, [period, fetchData]);

  if (loading && !stats) {
    return (
      <Box sx={{ display: 'flex', height: '80vh', alignItems: 'center', justifyContent: 'center' }}>
        <CircularProgress />
      </Box>
    );
  }

  // Форматирование сумм для виджетов
  const revenueDisplay = `${fNumber(stats?.summary?.revenue_this_month || 0)} / ${fNumber(stats?.summary?.total_revenue || 0)} ₽`;
  const lessonsDisplay = `${stats?.summary?.lessons_this_month || 0} / ${stats?.summary?.total_lessons || 0}`;

  // Общий рендер карточки (урок или ДЗ)
  const renderCard = (item, type) => {
    const isLesson = type === 'lesson';
    const title = isLesson ? item.title : item.homework?.title;
    const subTitle = isLesson ? item.client?.name : item.student?.name;
    const avatar = isLesson ? item.client?.avatar : item.student?.avatar;
    const timeLabel = isLesson ? 'Начало:' : 'Сдано:';
    const timeValue = isLesson ? fDateTime(item.start_time) : fDateTime(item.submitted_at);
    const buttonLabel = isLesson ? 'Подключиться' : 'Проверить';
    const link = isLesson ? `/dashboard/room/${item.id}` : `/dashboard/homework/submissions/${item.id}`;

    return (
      <Card 
        key={item.id} 
        sx={{ 
          textAlign: 'center', 
          bgcolor: 'background.paper',
          boxShadow: (theme) => theme.customShadows.z8,
          overflow: 'hidden',
          borderRadius: 2,
          mb: 2
        }}
      >
        <Box sx={{ position: 'relative' }}>
          <AvatarShape sx={{ left: 0, right: 0, zIndex: 10, mx: 'auto', bottom: -26, position: 'absolute', color: 'background.paper' }} />
          <Avatar alt={subTitle} src={avatar || ''} sx={{ width: 64, height: 64, zIndex: 11, left: 0, right: 0, bottom: -32, mx: 'auto', position: 'absolute' }} />
          <Image src={`${CONFIG.site.basePath}/assets/background/background-1.jpg`} alt="Banner" ratio="16/9" slotProps={{ overlay: { background: (theme) => varAlpha(theme.vars.palette.grey['900Channel'], 0.48) } }} />
        </Box>

        <Box sx={{ mt: 5, px: 2, pb: 2 }}>
          <Typography variant="subtitle1" noWrap>{title}</Typography>
          <Typography variant="body2" sx={{ color: 'text.secondary', mb: 2 }} noWrap>
            {isLesson ? `Ученик: ${subTitle || '---'}` : `Студент: ${subTitle || '---'}`}
          </Typography>
          <Stack direction="row" alignItems="center" justifyContent="center" spacing={1} sx={{ mb: 2, p: 1, bgcolor: 'background.neutral', borderRadius: 1 }}>
             <Typography variant="caption" sx={{ color: 'text.secondary' }}>{timeLabel}</Typography>
             <Typography variant="subtitle2">{timeValue}</Typography>
          </Stack>
          <Button fullWidth variant="soft" color={isLesson ? "primary" : "info"} href={link}>{buttonLabel}</Button>
        </Box>
      </Card>
    );
  };

  return (
    <DashboardContent
      maxWidth={false}
      disablePadding
      sx={{ borderTop: { lg: `solid 1px ${varAlpha(theme.vars.palette.grey['500Channel'], 0.12)}` } }}
    >
      <Box sx={{ display: 'flex', flex: '1 1 auto', flexDirection: { xs: 'column', lg: 'row' } }}>
        {/* ЛЕВАЯ ЧАСТЬ */}
        <Box sx={{ gap: 3, display: 'flex', flex: '1 1 auto', flexDirection: 'column', px: { xs: 2, sm: 3, xl: 5 }, py: 3, borderRight: { lg: `solid 1px ${varAlpha(theme.vars.palette.grey['500Channel'], 0.12)}` } }}>
          <Box sx={{ mb: 2 }}>
            <Typography variant="h4" sx={{ mb: 1 }}>Привет, {user?.first_name || 'Ментор'}! 🦾</Typography>
            <Typography sx={{ color: 'text.secondary' }}>Ваша активность и доходы.</Typography>
          </Box>

          <Box sx={{ gap: 3, display: 'grid', gridTemplateColumns: { xs: 'repeat(1, 1fr)', md: 'repeat(3, 1fr)' } }}>
            <CourseWidgetSummary title="Ученики" total={Number(stats?.summary?.total_clients || 0)} icon={`${CONFIG.site.basePath}/assets/icons/courses/ic-courses-progress.svg`} />
            <CourseWidgetSummary title="Занятий на неделе" total={Number(stats?.summary?.lessons_this_week || 0)} color="info" icon={`${CONFIG.site.basePath}/assets/icons/courses/ic-courses-certificates.svg`} />
            <CourseWidgetSummary title="На проверку" total={Number(stats?.summary?.pending_submissions || 0)} color="error" icon={`${CONFIG.site.basePath}/assets/icons/courses/ic-courses-completed.svg`} />
          </Box>

          <Box sx={{ gap: 3, display: 'grid', gridTemplateColumns: { xs: 'repeat(1, 1fr)', md: 'repeat(2, 1fr)' } }}>
            <Stack spacing={3}>
              <CourseWidgetSummary title="Доход (мес / всего)" total={revenueDisplay} color="success" icon={`${CONFIG.site.basePath}/assets/icons/glass/ic-glass-bag.svg`} />
              {incomeChart && <CourseHoursSpent title="Статистика дохода" value={period} chart={{ ...incomeChart, colors: [theme.palette.success.main], options: { tooltip: { y: { formatter: (val) => `${val} ₽` } } } }} onValueChange={(val) => setPeriod(val)} />}
            </Stack>
            <Stack spacing={3}>
              <CourseWidgetSummary title="Занятия (мес / всего)" total={lessonsDisplay} color="warning" icon={`${CONFIG.site.basePath}/assets/icons/glass/ic-glass-buy.svg`} />
              {lessonsChart && <CourseHoursSpent title="Статистика занятий" value={period} chart={{ ...lessonsChart, colors: [theme.palette.warning.main], options: { tooltip: { y: { formatter: (val) => `${val} занятий` } } } }} onValueChange={(val) => setPeriod(val)} />}
            </Stack>
          </Box>

          <CourseProgress title="План по урокам" chart={{ series: [{ label: 'Всего', value: Number(stats?.summary?.total_lessons || 1) }, { label: 'Завершено', value: Number(stats?.summary?.completed_lessons || 0) }] }} />
        </Box>

        {/* ПРАВАЯ ЧАСТЬ */}
        <Box sx={{ width: 1, display: 'flex', flexDirection: 'column', px: { xs: 2, sm: 3, xl: 5 }, pt: { lg: 8, xl: 10 }, pb: { xs: 8, xl: 10 }, flexShrink: 0, gap: 5, maxWidth: { lg: 320, xl: 360 }, bgcolor: { lg: 'background.neutral' } }}>
          <Box sx={{ px: { lg: 0 }, [`& .${cardClasses.root}`]: { p: 0, boxShadow: 'none', bgcolor: 'transparent' } }}>
             <CourseMyAccount user={user} />
          </Box>

          {/* Активные уроки */}
          <Stack spacing={2}>
            <Typography variant="h6">Активные уроки</Typography>
            {activeLessons.length > 0 ? activeLessons.slice(0, 2).map((l) => renderCard(l, 'lesson')) : (
              <Typography variant="body2" sx={{ color: 'text.secondary', textAlign: 'center', py: 2 }}>Нет текущих уроков</Typography>
            )}
          </Stack>

          {/* Сданные ДЗ */}
          <Stack spacing={2}>
            <Typography variant="h6">Проверка ДЗ</Typography>
            {recentSubmissions.length > 0 ? recentSubmissions.slice(0, 2).map((s) => renderCard(s, 'homework')) : (
              <Typography variant="body2" sx={{ color: 'text.secondary', textAlign: 'center', py: 2 }}>Нет новых работ</Typography>
            )}
          </Stack>
        </Box>
      </Box>
    </DashboardContent>
  );
}
