'use client';

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

import Box from '@mui/material/Box';
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 TextField from '@mui/material/TextField';
import Typography from '@mui/material/Typography';
import IconButton from '@mui/material/IconButton';
import LinearProgress from '@mui/material/LinearProgress';

import { submitHomework, getHomeworkById, validateHomeworkFiles } 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}`);
}

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

export function HomeworkSubmitDrawer({ open, homeworkId, onClose, onSuccess }) {
  const [homework, setHomework] = useState(null);
  const [content, setContent] = useState('');
  const [files, setFiles] = useState([]);
  const [loading, setLoading] = useState(false);
  const [uploadProgress, setUploadProgress] = useState(null);
  const [error, setError] = useState(null);

  useEffect(() => {
    if (!open) {
      setContent('');
      setFiles([]);
      setUploadProgress(null);
      setError(null);
      setHomework(null);
    } else if (homeworkId) {
      getHomeworkById(homeworkId)
        .then(setHomework)
        .catch(() => setHomework(null));
    }
  }, [open, homeworkId]);

  const assignmentFiles = useMemo(() => {
    if (!homework) return [];
    const list = [];
    if (homework.attachment) list.push({ label: 'Файл задания', url: fileUrl(homework.attachment) });
    (homework.files ?? [])
      .filter((f) => f.file_type === 'assignment')
      .forEach((f) => {
        if (f.file) list.push({ label: f.filename || 'Файл', url: fileUrl(f.file) });
      });
    if (homework.attachment_url?.trim())
      list.push({ label: 'Ссылка на материал', url: homework.attachment_url.trim() });
    return list;
  }, [homework]);

  const handleFileChange = (e) => {
    const list = Array.from(e.target.files || []);
    const combined = [...files, ...list];
    const { valid, error: validationError } = validateHomeworkFiles(combined);
    if (!valid) {
      setError(validationError ?? 'Ошибка файлов');
      return;
    }
    setFiles(combined);
    setError(null);
    e.target.value = '';
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!content.trim() && files.length === 0) {
      setError('Укажите текст или прикрепите файлы');
      return;
    }
    const { valid, error: validationError } = validateHomeworkFiles(files);
    if (!valid) {
      setError(validationError ?? 'Ошибка файлов');
      return;
    }
    try {
      setLoading(true);
      setError(null);
      setUploadProgress(0);
      await submitHomework(homeworkId, { content: content.trim(), files }, (p) =>
        setUploadProgress(p)
      );
      await onSuccess();
      onClose();
    } catch (err) {
      setError(err?.response?.data?.detail || err?.message || 'Ошибка отправки');
      setUploadProgress(null);
    } finally {
      setLoading(false);
    }
  };

  return (
    <Drawer
      anchor="right"
      open={open}
      onClose={loading ? undefined : onClose}
      PaperProps={{ sx: { width: { xs: '100%', sm: 460 } } }}
    >
      <Stack
        direction="row"
        alignItems="center"
        justifyContent="space-between"
        sx={{ px: 3, py: 2.5, borderBottom: '1px solid', borderColor: 'divider' }}
      >
        <Typography variant="h6">Отправить решение</Typography>
        <IconButton onClick={onClose} disabled={loading}>
          <Iconify icon="mingcute:close-line" />
        </IconButton>
      </Stack>

      <Box
        component="form"
        onSubmit={handleSubmit}
        sx={{ p: 3, overflowY: 'auto', flex: 1, display: 'flex', flexDirection: 'column', gap: 3 }}
      >
        {assignmentFiles.length > 0 && (
          <Box>
            <Typography variant="subtitle2" sx={{ mb: 1.5, color: 'text.secondary' }}>
              Файлы задания (от ментора)
            </Typography>
            <Stack spacing={1}>
              {assignmentFiles.map(({ label, url }, i) => (
                <Button
                  key={i}
                  component="a"
                  href={url}
                  target="_blank"
                  rel="noopener noreferrer"
                  variant="outlined"
                  startIcon={<Iconify icon="eva:download-outline" />}
                  sx={{ justifyContent: 'flex-start', textAlign: 'left' }}
                >
                  {label}
                </Button>
              ))}
            </Stack>
          </Box>
        )}

        <TextField
          label="Текст решения"
          multiline
          rows={6}
          value={content}
          onChange={(e) => setContent(e.target.value)}
          disabled={loading}
          placeholder="Введите текст решения..."
          fullWidth
        />

        <Box>
          <Typography variant="subtitle2" sx={{ mb: 1.5, color: 'text.secondary' }}>
            Файлы (до 50 МБ, не более 10 шт.)
          </Typography>

          <input
            id="hw-submit-file"
            type="file"
            multiple
            onChange={handleFileChange}
            disabled={loading}
            accept="image/*,video/*,audio/*,.pdf,.doc,.docx,.xls,.xlsx,.txt,.zip"
            style={{ display: 'none' }}
          />
          <Button
            component="label"
            htmlFor="hw-submit-file"
            variant="outlined"
            startIcon={<Iconify icon="eva:upload-outline" />}
            fullWidth
            disabled={loading}
            sx={{
              py: 2,
              border: '2px dashed',
              '&:hover': { border: '2px dashed' },
            }}
          >
            Прикрепить файлы
          </Button>

          {files.length > 0 && (
            <Stack spacing={0.5} sx={{ mt: 1.5 }}>
              {files.map((f, i) => (
                <Stack
                  key={`${f.name}-${i}`}
                  direction="row"
                  alignItems="center"
                  justifyContent="space-between"
                  sx={{
                    px: 1.5,
                    py: 1,
                    borderRadius: 1,
                    bgcolor: 'background.neutral',
                    border: '1px solid',
                    borderColor: 'divider',
                  }}
                >
                  <Typography variant="body2" noWrap sx={{ flex: 1 }}>
                    {f.name}
                  </Typography>
                  <IconButton
                    size="small"
                    onClick={() => setFiles((p) => p.filter((_, j) => j !== i))}
                    disabled={loading}
                    color="error"
                  >
                    <Iconify icon="mingcute:close-line" width={16} />
                  </IconButton>
                </Stack>
              ))}
            </Stack>
          )}

          {uploadProgress != null && (
            <Box sx={{ mt: 2 }}>
              <Stack direction="row" justifyContent="space-between" sx={{ mb: 0.5 }}>
                <Typography variant="caption" color="text.secondary">
                  Загрузка на сервер
                </Typography>
                <Typography variant="caption" fontWeight={600} color="primary">
                  {uploadProgress}%
                </Typography>
              </Stack>
              <LinearProgress variant="determinate" value={uploadProgress} />
            </Box>
          )}
        </Box>

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

        <Stack direction="row" spacing={1.5}>
          <Button variant="outlined" onClick={onClose} disabled={loading} fullWidth>
            Отмена
          </Button>
          <Button
            type="submit"
            variant="contained"
            disabled={loading || (!content.trim() && files.length === 0)}
            fullWidth
            startIcon={loading ? <Iconify icon="svg-spinners:8-dots-rotate" /> : null}
          >
            {loading ? (uploadProgress != null ? `${uploadProgress}%` : 'Отправка...') : 'Отправить'}
          </Button>
        </Stack>
      </Box>
    </Drawer>
  );
}
