'use client';

import { useState, useEffect } from 'react';

import Box from '@mui/material/Box';
import Tab from '@mui/material/Tab';
import Tabs from '@mui/material/Tabs';
import Chip from '@mui/material/Chip';
import Stack from '@mui/material/Stack';
import Alert from '@mui/material/Alert';
import Button from '@mui/material/Button';
import Drawer from '@mui/material/Drawer';
import Rating from '@mui/material/Rating';
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 {
  getMySubmission,
  gradeSubmission,
  deleteSubmission,
  checkSubmissionWithAi,
  getHomeworkSubmissions,
  returnSubmissionForRevision,
} from 'src/utils/homework-api';

import { CONFIG } from 'src/config-global';

import { Iconify } from 'src/components/iconify';

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

function fileUrl(href) {
  if (!href) return '';
  if (href.startsWith('http://') || href.startsWith('https://')) return href;
  const base = CONFIG.site.serverUrl?.replace('/api', '') || '';
  return base + (href.startsWith('/') ? href : `/${href}`);
}

function formatDateTime(s) {
  if (!s) return '—';
  const d = new Date(s);
  return Number.isNaN(d.getTime())
    ? '—'
    : d.toLocaleString('ru-RU', {
        day: 'numeric',
        month: 'long',
        year: 'numeric',
        hour: '2-digit',
        minute: '2-digit',
      });
}

// ----------------------------------------------------------------------
// File list component

function FileList({ files, singleUrl, label }) {
  const items = [];
  if (singleUrl) items.push({ label: label || 'Файл', url: fileUrl(singleUrl) });
  (files ?? []).forEach((f) => {
    if (f.file) items.push({ label: f.filename || 'Файл', url: fileUrl(f.file) });
  });

  if (!items.length) return null;
  return (
    <Stack spacing={1}>
      {items.map(({ label: l, url }, i) => (
        <Button
          key={i}
          component="a"
          href={url}
          target="_blank"
          rel="noopener noreferrer"
          variant="outlined"
          size="small"
          startIcon={<Iconify icon="eva:download-outline" />}
          sx={{ justifyContent: 'flex-start' }}
        >
          {l}
        </Button>
      ))}
    </Stack>
  );
}

// ----------------------------------------------------------------------
// Client view — own submission

function ClientSubmissionSection({ homework, childId, onOpenSubmit, onReload }) {
  const [submission, setSubmission] = useState(undefined); // undefined = loading
  const [deleting, setDeleting] = useState(false);
  const [error, setError] = useState(null);

  useEffect(() => {
    getMySubmission(homework.id, childId ? { child_id: childId } : undefined)
      .then(setSubmission)
      .catch(() => setSubmission(null));
  }, [homework.id, childId]);

  const handleDelete = async () => {
    try {
      setDeleting(true);
      await deleteSubmission(submission.id);
      setSubmission(null);
      onReload();
    } catch (e) {
      setError(e?.response?.data?.detail || e?.message || 'Ошибка');
    } finally {
      setDeleting(false);
    }
  };

  if (submission === undefined) return <CircularProgress size={24} />;

  if (!submission) {
    return (
      <Box>
        <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
          Вы ещё не сдали задание.
        </Typography>
        {homework.status === 'published' && !childId && (
          <Button variant="contained" onClick={onOpenSubmit}>
            Сдать ДЗ
          </Button>
        )}
      </Box>
    );
  }

  return (
    <Stack spacing={2}>
      <Stack direction="row" alignItems="center" spacing={1}>
        <Chip
          label={submission.status === 'returned' ? 'На доработке' : submission.status === 'checked' ? 'Проверено' : 'На проверке'}
          color={submission.status === 'returned' ? 'warning' : submission.status === 'checked' ? 'success' : 'info'}
          size="small"
        />
        <Typography variant="caption" color="text.secondary">
          {formatDateTime(submission.submitted_at)}
        </Typography>
      </Stack>

      {submission.content && (
        <Box sx={{ p: 2, bgcolor: 'background.neutral', borderRadius: 1 }}>
          <Typography variant="body2" sx={{ whiteSpace: 'pre-wrap' }}>
            {submission.content}
          </Typography>
        </Box>
      )}

      <FileList
        singleUrl={submission.attachment}
        files={(submission.files ?? []).filter((f) => f.file_type === 'submission')}
        label="Решение"
      />

      {submission.score != null && (
        <Stack spacing={0.5}>
          <Typography variant="subtitle2">Оценка</Typography>
          <Rating value={submission.score} max={5} readOnly />
          <Typography variant="body2" color="text.secondary">
            {submission.score} / {homework.max_score || 5}
          </Typography>
        </Stack>
      )}

      {submission.feedback && (
        <Box>
          <Typography variant="subtitle2" sx={{ mb: 1 }}>
            Комментарий ментора
          </Typography>
          {submission.feedback_html ? (
            <Box
              sx={{ p: 2, bgcolor: 'background.neutral', borderRadius: 1 }}
              dangerouslySetInnerHTML={{ __html: submission.feedback_html }}
            />
          ) : (
            <Box sx={{ p: 2, bgcolor: 'background.neutral', borderRadius: 1 }}>
              <Typography variant="body2" sx={{ whiteSpace: 'pre-wrap' }}>
                {submission.feedback}
              </Typography>
            </Box>
          )}
        </Box>
      )}

      {error && <Alert severity="error">{error}</Alert>}

      {submission.status !== 'checked' && !childId && (
        <Stack direction="row" spacing={1}>
          <Button variant="outlined" color="error" size="small" onClick={handleDelete} disabled={deleting}>
            {deleting ? 'Удаление...' : 'Удалить и переотправить'}
          </Button>
        </Stack>
      )}
    </Stack>
  );
}

// ----------------------------------------------------------------------
// Mentor submission item

function MentorSubmissionItem({ submission, homework, onReload }) {
  const [score, setScore] = useState(submission.score != null ? submission.score : '');
  const [feedback, setFeedback] = useState('');
  const [returnFeedback, setReturnFeedback] = useState('');
  const [showReturnForm, setShowReturnForm] = useState(false);
  const [grading, setGrading] = useState(false);
  const [returning, setReturning] = useState(false);
  const [aiChecking, setAiChecking] = useState(false);
  const [error, setError] = useState(null);

  const {student} = submission;

  const handleGrade = async () => {
    if (!score && score !== 0) {
      setError('Укажите оценку');
      return;
    }
    try {
      setGrading(true);
      setError(null);
      await gradeSubmission(submission.id, { score: Number(score), feedback: feedback.trim() });
      onReload();
    } catch (e) {
      setError(e?.response?.data?.detail || e?.message || 'Ошибка');
    } finally {
      setGrading(false);
    }
  };

  const handleReturn = async () => {
    if (!returnFeedback.trim()) {
      setError('Укажите причину возврата');
      return;
    }
    try {
      setReturning(true);
      setError(null);
      await returnSubmissionForRevision(submission.id, returnFeedback.trim());
      onReload();
    } catch (e) {
      setError(e?.response?.data?.detail || e?.message || 'Ошибка');
    } finally {
      setReturning(false);
    }
  };

  const handleAiCheck = async () => {
    try {
      setAiChecking(true);
      setError(null);
      const result = await checkSubmissionWithAi(submission.id);
      if (result.ai_score != null) setScore(result.ai_score);
      if (result.ai_feedback) setFeedback(result.ai_feedback);
      onReload();
    } catch (e) {
      setError(e?.response?.data?.detail || e?.message || 'Ошибка AI-проверки');
    } finally {
      setAiChecking(false);
    }
  };

  const isChecked = submission.status === 'checked';
  const isReturned = submission.status === 'returned';

  return (
    <Box
      sx={{
        p: 2,
        borderRadius: 2,
        border: '1px solid',
        borderColor: 'divider',
        bgcolor: 'background.neutral',
      }}
    >
      <Stack direction="row" alignItems="center" justifyContent="space-between" sx={{ mb: 1.5 }}>
        <Typography variant="subtitle2">
          {student?.first_name} {student?.last_name}
        </Typography>
        <Chip
          label={isChecked ? 'Проверено' : isReturned ? 'На доработке' : 'На проверке'}
          color={isChecked ? 'success' : isReturned ? 'warning' : 'info'}
          size="small"
        />
      </Stack>

      {submission.content && (
        <Box sx={{ mb: 1.5, p: 1.5, bgcolor: 'background.paper', borderRadius: 1 }}>
          <Typography variant="body2" sx={{ whiteSpace: 'pre-wrap' }}>
            {submission.content}
          </Typography>
        </Box>
      )}

      <FileList
        singleUrl={submission.attachment}
        files={(submission.files ?? []).filter((f) => f.file_type === 'submission')}
        label="Решение"
      />

      {/* AI draft info */}
      {submission.ai_score != null && !isChecked && (
        <Box sx={{ mt: 1.5, p: 1.5, bgcolor: 'info.lighter', borderRadius: 1 }}>
          <Typography variant="caption" color="info.main" fontWeight={600}>
            Черновик от ИИ: оценка {submission.ai_score}/5
          </Typography>
          {submission.ai_feedback && (
            <Typography variant="body2" sx={{ mt: 0.5, whiteSpace: 'pre-wrap', fontSize: 12 }}>
              {submission.ai_feedback}
            </Typography>
          )}
        </Box>
      )}

      {error && (
        <Alert severity="error" sx={{ mt: 1 }}>
          {error}
        </Alert>
      )}

      {/* Grade form */}
      {!isChecked && !showReturnForm && (
        <Stack spacing={1.5} sx={{ mt: 2 }}>
          <Stack direction="row" alignItems="center" spacing={2}>
            <Typography variant="body2" color="text.secondary">
              Оценка:
            </Typography>
            <Rating
              value={Number(score) || 0}
              max={homework.max_score || 5}
              onChange={(_, v) => setScore(v ?? '')}
            />
          </Stack>
          <TextField
            label="Комментарий"
            multiline
            rows={2}
            value={feedback}
            onChange={(e) => setFeedback(e.target.value)}
            size="small"
            fullWidth
          />
          <Stack direction="row" spacing={1} flexWrap="wrap">
            <Button
              variant="contained"
              size="small"
              onClick={handleGrade}
              disabled={grading || aiChecking}
              startIcon={grading ? <Iconify icon="svg-spinners:8-dots-rotate" /> : null}
            >
              {grading ? 'Сохранение...' : 'Выставить оценку'}
            </Button>
            <Button
              variant="outlined"
              size="small"
              color="warning"
              onClick={() => setShowReturnForm(true)}
              disabled={grading || aiChecking}
            >
              Вернуть на доработку
            </Button>
            <Button
              variant="outlined"
              size="small"
              color="info"
              onClick={handleAiCheck}
              disabled={grading || aiChecking}
              startIcon={
                aiChecking ? (
                  <Iconify icon="svg-spinners:8-dots-rotate" />
                ) : (
                  <Iconify icon="solar:magic-stick-3-bold" />
                )
              }
            >
              {aiChecking ? 'Проверка...' : 'ИИ-проверка'}
            </Button>
          </Stack>
        </Stack>
      )}

      {/* Return form */}
      {showReturnForm && (
        <Stack spacing={1.5} sx={{ mt: 2 }}>
          <TextField
            label="Причина возврата"
            multiline
            rows={2}
            value={returnFeedback}
            onChange={(e) => setReturnFeedback(e.target.value)}
            size="small"
            fullWidth
          />
          <Stack direction="row" spacing={1}>
            <Button
              variant="contained"
              color="warning"
              size="small"
              onClick={handleReturn}
              disabled={returning}
            >
              {returning ? 'Отправка...' : 'Вернуть'}
            </Button>
            <Button
              variant="outlined"
              size="small"
              onClick={() => setShowReturnForm(false)}
              disabled={returning}
            >
              Отмена
            </Button>
          </Stack>
        </Stack>
      )}
    </Box>
  );
}

// ----------------------------------------------------------------------
// Main drawer

export function HomeworkDetailsDrawer({ open, homework, userRole, childId, onClose, onSuccess, onOpenSubmit, onOpenEdit }) {
  const [submissions, setSubmissions] = useState([]);
  const [subsLoading, setSubsLoading] = useState(false);
  const [tab, setTab] = useState(0);
  const isMentor = userRole === 'mentor';

  const loadSubmissions = () => {
    if (!homework || !isMentor) return;
    setSubsLoading(true);
    getHomeworkSubmissions(homework.id)
      .then(setSubmissions)
      .catch(() => setSubmissions([]))
      .finally(() => setSubsLoading(false));
  };

  useEffect(() => {
    if (open && homework && isMentor) {
      loadSubmissions();
      setTab(0);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open, homework?.id, isMentor]);

  if (!homework) return null;

  const assignmentFiles = (homework.files ?? []).filter((f) => f.file_type === 'assignment');

  return (
    <Drawer
      anchor="right"
      open={open}
      onClose={onClose}
      PaperProps={{ sx: { width: { xs: '100%', sm: 560 } } }}
    >
      {/* Header */}
      <Stack
        direction="row"
        alignItems="flex-start"
        justifyContent="space-between"
        sx={{ px: 3, py: 2.5, borderBottom: '1px solid', borderColor: 'divider' }}
      >
        <Box sx={{ flex: 1, pr: 2 }}>
          <Typography variant="h6">{homework.title}</Typography>
          {homework.deadline && (
            <Typography variant="caption" color={homework.is_overdue ? 'error' : 'text.secondary'}>
              Дедлайн: {formatDateTime(homework.deadline)}
              {homework.is_overdue && ' • Просрочено'}
            </Typography>
          )}
        </Box>
        <IconButton onClick={onClose} sx={{ flexShrink: 0 }}>
          <Iconify icon="mingcute:close-line" />
        </IconButton>
      </Stack>

      {/* Tabs for mentor */}
      {isMentor && (
        <Tabs value={tab} onChange={(_, v) => setTab(v)} sx={{ px: 3, borderBottom: '1px solid', borderColor: 'divider' }}>
          <Tab label="Задание" />
          <Tab label={`Решения (${homework.total_submissions || submissions.length})`} />
        </Tabs>
      )}

      <Box sx={{ p: 3, overflowY: 'auto', flex: 1 }}>
        {/* Assignment tab / single view */}
        {(!isMentor || tab === 0) && (
          <Stack spacing={3}>
            {homework.description && (
              <Box>
                <Typography variant="subtitle2" sx={{ mb: 1 }}>
                  Описание
                </Typography>
                <Typography variant="body2" sx={{ whiteSpace: 'pre-wrap' }}>
                  {homework.description}
                </Typography>
              </Box>
            )}

            {(homework.attachment || assignmentFiles.length > 0 || homework.attachment_url) && (
              <Box>
                <Typography variant="subtitle2" sx={{ mb: 1 }}>
                  Файлы задания
                </Typography>
                <FileList
                  singleUrl={homework.attachment}
                  files={assignmentFiles}
                  label="Файл задания"
                />
                {homework.attachment_url && (
                  <Button
                    component="a"
                    href={homework.attachment_url}
                    target="_blank"
                    rel="noopener noreferrer"
                    variant="outlined"
                    size="small"
                    startIcon={<Iconify icon="eva:external-link-outline" />}
                    sx={{ mt: 1, justifyContent: 'flex-start' }}
                  >
                    Ссылка на материал
                  </Button>
                )}
              </Box>
            )}

            {isMentor && homework.fill_later && (
              <Alert
                severity="warning"
                action={
                  <Button size="small" onClick={() => { onClose(); onOpenEdit(homework); }}>
                    Заполнить
                  </Button>
                }
              >
                Задание ожидает заполнения
              </Alert>
            )}

            {isMentor && (
              <Stack spacing={1}>
                <Typography variant="caption" color="text.secondary">
                  Статус: {homework.status === 'published' ? 'Опубликовано' : homework.status === 'draft' ? 'Черновик' : 'Архив'}
                </Typography>
                {homework.average_score > 0 && (
                  <Typography variant="caption" color="text.secondary">
                    Средняя оценка: {homework.average_score.toFixed(1)} / 5
                  </Typography>
                )}
              </Stack>
            )}

            {/* Client submission section */}
            {(userRole === 'client' || userRole === 'parent') && homework.status === 'published' && (
              <>
                <Divider />
                <Box>
                  <Typography variant="subtitle1" sx={{ mb: 2 }}>
                    Ваше решение
                  </Typography>
                  <ClientSubmissionSection
                    homework={homework}
                    childId={userRole === 'parent' ? childId : null}
                    onOpenSubmit={onOpenSubmit}
                    onReload={onSuccess}
                  />
                </Box>
              </>
            )}
          </Stack>
        )}

        {/* Submissions tab for mentor */}
        {isMentor && tab === 1 && (
          <Stack spacing={2}>
            {subsLoading ? (
              <Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}>
                <CircularProgress />
              </Box>
            ) : submissions.length === 0 ? (
              <Typography variant="body2" color="text.secondary">
                Нет решений
              </Typography>
            ) : (
              submissions.map((sub) => (
                <MentorSubmissionItem
                  key={sub.id}
                  submission={sub}
                  homework={homework}
                  onReload={() => {
                    loadSubmissions();
                    onSuccess();
                  }}
                />
              ))
            )}
          </Stack>
        )}
      </Box>
    </Drawer>
  );
}
