'use client';

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

import Tab from '@mui/material/Tab';
import Box from '@mui/material/Box';
import Tabs from '@mui/material/Tabs';
import Stack from '@mui/material/Stack';
import Paper from '@mui/material/Paper';
import Typography from '@mui/material/Typography';
import CircularProgress from '@mui/material/CircularProgress';
import { DatePicker } from '@mui/x-date-pickers/DatePicker';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import dayjs from 'dayjs';
import 'dayjs/locale/ru';

import { DashboardContent } from 'src/layouts/dashboard';
import { useAuthContext } from 'src/auth/hooks';
import {
  getLast30DaysRange,
  getAnalyticsOverview,
  getAnalyticsStudents,
  getAnalyticsRevenue,
  getAnalyticsGradesByDay,
} from 'src/utils/analytics-api';
import { getMentorIncome } from 'src/utils/dashboard-api';

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

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

const formatCurrency = (v) =>
  new Intl.NumberFormat('ru-RU', { style: 'currency', currency: 'RUB', maximumFractionDigits: 0 }).format(v ?? 0);

function StatCard({ label, value }) {
  return (
    <Paper sx={{ p: 2, borderRadius: 2, flex: 1, minWidth: 120 }}>
      <Typography variant="caption" color="text.secondary" display="block">
        {label}
      </Typography>
      <Typography variant="h6" fontWeight={700} mt={0.5}>
        {value ?? '—'}
      </Typography>
    </Paper>
  );
}

function DateRangeFilter({ value, onChange, disabled }) {
  return (
    <LocalizationProvider dateAdapter={AdapterDayjs} adapterLocale="ru">
      <Stack direction="row" spacing={1} alignItems="center">
        <DatePicker
          label="От"
          value={dayjs(value.start_date)}
          onChange={(d) => d && onChange({ ...value, start_date: d.format('YYYY-MM-DD') })}
          disabled={disabled}
          slotProps={{ textField: { size: 'small', sx: { width: 140 } } }}
        />
        <DatePicker
          label="До"
          value={dayjs(value.end_date)}
          onChange={(d) => d && onChange({ ...value, end_date: d.format('YYYY-MM-DD') })}
          disabled={disabled}
          slotProps={{ textField: { size: 'small', sx: { width: 140 } } }}
        />
      </Stack>
    </LocalizationProvider>
  );
}

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

function IncomeTab() {
  const defaultRange = useMemo(() => getLast30DaysRange(), []);
  const [range, setRange] = useState(defaultRange);
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const d = await getMentorIncome('range', range.start_date, range.end_date);
      setData(d);
    } catch {
      setData(null);
    } finally {
      setLoading(false);
    }
  }, [range]);

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

  const chartOptions = useMemo(() => ({
    chart: { id: 'income-chart', toolbar: { show: false } },
    stroke: { curve: 'smooth', width: 2 },
    colors: ['#7C3AED'],
    dataLabels: { enabled: false },
    xaxis: {
      categories: (data?.chart_data ?? []).map((d) => d.date),
      labels: { style: { fontSize: '11px' } },
    },
    fill: { type: 'gradient', gradient: { opacityFrom: 0.5, opacityTo: 0.05 } },
    tooltip: { y: { formatter: (val) => formatCurrency(val) } },
  }), [data]);

  const series = useMemo(() => [{ name: 'Доход', data: (data?.chart_data ?? []).map((d) => d.income) }], [data]);

  return (
    <Box>
      <Stack direction="row" alignItems="center" justifyContent="space-between" mb={2} flexWrap="wrap" gap={1}>
        <Typography variant="h6">Доход</Typography>
        <DateRangeFilter value={range} onChange={setRange} disabled={loading} />
      </Stack>

      {loading ? (
        <Box sx={{ display: 'flex', justifyContent: 'center', py: 6 }}>
          <CircularProgress />
        </Box>
      ) : (
        <>
          <Stack direction="row" spacing={2} mb={3} flexWrap="wrap">
            <StatCard label="Общий доход" value={formatCurrency(data?.summary?.total_income)} />
            <StatCard label="Средняя цена" value={formatCurrency(data?.summary?.average_lesson_price)} />
            <StatCard label="Занятий" value={data?.summary?.total_lessons} />
          </Stack>

          {(data?.chart_data ?? []).length > 0 ? (
            <ApexChart options={chartOptions} series={series} type="area" height={300} />
          ) : (
            <Typography color="text.secondary" align="center" py={4}>
              Нет данных за период
            </Typography>
          )}

          {(data?.top_lessons ?? []).length > 0 && (
            <Box mt={3}>
              <Typography variant="subtitle1" fontWeight={600} mb={1}>
                Топ занятий по доходам
              </Typography>
              {data.top_lessons.slice(0, 10).map((item, i) => (
                <Stack
                  key={i}
                  direction="row"
                  justifyContent="space-between"
                  py={1}
                  sx={{ borderBottom: '1px solid', borderColor: 'divider' }}
                >
                  <Typography variant="body2">
                    {i + 1}. {item.lesson_title || item.target_name || 'Занятие'}
                  </Typography>
                  <Typography variant="body2" fontWeight={600} color="primary.main">
                    {formatCurrency(item.total_income)}
                  </Typography>
                </Stack>
              ))}
            </Box>
          )}
        </>
      )}
    </Box>
  );
}

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

function LessonsTab() {
  const defaultRange = useMemo(() => getLast30DaysRange(), []);
  const [range, setRange] = useState(defaultRange);
  const [revenue, setRevenue] = useState(null);
  const [overview, setOverview] = useState(null);
  const [loading, setLoading] = useState(true);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const [rev, ov] = await Promise.all([
        getAnalyticsRevenue({ period: 'custom', ...range }).catch(() => null),
        getAnalyticsOverview({ period: 'custom', ...range }).catch(() => null),
      ]);
      setRevenue(rev);
      setOverview(ov);
    } catch {
      setRevenue(null);
      setOverview(null);
    } finally {
      setLoading(false);
    }
  }, [range]);

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

  const byDay = revenue?.by_day ?? [];

  const chartOptions = useMemo(() => ({
    chart: { id: 'lessons-chart', toolbar: { show: false } },
    stroke: { curve: 'smooth', width: 2 },
    colors: ['#7C3AED'],
    dataLabels: { enabled: false },
    xaxis: {
      categories: byDay.map((d) => d.date),
      labels: { style: { fontSize: '11px' } },
    },
    fill: { type: 'gradient', gradient: { opacityFrom: 0.5, opacityTo: 0.05 } },
    tooltip: { y: { formatter: (val) => `${val} занятий` } },
  }), [byDay]);

  const series = useMemo(() => [{ name: 'Занятий', data: byDay.map((d) => d.lessons_count) }], [byDay]);

  return (
    <Box>
      <Stack direction="row" alignItems="center" justifyContent="space-between" mb={2} flexWrap="wrap" gap={1}>
        <Typography variant="h6">Занятия</Typography>
        <DateRangeFilter value={range} onChange={setRange} disabled={loading} />
      </Stack>

      {loading ? (
        <Box sx={{ display: 'flex', justifyContent: 'center', py: 6 }}>
          <CircularProgress />
        </Box>
      ) : (
        <>
          <Stack direction="row" spacing={2} mb={3} flexWrap="wrap">
            <StatCard label="Всего" value={overview?.lessons?.total} />
            <StatCard label="Проведено" value={overview?.lessons?.completed} />
            <StatCard label="Отменено" value={overview?.lessons?.cancelled} />
          </Stack>

          {byDay.length > 0 ? (
            <ApexChart options={chartOptions} series={series} type="area" height={300} />
          ) : (
            <Typography color="text.secondary" align="center" py={4}>
              Нет данных за период
            </Typography>
          )}
        </>
      )}
    </Box>
  );
}

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

function StudentsTab() {
  const defaultRange = useMemo(() => getLast30DaysRange(), []);
  const [range, setRange] = useState(defaultRange);
  const [grades, setGrades] = useState(null);
  const [students, setStudents] = useState(null);
  const [overview, setOverview] = useState(null);
  const [loading, setLoading] = useState(true);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const r = { period: 'custom', ...range };
      const [gr, stu, ov] = await Promise.all([
        getAnalyticsGradesByDay(r).catch(() => null),
        getAnalyticsStudents(r).catch(() => null),
        getAnalyticsOverview(r).catch(() => null),
      ]);
      setGrades(gr);
      setStudents(stu);
      setOverview(ov);
    } catch {
      setGrades(null);
      setStudents(null);
      setOverview(null);
    } finally {
      setLoading(false);
    }
  }, [range]);

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

  const byDay = grades?.by_day ?? [];

  const chartOptions = useMemo(() => ({
    chart: { id: 'grades-chart', toolbar: { show: false } },
    stroke: { curve: 'smooth', width: 2 },
    colors: ['#7C3AED'],
    dataLabels: { enabled: false },
    xaxis: {
      categories: byDay.map((d) => d.date),
      labels: { style: { fontSize: '11px' } },
    },
    yaxis: { min: 0, max: 5 },
    fill: { type: 'gradient', gradient: { opacityFrom: 0.5, opacityTo: 0.05 } },
    tooltip: { y: { formatter: (val) => (val ? `Ср. оценка: ${val}` : '—') } },
  }), [byDay]);

  const series = useMemo(() => [
    { name: 'Средняя оценка', data: byDay.map((d) => d.average_grade ?? 0) },
  ], [byDay]);

  return (
    <Box>
      <Stack direction="row" alignItems="center" justifyContent="space-between" mb={2} flexWrap="wrap" gap={1}>
        <Typography variant="h6">Успех учеников</Typography>
        <DateRangeFilter value={range} onChange={setRange} disabled={loading} />
      </Stack>

      {loading ? (
        <Box sx={{ display: 'flex', justifyContent: 'center', py: 6 }}>
          <CircularProgress />
        </Box>
      ) : (
        <>
          <Stack direction="row" spacing={2} mb={3} flexWrap="wrap">
            <StatCard label="Средняя оценка" value={grades?.summary?.average_grade ?? overview?.grades?.average} />
            <StatCard label="Занятий с оценкой" value={grades?.summary?.graded_lessons} />
            <StatCard label="Активных учеников" value={overview?.students?.active} />
          </Stack>

          {byDay.length > 0 ? (
            <ApexChart options={chartOptions} series={series} type="area" height={300} />
          ) : (
            <Typography color="text.secondary" align="center" py={4}>
              Нет данных за период
            </Typography>
          )}

          {(students?.students ?? []).length > 0 && (
            <Box mt={3}>
              <Typography variant="subtitle1" fontWeight={600} mb={1}>
                Топ ученики
              </Typography>
              {students.students.slice(0, 10).map((s, i) => (
                <Stack
                  key={s.id}
                  direction="row"
                  justifyContent="space-between"
                  py={1}
                  sx={{ borderBottom: '1px solid', borderColor: 'divider' }}
                >
                  <Typography variant="body2">{i + 1}. {s.name}</Typography>
                  <Typography variant="body2" color="text.secondary">
                    {s.lessons_completed} занятий · ср. {s.average_grade}
                  </Typography>
                </Stack>
              ))}
            </Box>
          )}
        </>
      )}
    </Box>
  );
}

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

export function AnalyticsView() {
  const { user } = useAuthContext();
  const [tab, setTab] = useState(0);

  if (user?.role !== 'mentor') {
    return (
      <DashboardContent>
        <Typography color="text.secondary" align="center" mt={8}>
          Аналитика доступна только менторам.
        </Typography>
      </DashboardContent>
    );
  }

  return (
    <DashboardContent maxWidth="lg">
      <Typography variant="h4" mb={3}>
        Аналитика
      </Typography>

      <Paper sx={{ borderRadius: 2 }}>
        <Tabs value={tab} onChange={(_, v) => setTab(v)} sx={{ px: 2, borderBottom: 1, borderColor: 'divider' }}>
          <Tab label="Доход" />
          <Tab label="Занятия" />
          <Tab label="Ученики" />
        </Tabs>

        <Box p={3}>
          {tab === 0 && <IncomeTab />}
          {tab === 1 && <LessonsTab />}
          {tab === 2 && <StudentsTab />}
        </Box>
      </Paper>
    </DashboardContent>
  );
}
