'use client';

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

import Box from '@mui/material/Box';
import Chip from '@mui/material/Chip';
import Stack from '@mui/material/Stack';
import Paper from '@mui/material/Paper';
import Button from '@mui/material/Button';
import Drawer from '@mui/material/Drawer';
import Divider from '@mui/material/Divider';
import TextField from '@mui/material/TextField';
import Typography from '@mui/material/Typography';
import IconButton from '@mui/material/IconButton';
import CircularProgress from '@mui/material/CircularProgress';

import { Iconify } from 'src/components/iconify';
import { DashboardContent } from 'src/layouts/dashboard';
import { useAuthContext } from 'src/auth/hooks';
import { getLessons, completeLesson } from 'src/utils/dashboard-api';

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

function getSubjectName(lesson) {
  if (typeof lesson.subject === 'string') return lesson.subject;
  if (lesson.subject?.name) return lesson.subject.name;
  return lesson.subject_name || 'Занятие';
}

function getClientName(lesson) {
  if (typeof lesson.client === 'object' && lesson.client?.user) {
    return `${lesson.client.user.first_name} ${lesson.client.user.last_name}`;
  }
  return lesson.client_name || 'Студент';
}

function formatDate(s) {
  return new Date(s).toLocaleDateString('ru-RU', { day: 'numeric', month: 'long', year: 'numeric' });
}

function formatTime(s) {
  return new Date(s).toLocaleTimeString('ru-RU', { hour: '2-digit', minute: '2-digit' });
}

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

function FeedbackDrawer({ open, lesson, onClose, onSuccess }) {
  const [form, setForm] = useState({ mentor_grade: '', school_grade: '', mentor_notes: '' });
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  useEffect(() => {
    if (open && lesson) {
      setForm({
        mentor_grade: lesson.mentor_grade?.toString() || '',
        school_grade: lesson.school_grade?.toString() || '',
        mentor_notes: lesson.mentor_notes || '',
      });
      setError(null);
    }
  }, [open, lesson]);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError(null);
    setLoading(true);
    try {
      await completeLesson(
        lesson.id,
        form.mentor_notes.trim(),
        form.mentor_grade ? parseInt(form.mentor_grade, 10) : undefined,
        form.school_grade ? parseInt(form.school_grade, 10) : undefined,
      );
      onSuccess();
      onClose();
    } catch (err) {
      setError(err?.response?.data?.detail || err?.message || 'Ошибка сохранения');
    } finally {
      setLoading(false);
    }
  };

  return (
    <Drawer anchor="right" open={open} onClose={loading ? undefined : onClose} PaperProps={{ sx: { width: { xs: '100%', sm: 480 } } }}>
      <Stack direction="row" alignItems="center" justifyContent="space-between" px={3} py={2} borderBottom="1px solid" borderColor="divider">
        <Box>
          <Typography variant="h6">Обратная связь</Typography>
          {lesson && (
            <Typography variant="caption" color="text.secondary">
              {lesson.title} — {getSubjectName(lesson)}
            </Typography>
          )}
        </Box>
        <IconButton onClick={onClose} disabled={loading}>
          <Iconify icon="mingcute:close-line" />
        </IconButton>
      </Stack>

      {lesson && (
        <Box component="form" onSubmit={handleSubmit} sx={{ p: 3, overflowY: 'auto', flex: 1, display: 'flex', flexDirection: 'column', gap: 2 }}>
          <Paper sx={{ p: 2, borderRadius: 2, bgcolor: 'primary.lighter' }}>
            <Stack direction="row" flexWrap="wrap" gap={2}>
              <Box>
                <Typography variant="caption" color="text.secondary">Студент</Typography>
                <Typography variant="body2" fontWeight={500}>{getClientName(lesson)}</Typography>
              </Box>
              <Box>
                <Typography variant="caption" color="text.secondary">Дата</Typography>
                <Typography variant="body2" fontWeight={500}>{formatDate(lesson.start_time)}</Typography>
              </Box>
              <Box>
                <Typography variant="caption" color="text.secondary">Время</Typography>
                <Typography variant="body2" fontWeight={500}>{formatTime(lesson.start_time)} — {formatTime(lesson.end_time)}</Typography>
              </Box>
            </Stack>
          </Paper>

          <Typography variant="subtitle2">Оценки</Typography>
          <Stack direction="row" spacing={2}>
            <TextField
              label="Оценка за занятие (1–5)"
              type="number"
              inputProps={{ min: 1, max: 5 }}
              value={form.mentor_grade}
              onChange={(e) => setForm((p) => ({ ...p, mentor_grade: e.target.value }))}
              disabled={loading}
              size="small"
              fullWidth
            />
            <TextField
              label="Оценка в школе (1–5)"
              type="number"
              inputProps={{ min: 1, max: 5 }}
              value={form.school_grade}
              onChange={(e) => setForm((p) => ({ ...p, school_grade: e.target.value }))}
              disabled={loading}
              size="small"
              fullWidth
            />
          </Stack>

          <TextField
            label="Комментарий к занятию"
            multiline
            rows={4}
            value={form.mentor_notes}
            onChange={(e) => setForm((p) => ({ ...p, mentor_notes: e.target.value }))}
            disabled={loading}
            placeholder="Что прошли на занятии, успехи студента, рекомендации..."
          />

          {error && (
            <Typography color="error" variant="body2">
              {error}
            </Typography>
          )}

          <Stack direction="row" spacing={1.5} mt="auto">
            <Button variant="outlined" color="inherit" onClick={onClose} disabled={loading} fullWidth>
              Отмена
            </Button>
            <Button type="submit" variant="contained" disabled={loading} fullWidth>
              {loading ? 'Сохранение...' : 'Сохранить'}
            </Button>
          </Stack>
        </Box>
      )}
    </Drawer>
  );
}

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

function LessonCard({ lesson, onFill }) {
  const hasFeedback = !!(lesson.mentor_grade || lesson.school_grade || lesson.mentor_notes?.trim());

  return (
    <Paper
      sx={{
        p: 2,
        borderRadius: 2,
        cursor: 'pointer',
        transition: 'box-shadow 0.2s',
        '&:hover': { boxShadow: 4 },
      }}
      onClick={onFill}
    >
      <Chip label={getSubjectName(lesson)} size="small" color="primary" variant="soft" sx={{ mb: 1 }} />
      <Typography variant="subtitle2" mb={0.5}>
        {lesson.title}
      </Typography>
      <Typography variant="caption" color="text.secondary" display="flex" alignItems="center" gap={0.5} mb={0.5}>
        <Iconify icon="solar:user-linear" width={14} />
        {getClientName(lesson)}
      </Typography>
      <Typography variant="caption" color="text.secondary" display="flex" alignItems="center" gap={0.5} mb={0.5}>
        <Iconify icon="solar:calendar-linear" width={14} />
        {formatDate(lesson.start_time)}
      </Typography>
      <Typography variant="caption" color="text.secondary" display="flex" alignItems="center" gap={0.5} mb={1.5}>
        <Iconify icon="solar:clock-circle-linear" width={14} />
        {formatTime(lesson.start_time)} — {formatTime(lesson.end_time)}
      </Typography>
      {lesson.mentor_grade != null && (
        <Typography variant="caption" color="primary.main" fontWeight={600} display="block" mb={1}>
          Оценка: {lesson.mentor_grade}/5
        </Typography>
      )}
      <Button
        variant={hasFeedback ? 'soft' : 'contained'}
        size="small"
        fullWidth
        onClick={(e) => { e.stopPropagation(); onFill(); }}
      >
        {hasFeedback ? 'Редактировать' : 'Заполнить'}
      </Button>
    </Paper>
  );
}

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

export function FeedbackView() {
  const { user } = useAuthContext();
  const [lessons, setLessons] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [selected, setSelected] = useState(null);
  const [drawerOpen, setDrawerOpen] = useState(false);

  const load = useCallback(async () => {
    if (user?.role !== 'mentor') return;
    setLoading(true);
    setError(null);
    try {
      const res = await getLessons({ status: 'completed' });
      const list = Array.isArray(res) ? res : res?.results || [];
      setLessons(list.filter((l) => !l.group));
    } catch (err) {
      setError(err?.message || 'Ошибка загрузки');
    } finally {
      setLoading(false);
    }
  }, [user?.role]);

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

  const todoLessons = useMemo(
    () => lessons.filter((l) => !(l.mentor_grade || l.school_grade || l.mentor_notes?.trim())),
    [lessons],
  );
  const doneLessons = useMemo(
    () => lessons.filter((l) => !!(l.mentor_grade || l.school_grade || l.mentor_notes?.trim())),
    [lessons],
  );

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

  return (
    <DashboardContent maxWidth="xl">
      <Typography variant="h4" mb={3}>
        Обратная связь
      </Typography>

      {error && (
        <Typography color="error" mb={2}>
          {error}
        </Typography>
      )}

      {loading ? (
        <Box sx={{ display: 'flex', justifyContent: 'center', py: 8 }}>
          <CircularProgress />
        </Box>
      ) : (
        <Stack direction={{ xs: 'column', md: 'row' }} spacing={3} alignItems="flex-start">
          {/* Ожидают */}
          <Box flex={1} minWidth={0}>
            <Typography variant="subtitle1" fontWeight={700} mb={2}>
              Ожидают {todoLessons.length > 0 ? `(${todoLessons.length})` : ''}
            </Typography>
            <Stack spacing={2}>
              {todoLessons.map((l) => (
                <LessonCard
                  key={l.id}
                  lesson={l}
                  onFill={() => { setSelected(l); setDrawerOpen(true); }}
                />
              ))}
              {todoLessons.length === 0 && (
                <Typography color="text.secondary" variant="body2">
                  Нет занятий, ожидающих обратной связи
                </Typography>
              )}
            </Stack>
          </Box>

          <Divider orientation="vertical" flexItem sx={{ display: { xs: 'none', md: 'block' } }} />

          {/* Заполнено */}
          <Box flex={1} minWidth={0}>
            <Typography variant="subtitle1" fontWeight={700} mb={2}>
              Заполнено {doneLessons.length > 0 ? `(${doneLessons.length})` : ''}
            </Typography>
            <Stack spacing={2}>
              {doneLessons.map((l) => (
                <LessonCard
                  key={l.id}
                  lesson={l}
                  onFill={() => { setSelected(l); setDrawerOpen(true); }}
                />
              ))}
              {doneLessons.length === 0 && (
                <Typography color="text.secondary" variant="body2">
                  Нет завершённых занятий
                </Typography>
              )}
            </Stack>
          </Box>
        </Stack>
      )}

      <FeedbackDrawer
        open={drawerOpen}
        lesson={selected}
        onClose={() => setDrawerOpen(false)}
        onSuccess={load}
      />
    </DashboardContent>
  );
}
