'use client';

import { useState, useEffect } from 'react';

import Box from '@mui/material/Box';
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 TextField from '@mui/material/TextField';
import Typography from '@mui/material/Typography';
import IconButton from '@mui/material/IconButton';
import CircularProgress from '@mui/material/CircularProgress';
import { MobileDateTimePicker } from '@mui/x-date-pickers/MobileDateTimePicker';

import {
  updateHomework,
  publishHomework,
  uploadHomeworkFile,
  deleteHomeworkFile,
} from 'src/utils/homework-api';

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

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

export function HomeworkEditDrawer({ open, homework, onClose, onSuccess }) {
  const [title, setTitle] = useState('');
  const [description, setDescription] = useState('');
  const [deadline, setDeadline] = useState(null);
  const [existingFiles, setExistingFiles] = useState([]);
  const [uploadingCount, setUploadingCount] = useState(0);
  const [saving, setSaving] = useState(false);
  const [publishing, setPublishing] = useState(false);
  const [error, setError] = useState(null);

  useEffect(() => {
    if (!open || !homework) return;
    setTitle(homework.title || '');
    setDescription(homework.description || '');
    setDeadline(homework.deadline ? new Date(homework.deadline) : null);
    setExistingFiles(homework.files?.filter((f) => f.file_type === 'assignment') || []);
    setError(null);
  }, [open, homework]);

  const handleFileChange = (e) => {
    const newFiles = Array.from(e.target.files || []);
    if (!newFiles.length || !homework) return;
    e.target.value = '';

    const validFiles = newFiles.filter((file) => {
      if (file.size > 10 * 1024 * 1024) {
        setError(`Файл "${file.name}" больше 10 МБ`);
        return false;
      }
      return true;
    });

    if (!validFiles.length) return;

    setUploadingCount((c) => c + validFiles.length);

    Promise.all(
      validFiles.map((file) =>
        uploadHomeworkFile(homework.id, file)
          .then((uploaded) => {
            setExistingFiles((prev) => [...prev, uploaded]);
          })
          .catch((err) => {
            setError(err?.response?.data?.detail || err?.message || 'Ошибка загрузки файла');
          })
          .finally(() => {
            setUploadingCount((c) => c - 1);
          })
      )
    );
  };

  const handleRemoveFile = async (fileId) => {
    try {
      await deleteHomeworkFile(fileId);
      setExistingFiles((prev) => prev.filter((f) => f.id !== fileId));
    } catch (err) {
      setError(err?.response?.data?.detail || err?.message || 'Ошибка удаления файла');
    }
  };

  const handleSave = async () => {
    if (!homework) return;
    try {
      setError(null);
      setSaving(true);
      await updateHomework(homework.id, {
        title: title.trim() || homework.title,
        description: description.trim(),
        deadline: deadline ? deadline.toISOString() : null,
      });
      onSuccess();
    } catch (e) {
      setError(e?.response?.data?.detail || e?.message || 'Ошибка сохранения');
    } finally {
      setSaving(false);
    }
  };

  const handlePublish = async () => {
    if (!homework) return;
    if (!title.trim()) {
      setError('Укажите название задания');
      return;
    }
    if (!description.trim()) {
      setError('Укажите текст задания');
      return;
    }
    try {
      setError(null);
      setPublishing(true);
      await updateHomework(homework.id, {
        title: title.trim(),
        description: description.trim(),
        deadline: deadline ? deadline.toISOString() : null,
      });
      await publishHomework(homework.id);
      onSuccess();
      onClose();
    } catch (e) {
      setError(e?.response?.data?.detail || e?.message || 'Ошибка публикации');
    } finally {
      setPublishing(false);
    }
  };

  const isLoading = saving || publishing || uploadingCount > 0;

  return (
    <Drawer
      anchor="right"
      open={open}
      onClose={isLoading ? undefined : onClose}
      PaperProps={{ sx: { width: { xs: '100%', sm: 560 } } }}
    >
      <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={isLoading}>
          <Iconify icon="mingcute:close-line" />
        </IconButton>
      </Stack>

      <Box sx={{ p: 3, overflowY: 'auto', flex: 1, display: 'flex', flexDirection: 'column', gap: 3 }}>
        <TextField
          label="Название задания *"
          value={title}
          onChange={(e) => setTitle(e.target.value)}
          disabled={isLoading}
          fullWidth
        />

        <TextField
          label="Текст задания *"
          multiline
          rows={4}
          value={description}
          onChange={(e) => setDescription(e.target.value)}
          disabled={isLoading}
          placeholder="Опишите задание, шаги, ссылки..."
          fullWidth
        />

        <MobileDateTimePicker
          label="Дедлайн (опционально)"
          value={deadline}
          onChange={setDeadline}
          disabled={isLoading}
          slotProps={{ textField: { fullWidth: true } }}
        />

        <Box>
          <Typography variant="subtitle2" sx={{ mb: 1.5, color: 'text.secondary' }}>
            Файлы к заданию
          </Typography>

          <input
            type="file"
            multiple
            id="edit-hw-file"
            onChange={handleFileChange}
            disabled={isLoading}
            accept=".pdf,.doc,.docx,.txt,.jpg,.jpeg,.png,.zip,.rar"
            style={{ display: 'none' }}
          />
          <Button
            component="label"
            htmlFor="edit-hw-file"
            variant="outlined"
            startIcon={
              uploadingCount > 0 ? (
                <CircularProgress size={16} />
              ) : (
                <Iconify icon="eva:upload-outline" />
              )
            }
            fullWidth
            disabled={isLoading}
            sx={{ py: 1.5, border: '2px dashed', '&:hover': { border: '2px dashed' } }}
          >
            {uploadingCount > 0 ? `Загрузка ${uploadingCount}...` : 'Загрузить файлы'}
          </Button>

          {existingFiles.length > 0 && (
            <Stack direction="row" flexWrap="wrap" gap={1} sx={{ mt: 1.5 }}>
              {existingFiles.map((file) => (
                <Chip
                  key={file.id}
                  label={file.filename || 'Файл'}
                  size="small"
                  onDelete={() => handleRemoveFile(file.id)}
                  icon={<Iconify icon="eva:file-outline" width={14} />}
                />
              ))}
            </Stack>
          )}
        </Box>

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

        <Stack direction="row" spacing={1.5} flexWrap="wrap">
          <Button
            variant="contained"
            onClick={handlePublish}
            disabled={isLoading}
            startIcon={publishing ? <Iconify icon="svg-spinners:8-dots-rotate" /> : null}
          >
            {publishing ? 'Публикация...' : 'Опубликовать ДЗ'}
          </Button>
          <Button
            variant="outlined"
            onClick={handleSave}
            disabled={isLoading}
            startIcon={saving ? <Iconify icon="svg-spinners:8-dots-rotate" /> : null}
          >
            {saving ? 'Сохранение...' : 'Сохранить черновик'}
          </Button>
        </Stack>
      </Box>
    </Drawer>
  );
}
