'use client';

import { useState, useEffect } from 'react';

import { createHomework } from 'src/utils/homework-api';
import { completeLesson, uploadLessonFile } from 'src/utils/dashboard-api';

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

const MAX_LESSON_FILES = 10;
const MAX_FILE_SIZE_MB = 10;

function formatSize(bytes) {
  if (bytes >= 1024 * 1024) return `${(bytes / 1024 / 1024).toFixed(2)} МБ`;
  if (bytes >= 1024) return `${(bytes / 1024).toFixed(1)} КБ`;
  return `${bytes} Б`;
}

function getFileKind(file) {
  const t = file.type?.toLowerCase() ?? '';
  const name = file.name.toLowerCase();
  if (t.startsWith('image/') || /\.(jpe?g|png|gif|webp|bmp|svg|ico)$/i.test(name)) return 'image';
  if (t.startsWith('video/') || /\.(mp4|webm|ogg|mov|avi|mkv)$/i.test(name)) return 'video';
  if (t === 'application/pdf' || name.endsWith('.pdf')) return 'pdf';
  return 'other';
}

function FilePreviewChip({ file, onRemove, disabled }) {
  const kind = getFileKind(file);
  const [objectUrl, setObjectUrl] = useState(null);
  const name = file.name.length > 28 ? `${file.name.slice(0, 25)}…` : file.name;

  useEffect(() => {
    if (kind === 'image' || kind === 'video' || kind === 'pdf') {
      const url = URL.createObjectURL(file);
      setObjectUrl(url);
      return () => URL.revokeObjectURL(url);
    }
    return undefined;
  }, [file, kind]);

  let previewBlock;
  if (kind === 'image' && objectUrl) {
    previewBlock = (
      <img src={objectUrl} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover', borderRadius: 8 }} />
    );
  } else if (kind === 'video' && objectUrl) {
    previewBlock = (
      <video src={objectUrl} muted playsInline preload="metadata" style={{ width: '100%', height: '100%', objectFit: 'cover', borderRadius: 8 }} />
    );
  } else if (kind === 'pdf' && objectUrl) {
    previewBlock = (
      <iframe src={objectUrl} title={file.name} style={{ width: '100%', height: '100%', border: 'none', borderRadius: 8, minHeight: 140 }} />
    );
  } else {
    previewBlock = (
      <div style={{ width: '100%', height: '100%', minHeight: 60, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'rgba(0,0,0,0.08)', borderRadius: 8 }}>
        <span style={{ fontSize: 28 }}>📄</span>
      </div>
    );
  }

  return (
    <div style={{ background: 'rgba(0,0,0,0.06)', borderRadius: 12, border: '1px solid rgba(0,0,0,0.12)', overflow: 'hidden' }}>
      <div style={{ aspectRatio: '4/3', minHeight: 80, maxHeight: 140 }}>{previewBlock}</div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '8px 12px' }}>
        <div style={{ minWidth: 0, flex: 1 }}>
          <div style={{ fontSize: 13, fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{name}</div>
          <div style={{ fontSize: 11, opacity: 0.6 }}>{formatSize(file.size)}</div>
        </div>
        <button
          type="button"
          onClick={onRemove}
          disabled={disabled}
          aria-label="Удалить"
          style={{ width: 28, height: 28, display: 'flex', alignItems: 'center', justifyContent: 'center', borderRadius: 8, border: 'none', background: 'rgba(186,26,26,0.15)', color: '#ba1a1a', cursor: disabled ? 'not-allowed' : 'pointer' }}
        >
          ✕
        </button>
      </div>
    </div>
  );
}

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

export function ExitLessonModal({ isOpen, lessonId, onClose, onExit }) {
  const [step, setStep] = useState('choose_exit');
  const [formData, setFormData] = useState({ mentor_grade: '', school_grade: '', mentor_notes: '' });
  const [homeworkText, setHomeworkText] = useState('');
  const [files, setFiles] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [mounted, setMounted] = useState(false);
  const [visible, setVisible] = useState(false);

  useEffect(() => {
    if (isOpen) {
      setMounted(true);
      const t = requestAnimationFrame(() => {
        requestAnimationFrame(() => setVisible(true));
      });
      return () => cancelAnimationFrame(t);
    }
    setVisible(false);
    return undefined;
  }, [isOpen]);

  const reset = () => {
    setStep('choose_exit');
    setFormData({ mentor_grade: '', school_grade: '', mentor_notes: '' });
    setHomeworkText('');
    setFiles([]);
    setError(null);
  };

  const handleClose = () => {
    if (!loading) {
      reset();
      onClose();
    }
  };

  const handleTransitionEnd = (e) => {
    if (e.propertyName !== 'transform') return;
    if (!isOpen) setMounted(false);
  };

  if (!mounted) return null;

  const notes = (formData.mentor_notes || '').trim();
  const mentorGrade = formData.mentor_grade ? parseInt(formData.mentor_grade, 10) : undefined;
  const schoolGrade = formData.school_grade ? parseInt(formData.school_grade, 10) : undefined;

  const handleJustExit = () => {
    reset();
    onClose();
    onExit();
  };

  const handleCompleteNoHw = async () => {
    if (lessonId == null) return;
    setLoading(true);
    setError(null);
    try {
      const result = await completeLesson(String(lessonId), notes, mentorGrade, schoolGrade, undefined);
      if (!result?.success) {
        setError(result?.message || 'Не удалось завершить занятие.');
        return;
      }
      reset();
      onClose();
      onExit();
    } catch (e) {
      setError(e?.message || 'Не удалось завершить занятие');
    } finally {
      setLoading(false);
    }
  };

  const handleCompleteHwLater = async () => {
    if (lessonId == null) return;
    setLoading(true);
    setError(null);
    try {
      const completeResult = await completeLesson(String(lessonId), notes, mentorGrade, schoolGrade, undefined);
      if (!completeResult?.success) {
        setError(completeResult?.message || 'Не удалось завершить занятие.');
        return;
      }
      await createHomework({ title: 'ДЗ (заполнить позже)', description: '', lesson_id: lessonId, status: 'draft', fill_later: true });
      reset();
      onClose();
      onExit();
    } catch (e) {
      setError(e?.message || 'Не удалось завершить занятие');
    } finally {
      setLoading(false);
    }
  };

  const handleSaveHw = async () => {
    if (lessonId == null) return;
    const text = homeworkText.trim();
    if (!text && files.length === 0) {
      setError('Добавьте текст или прикрепите файлы');
      return;
    }
    setLoading(true);
    setError(null);
    try {
      const lessonFileIds = [];
      // eslint-disable-next-line no-restricted-syntax
      for (const file of files) {
        // eslint-disable-next-line no-await-in-loop
        const created = await uploadLessonFile(lessonId, file);
        const id = typeof created.id === 'number' ? created.id : parseInt(String(created.id), 10);
        if (!Number.isNaN(id)) lessonFileIds.push(id);
      }
      await createHomework({ title: 'Домашнее задание', description: text || '', lesson_id: lessonId, status: 'published' });
      const result = await completeLesson(String(lessonId), notes, mentorGrade, schoolGrade, text || undefined, true, lessonFileIds);
      if (!result?.success) {
        setError(result?.message || 'Занятие не удалось завершить.');
        return;
      }
      reset();
      onClose();
      onExit();
    } catch (e) {
      setError(e?.message || 'Не удалось сохранить ДЗ и завершить занятие');
    } finally {
      setLoading(false);
    }
  };

  const handleFileChange = (e) => {
    const { files: list } = e.target;
    if (!list?.length) return;
    const add = [];
    for (let i = 0; i < list.length; i += 1) {
      const f = list[i];
      if (f.size <= MAX_FILE_SIZE_MB * 1024 * 1024) add.push(f);
    }
    setFiles((prev) => [...prev, ...add].slice(0, MAX_LESSON_FILES));
    e.target.value = '';
  };

  const stepTitle = {
    choose_exit: 'Выйти из занятия',
    grades: 'Оценки',
    comment: 'Комментарий',
    choose_hw: 'Завершить занятие',
    hw_form: 'Домашнее задание',
  }[step] || '';

  const panelStyle = {
    position: 'fixed',
    top: 0,
    right: 0,
    bottom: 0,
    width: 420,
    background: '#fff',
    boxShadow: '-4px 0 24px rgba(0,0,0,0.15)',
    overflow: 'hidden',
    display: 'flex',
    flexDirection: 'column',
    zIndex: 10002,
    transform: isOpen && visible ? 'translateX(0)' : 'translateX(100%)',
    transition: 'transform 0.3s ease',
  };

  const btnBase = { padding: '14px 20px', borderRadius: 14, fontSize: 15, cursor: loading ? 'not-allowed' : 'pointer' };
  const btnPrimary = { ...btnBase, border: 'none', background: '#1976d2', color: '#fff', fontWeight: 600 };
  const btnSecondary = { ...btnBase, border: '1px solid #ddd', background: '#f5f5f5', color: '#333' };

  return (
    <div style={panelStyle} onTransitionEnd={handleTransitionEnd}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '20px 24px', borderBottom: '1px solid #eee', flexShrink: 0 }}>
        <h2 style={{ fontSize: 20, fontWeight: 600, margin: 0 }}>{stepTitle}</h2>
        <button type="button" onClick={handleClose} disabled={loading} style={{ width: 44, height: 44, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'none', border: 'none', borderRadius: 12, cursor: 'pointer', fontSize: 20 }}>
          ✕
        </button>
      </div>

      <div style={{ padding: '24px 28px', overflowY: 'auto', flex: 1 }}>
        {step === 'choose_exit' && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            <button type="button" onClick={handleJustExit} disabled={loading} style={{ ...btnSecondary, textAlign: 'left', display: 'flex', alignItems: 'center', gap: 12 }}>
              🚪 Выйти
            </button>
            {lessonId != null && (
              <button type="button" onClick={() => setStep('grades')} disabled={loading} style={{ ...btnPrimary, textAlign: 'left', display: 'flex', alignItems: 'center', gap: 12 }}>
                ✅ Выйти и завершить занятие
              </button>
            )}
          </div>
        )}

        {step === 'grades' && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            <p style={{ margin: '0 0 8px', fontSize: 14, color: '#666' }}>Необязательно</p>
            <div>
              {/* eslint-disable-next-line jsx-a11y/label-has-associated-control */}
              <label htmlFor="exit-mentor-grade" style={{ display: 'block', fontSize: 14, fontWeight: 500, marginBottom: 8, color: '#555' }}>
                Оценка за занятие (1–5)
              </label>
              <input
                id="exit-mentor-grade"
                type="number"
                min={1}
                max={5}
                value={formData.mentor_grade}
                onChange={(e) => setFormData((d) => ({ ...d, mentor_grade: e.target.value }))}
                style={{ width: '100%', padding: '12px 16px', borderRadius: 12, border: '1px solid #ddd', fontSize: 15 }}
              />
            </div>
            <div>
              {/* eslint-disable-next-line jsx-a11y/label-has-associated-control */}
              <label htmlFor="exit-school-grade" style={{ display: 'block', fontSize: 14, fontWeight: 500, marginBottom: 8, color: '#555' }}>
                Оценка в школе (1–5)
              </label>
              <input
                id="exit-school-grade"
                type="number"
                min={1}
                max={5}
                value={formData.school_grade}
                onChange={(e) => setFormData((d) => ({ ...d, school_grade: e.target.value }))}
                style={{ width: '100%', padding: '12px 16px', borderRadius: 12, border: '1px solid #ddd', fontSize: 15 }}
              />
            </div>
            <div style={{ display: 'flex', gap: 12, marginTop: 8 }}>
              <button type="button" onClick={() => setStep('choose_exit')} disabled={loading} style={btnSecondary}>Назад</button>
              <button type="button" onClick={() => setStep('comment')} disabled={loading} style={{ ...btnPrimary, flex: 1 }}>Далее</button>
            </div>
          </div>
        )}

        {step === 'comment' && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            <p style={{ margin: '0 0 8px', fontSize: 14, color: '#666' }}>Комментарий к занятию (необязательно)</p>
            <textarea
              value={formData.mentor_notes}
              onChange={(e) => setFormData((d) => ({ ...d, mentor_notes: e.target.value }))}
              rows={5}
              placeholder="Что прошли, успехи, рекомендации..."
              disabled={loading}
              style={{ width: '100%', padding: '12px 16px', borderRadius: 12, border: '1px solid #ddd', fontSize: 15, resize: 'vertical' }}
            />
            <div style={{ display: 'flex', gap: 12 }}>
              <button type="button" onClick={() => setStep('grades')} disabled={loading} style={btnSecondary}>Назад</button>
              <button type="button" onClick={() => setStep('choose_hw')} disabled={loading} style={{ ...btnPrimary, flex: 1 }}>Далее</button>
            </div>
          </div>
        )}

        {step === 'choose_hw' && (
          <>
            <p style={{ margin: '0 0 16px', fontSize: 15, color: '#666' }}>Выдать домашнее задание?</p>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              <button type="button" onClick={() => setStep('comment')} disabled={loading} style={{ ...btnSecondary, textAlign: 'left', display: 'flex', alignItems: 'center', gap: 12 }}>
                ← Назад
              </button>
              <button type="button" onClick={() => setStep('hw_form')} disabled={loading} style={{ ...btnSecondary, textAlign: 'left', display: 'flex', alignItems: 'center', gap: 12 }}>
                📋 Да
              </button>
              <button type="button" onClick={handleCompleteNoHw} disabled={loading} style={{ ...btnSecondary, textAlign: 'left', display: 'flex', alignItems: 'center', gap: 12 }}>
                ✕ Нет
              </button>
              <button type="button" onClick={handleCompleteHwLater} disabled={loading} style={{ ...btnSecondary, textAlign: 'left', display: 'flex', alignItems: 'center', gap: 12 }}>
                🕐 Позже (заполню на странице ДЗ)
              </button>
            </div>
          </>
        )}

        {step === 'hw_form' && (
          <>
            <div style={{ marginBottom: 20 }}>
              {/* eslint-disable-next-line jsx-a11y/label-has-associated-control */}
              <label htmlFor="exit-hw-text" style={{ display: 'block', fontSize: 14, fontWeight: 600, marginBottom: 8, color: '#555' }}>
                Текст задания
              </label>
              <textarea
                id="exit-hw-text"
                value={homeworkText}
                onChange={(e) => setHomeworkText(e.target.value)}
                rows={4}
                placeholder="Опишите домашнее задание..."
                disabled={loading}
                style={{ width: '100%', padding: '12px 16px', borderRadius: 12, border: '1px solid #ddd', fontSize: 15, resize: 'vertical' }}
              />
            </div>
            <div style={{ marginBottom: 20 }}>
              <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 8, color: '#555' }}>
                Файлы (до {MAX_FILE_SIZE_MB} МБ, не более {MAX_LESSON_FILES} шт.)
              </div>
              <input
                id="exit-lesson-file-input"
                type="file"
                multiple
                onChange={handleFileChange}
                disabled={loading}
                style={{ position: 'absolute', width: 1, height: 1, opacity: 0, pointerEvents: 'none' }}
              />
              {/* eslint-disable-next-line jsx-a11y/label-has-associated-control */}
              <label
                htmlFor="exit-lesson-file-input"
                style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10, padding: '16px 20px', borderRadius: 12, border: '2px dashed #ddd', background: '#f9f9f9', fontSize: 15, cursor: loading ? 'not-allowed' : 'pointer' }}
              >
                📎 Прикрепить файлы
              </label>
              {files.length > 0 && (
                <div style={{ marginTop: 12, display: 'flex', flexDirection: 'column', gap: 8 }}>
                  {files.map((f, i) => (
                    <FilePreviewChip
                      key={`${f.name}-${i}-${f.size}`}
                      file={f}
                      onRemove={() => setFiles((p) => p.filter((_, j) => j !== i))}
                      disabled={loading}
                    />
                  ))}
                </div>
              )}
            </div>
            {error && (
              <div style={{ background: 'rgba(186,26,26,0.1)', border: '1px solid #ba1a1a', borderRadius: 12, padding: 12, marginBottom: 16, fontSize: 14, color: '#ba1a1a' }}>
                {error}
              </div>
            )}
            <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
              <button type="button" onClick={() => setStep('choose_hw')} disabled={loading} style={btnSecondary}>Назад</button>
              <button type="button" onClick={handleCompleteHwLater} disabled={loading} style={{ ...btnSecondary, flex: 1, minWidth: 100 }}>Позже</button>
              <button type="button" onClick={handleSaveHw} disabled={loading} style={{ ...btnPrimary, flex: 1, minWidth: 100, opacity: loading ? 0.8 : 1 }}>
                {loading ? 'Сохранение...' : 'Сохранить'}
              </button>
            </div>
          </>
        )}
      </div>
    </div>
  );
}
