import 'dart:convert';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import '../../../../core/services/materials_rag_service.dart';
import '../../../../core/services/rag_ai_service.dart';
import '../../../../core/services/gamification_service.dart';
import '../../../../core/utils/logger.dart';
import '../../../../core/theme/app_theme_extension.dart';

class QuizListPage extends StatefulWidget {
  const QuizListPage({super.key});

  @override
  State<QuizListPage> createState() => _QuizListPageState();
}

class _QuizListPageState extends State<QuizListPage>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;

  List<Map<String, String>> _materials = [];
  Map<String, String> _materialClassNames =
      {}; // classId → name (para Gerar Quiz)
  List<Map<String, dynamic>> _history = [];
  List<Map<String, dynamic>> _teacherQuizzes = [];
  Map<String, String> _classNames = {}; // classId → name (para Do Professor)
  bool _loadingMaterials = true;
  bool _loadingHistory = true;
  bool _loadingTeacherQuizzes = true;

  // disciplina seleccionada no tab "Gerar Quiz" (null = vista de disciplinas)
  String? _selectedMaterialDisciplineId;
  // disciplina seleccionada no tab "Histórico" (null = vista de disciplinas)
  String? _selectedHistoryDisciplineId;
  // disciplina seleccionada no tab "Do Professor" (null = vista de disciplinas)
  String? _selectedDisciplineId;
  // classId → name para o histórico
  Map<String, String> _historyClassNames = {};

  // generating state
  String? _generatingForId;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 3, vsync: this);
    _loadMaterialsThenHistory();
    _loadTeacherQuizzes();
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  Future<void> _loadMaterialsThenHistory() async {
    await _loadMaterials();
    await _loadHistory();
  }

  Future<void> _loadMaterials() async {
    final mats = await MaterialsRAGService.getAvailableMaterialsForStudent();
    if (!mounted) return;

    final uid = FirebaseAuth.instance.currentUser?.uid;
    final classNamesMap = <String, String>{}; // classId \u2192 name
    // teacherId \u2192 classId  (para materiais sem classId explícito)
    final teacherToClass = <String, String>{};

    if (uid != null) {
      // Buscar turmas em que o aluno está inscrito
      final enrollSnap = await FirebaseFirestore.instance
          .collection('enrollments')
          .where('studentId', isEqualTo: uid)
          .get();
      final enrolledClassIds = enrollSnap.docs
          .map((d) => d.data()['classId'] as String?)
          .whereType<String>()
          .toSet();

      if (enrolledClassIds.isNotEmpty) {
        final classDocs = await Future.wait(
          enrolledClassIds.map(
            (id) =>
                FirebaseFirestore.instance.collection('classes').doc(id).get(),
          ),
        );
        for (final doc in classDocs.where((d) => d.exists)) {
          final name = doc.data()?['name'] as String? ?? doc.id;
          classNamesMap[doc.id] = name;
          final tid = doc.data()?['teacherId'] as String?;
          if (tid != null) teacherToClass[tid] = doc.id;
        }
      }
    }

    // Se algum material não tem classId, inferir pelo teacherId do material
    final enriched = mats.map<Map<String, String>>((m) {
      if (m['classId'] != null) return m;
      final tid = m['teacherId'];
      final inferred = tid != null ? teacherToClass[tid] : null;
      if (inferred != null) {
        return Map<String, String>.from({...m, 'classId': inferred});
      }
      return m;
    }).toList();

    // Buscar classIds que vieram explicitamente nos materiais e ainda não temos nome
    final extraClassIds = enriched
        .map((m) => m['classId'])
        .whereType<String>()
        .where((id) => !classNamesMap.containsKey(id))
        .toSet();
    if (extraClassIds.isNotEmpty) {
      final docs = await Future.wait(
        extraClassIds.map(
          (id) =>
              FirebaseFirestore.instance.collection('classes').doc(id).get(),
        ),
      );
      for (final doc in docs.where((d) => d.exists)) {
        classNamesMap[doc.id] = doc.data()?['name'] as String? ?? doc.id;
      }
    }

    Logger.info(
      'Materials loaded: ${enriched.length}, classNames: $classNamesMap, teacherToClass: $teacherToClass',
    );

    if (mounted)
      setState(() {
        _materials = enriched;
        _materialClassNames = classNamesMap;
        _loadingMaterials = false;
      });
  }

  Future<void> _loadTeacherQuizzes() async {
    Logger.info('=== _loadTeacherQuizzes STARTED ===');
    try {
      final uid = FirebaseAuth.instance.currentUser?.uid;
      if (uid == null) {
        if (mounted) setState(() => _loadingTeacherQuizzes = false);
        return;
      }

      // Obter enrollments do aluno
      final enrollSnap = await FirebaseFirestore.instance
          .collection('enrollments')
          .where('studentId', isEqualTo: uid)
          .get();

      final classIds = enrollSnap.docs
          .map((d) => d.data()['classId'] as String?)
          .whereType<String>()
          .toSet();

      if (classIds.isEmpty) {
        if (mounted) setState(() => _loadingTeacherQuizzes = false);
        return;
      }

      // Obter dados das turmas (name + teacherId)
      final classSnaps = await Future.wait(
        classIds.map(
          (id) =>
              FirebaseFirestore.instance.collection('classes').doc(id).get(),
        ),
      );

      final classNamesMap = <String, String>{};
      final teacherIds = <String>{};
      for (final doc in classSnaps.where((d) => d.exists)) {
        final data = doc.data()!;
        classNamesMap[doc.id] = data['name'] as String? ?? doc.id;
        final tid = data['teacherId'] as String?;
        if (tid != null) teacherIds.add(tid);
      }

      final classIdList = classIds.toList();
      final batches = <Future<QuerySnapshot>>[];

      if (teacherIds.isNotEmpty) {
        final batch = teacherIds.take(10).toList();
        batches.add(
          FirebaseFirestore.instance
              .collection('teacherQuizzes')
              .where('teacherId', whereIn: batch)
              .orderBy('createdAt', descending: true)
              .get(),
        );
      }

      if (classIdList.isNotEmpty) {
        final batch = classIdList.take(10).toList();
        batches.add(
          FirebaseFirestore.instance
              .collection('teacherQuizzes')
              .where('classIds', arrayContainsAny: batch)
              .orderBy('createdAt', descending: true)
              .get(),
        );
      }

      List<Map<String, dynamic>> quizzes = [];

      if (batches.isNotEmpty) {
        final results = await Future.wait(batches);
        final seen = <String>{};
        quizzes = results
            .expand((s) => s.docs)
            .where((d) => seen.add(d.id))
            .map((d) => {'id': d.id, ...d.data() as Map<String, dynamic>})
            .toList();
      }

      // Fallback: busca sem filtro e filtra manualmente
      if (quizzes.isEmpty) {
        try {
          final allSnap = await FirebaseFirestore.instance
              .collection('teacherQuizzes')
              .orderBy('createdAt', descending: true)
              .limit(50)
              .get();
          quizzes = allSnap.docs
              .map((d) => {'id': d.id, ...d.data() as Map<String, dynamic>})
              .where((quiz) {
                final quizTeacherId = quiz['teacherId'] as String?;
                final quizClassIds =
                    (quiz['classIds'] as List?)?.cast<String>() ?? [];
                return teacherIds.contains(quizTeacherId) ||
                    quizClassIds.any((cid) => classIds.contains(cid));
              })
              .toList();
        } catch (e) {
          Logger.error('Fallback all quizzes query failed: $e');
        }
      }

      Logger.info('Teacher quizzes loaded: ${quizzes.length}');
      if (mounted) {
        setState(() {
          _teacherQuizzes = quizzes;
          _classNames = classNamesMap;
          _loadingTeacherQuizzes = false;
        });
      }
    } catch (e) {
      Logger.error('Error loading teacher quizzes: $e');
      if (mounted) setState(() => _loadingTeacherQuizzes = false);
    }
  }

  Future<void> _loadHistory() async {
    try {
      final uid = FirebaseAuth.instance.currentUser?.uid;
      if (uid == null) {
        if (mounted) setState(() => _loadingHistory = false);
        return;
      }
      final snap = await FirebaseFirestore.instance
          .collection('quizHistory')
          .doc(uid)
          .collection('quizzes')
          .orderBy('createdAt', descending: true)
          .limit(30)
          .get();
      final list = snap.docs.map((d) => {'id': d.id, ...d.data()}).toList();

      // Resolver nomes de disciplinas para o histórico
      // 1) Usar _materialClassNames (já carregados) para quizzes gerados pelo aluno
      // 2) Para teacher quizzes, buscar classId via teacherQuizzes collection
      final histClassNames = Map<String, String>.from(_materialClassNames);

      // Enriquecer items de histórico com classId se em falta
      final teacherQuizIds = list
          .where((e) => e['teacherQuizId'] != null && e['classId'] == null)
          .map((e) => e['teacherQuizId'] as String)
          .toSet();
      if (teacherQuizIds.isNotEmpty) {
        final tqDocs = await Future.wait(
          teacherQuizIds.map(
            (id) => FirebaseFirestore.instance
                .collection('teacherQuizzes')
                .doc(id)
                .get(),
          ),
        );
        for (final doc in tqDocs.where((d) => d.exists)) {
          final cids = doc.data()?['classIds'] as List<dynamic>?;
          if (cids != null && cids.isNotEmpty) {
            final cid = cids.first as String;
            // Associar teacherQuizId → classId
            for (final item in list) {
              if (item['teacherQuizId'] == doc.id && item['classId'] == null) {
                item['classId'] = cid;
              }
            }
            // Buscar nome da classe se ainda não temos
            if (!histClassNames.containsKey(cid)) {
              final classDoc = await FirebaseFirestore.instance
                  .collection('classes')
                  .doc(cid)
                  .get();
              if (classDoc.exists) {
                histClassNames[cid] =
                    classDoc.data()?['name'] as String? ?? cid;
              }
            }
          }
        }
      }

      // Para quizzes gerados pelo aluno sem classId: inferir pelo materialId
      final materialIds = list
          .where((e) => e['materialId'] != null && e['classId'] == null)
          .map((e) => e['materialId'] as String)
          .toSet();
      if (materialIds.isNotEmpty) {
        // Procurar nos materiais já carregados
        for (final mat in _materials) {
          if (materialIds.contains(mat['id']) && mat['classId'] != null) {
            for (final item in list) {
              if (item['materialId'] == mat['id'] && item['classId'] == null) {
                item['classId'] = mat['classId'];
              }
            }
          }
        }
        // Buscar nomes de classes extra
        final extraCids = list
            .map((e) => e['classId'] as String?)
            .whereType<String>()
            .where((id) => !histClassNames.containsKey(id))
            .toSet();
        if (extraCids.isNotEmpty) {
          final docs = await Future.wait(
            extraCids.map(
              (id) => FirebaseFirestore.instance
                  .collection('classes')
                  .doc(id)
                  .get(),
            ),
          );
          for (final doc in docs.where((d) => d.exists)) {
            histClassNames[doc.id] = doc.data()?['name'] as String? ?? doc.id;
          }
        }
      }

      if (mounted)
        setState(() {
          _history = list;
          _historyClassNames = histClassNames;
          _loadingHistory = false;
        });
    } catch (e) {
      Logger.error('Error loading quiz history: $e');
      if (mounted) setState(() => _loadingHistory = false);
    }
  }

  Future<void> _generateQuiz(Map<String, String> material) async {
    setState(() => _generatingForId = material['id']);
    try {
      final matId = material['id']!;
      final matName = material['name'] ?? 'Material';

      // Buscar contexto do PDF
      final context = await MaterialsRAGService.getRelevantChunks(
        userQuery: 'conteúdo geral resumo tópicos principais',
        selectedMaterialIds: [matId],
      );

      if (context.isEmpty) {
        if (mounted) _showSnack('Não foi possível aceder ao conteúdo do PDF.');
        return;
      }

      // Gerar quiz via Ollama em formato JSON estruturado
      final numQuestions = 5 + Random().nextInt(16); // 5..20
      final prompt =
          'Usa APENAS o seguinte contexto para criar um quiz. Não uses conhecimento externo.\n\n'
          '$context\n\n'
          'Cria um quiz com EXACTAMENTE $numQuestions perguntas de escolha múltipla sobre o conteúdo acima. Não repitas perguntas.\n'
          'Responde SOMENTE com JSON válido, sem texto adicional, sem markdown, sem blocos de código.\n'
          'Formato exacto:\n'
          '[{"q":"Pergunta aqui","opts":["A) opção","B) opção","C) opção","D) opção"],"ans":0,"exp":"Explicação breve da resposta correcta"},...]\n'
          'ans é o índice (0-3) da opção correcta.';

      final raw = await RAGAIService.generateQuiz(prompt);
      final questions = _parseQuizJson(raw);

      if (questions.isEmpty) {
        if (mounted)
          _showSnack('Não foi possível gerar o quiz. Tenta novamente.');
        return;
      }

      // Guardar no histórico (guardar JSON raw para poder rever)
      final uid = FirebaseAuth.instance.currentUser?.uid;
      String? historyDocId;
      if (uid != null) {
        final classId = material['classId'];
        final docRef = await FirebaseFirestore.instance
            .collection('quizHistory')
            .doc(uid)
            .collection('quizzes')
            .add({
              'materialId': matId,
              'materialName': matName,
              if (classId != null) 'classId': classId,
              'quizJson': raw,
              'createdAt': FieldValue.serverTimestamp(),
            });
        historyDocId = docRef.id;
        await _loadHistory();
      }

      if (mounted)
        _showInteractiveQuiz(matName, questions, historyDocId: historyDocId);
    } catch (e) {
      Logger.error('Error generating quiz: $e');
      if (mounted) _showSnack('Erro ao gerar quiz. Tenta novamente.');
    } finally {
      if (mounted) setState(() => _generatingForId = null);
    }
  }

  /// Agrupa os quizzes por disciplina.
  /// Usa o primeiro classId do quiz para determinar a disciplina.
  /// Se não houver classId, agrupa em "Geral".
  Map<String, List<Map<String, dynamic>>> _groupByDiscipline() {
    final Map<String, List<Map<String, dynamic>>> groups = {};
    for (final quiz in _teacherQuizzes) {
      final quizClassIds = (quiz['classIds'] as List?)?.cast<String>() ?? [];
      // Encontrar o primeiro classId que temos nome
      String? groupId = quizClassIds.cast<String?>().firstWhere(
        (cid) => cid != null && _classNames.containsKey(cid),
        orElse: () => null,
      );
      groupId ??= quizClassIds.isNotEmpty ? quizClassIds.first : '__geral__';
      groups.putIfAbsent(groupId, () => []).add(quiz);
    }
    return groups;
  }

  Widget _buildTeacherQuizzesTab(ColorScheme cs) {
    if (_loadingTeacherQuizzes)
      return const Center(child: CircularProgressIndicator());
    if (_teacherQuizzes.isEmpty) {
      return Center(
        child: Padding(
          padding: const EdgeInsets.all(32),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Icon(
                Icons.school_outlined,
                size: 64,
                color: cs.onSurfaceVariant.withValues(alpha: 0.4),
              ),
              const SizedBox(height: 16),
              Text(
                'Sem quizzes do professor disponíveis.',
                textAlign: TextAlign.center,
                style: TextStyle(color: cs.onSurfaceVariant, fontSize: 16),
              ),
              const SizedBox(height: 8),
              Text(
                'O teu professor ainda não publicou quizzes.',
                textAlign: TextAlign.center,
                style: TextStyle(
                  color: cs.onSurfaceVariant.withValues(alpha: 0.7),
                  fontSize: 13,
                ),
              ),
            ],
          ),
        ),
      );
    }

    final groups = _groupByDiscipline();

    // Vista de lista de quizzes de uma disciplina
    if (_selectedDisciplineId != null) {
      final quizzes = groups[_selectedDisciplineId] ?? [];
      final disciplineName =
          _classNames[_selectedDisciplineId] ??
          (_selectedDisciplineId == '__geral__'
              ? 'Geral'
              : _selectedDisciplineId!);
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // Cabeçalho com botão voltar
          Padding(
            padding: const EdgeInsets.fromLTRB(8, 8, 16, 0),
            child: Row(
              children: [
                IconButton(
                  icon: Icon(Icons.arrow_back, color: cs.onSurface),
                  onPressed: () => setState(() => _selectedDisciplineId = null),
                ),
                const SizedBox(width: 4),
                Expanded(
                  child: Text(
                    disciplineName,
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                      color: cs.onSurface,
                    ),
                  ),
                ),
                Text(
                  '${quizzes.length} quiz${quizzes.length != 1 ? 'zes' : ''}',
                  style: TextStyle(fontSize: 13, color: cs.onSurfaceVariant),
                ),
              ],
            ),
          ),
          const Divider(height: 1),
          Expanded(
            child: ListView.separated(
              padding: const EdgeInsets.all(16),
              itemCount: quizzes.length,
              separatorBuilder: (_, __) => const SizedBox(height: 12),
              itemBuilder: (context, i) {
                final quiz = quizzes[i];
                final name = (quiz['materialName'] as String? ?? 'Quiz')
                    .replaceAll('.pdf', '')
                    .replaceAll('_', ' ');
                final ts = quiz['createdAt'];
                String dateStr = '';
                if (ts is Timestamp) {
                  final dt = ts.toDate();
                  dateStr =
                      '${dt.day.toString().padLeft(2, '0')}/${dt.month.toString().padLeft(2, '0')}/${dt.year}';
                }
                return Container(
                  decoration: BoxDecoration(
                    color: cs.surface,
                    borderRadius: BorderRadius.circular(16),
                    border: Border.all(
                      color: cs.outline.withValues(alpha: 0.15),
                    ),
                    boxShadow: [
                      BoxShadow(
                        color: cs.shadow.withValues(alpha: 0.05),
                        blurRadius: 8,
                        offset: const Offset(0, 2),
                      ),
                    ],
                  ),
                  child: ListTile(
                    contentPadding: const EdgeInsets.symmetric(
                      horizontal: 16,
                      vertical: 8,
                    ),
                    leading: Container(
                      width: 44,
                      height: 44,
                      decoration: BoxDecoration(
                        color: cs.secondary.withValues(alpha: 0.12),
                        borderRadius: BorderRadius.circular(10),
                      ),
                      child: Icon(Icons.quiz, color: cs.secondary, size: 22),
                    ),
                    title: Text(
                      name,
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                        fontWeight: FontWeight.w600,
                        fontSize: 14,
                        color: cs.onSurface,
                      ),
                    ),
                    subtitle: dateStr.isNotEmpty
                        ? Text(
                            'Publicado em $dateStr',
                            style: TextStyle(
                              fontSize: 12,
                              color: cs.onSurfaceVariant,
                            ),
                          )
                        : null,
                    trailing: Icon(
                      Icons.play_circle_outline,
                      color: cs.secondary,
                      size: 28,
                    ),
                    onTap: () => _showTeacherQuiz(quiz),
                  ),
                );
              },
            ),
          ),
        ],
      );
    }

    // Vista de disciplinas (cartões)
    final disciplineIds = groups.keys.toList();
    return ListView.separated(
      padding: const EdgeInsets.all(16),
      itemCount: disciplineIds.length,
      separatorBuilder: (_, __) => const SizedBox(height: 12),
      itemBuilder: (context, i) {
        final dId = disciplineIds[i];
        final dName = _classNames[dId] ?? (dId == '__geral__' ? 'Geral' : dId);
        final count = groups[dId]!.length;
        return InkWell(
          borderRadius: BorderRadius.circular(16),
          onTap: () => setState(() => _selectedDisciplineId = dId),
          child: Container(
            padding: const EdgeInsets.all(20),
            decoration: BoxDecoration(
              color: cs.surface,
              borderRadius: BorderRadius.circular(16),
              border: Border.all(color: cs.outline.withValues(alpha: 0.15)),
              boxShadow: [
                BoxShadow(
                  color: cs.shadow.withValues(alpha: 0.05),
                  blurRadius: 8,
                  offset: const Offset(0, 2),
                ),
              ],
            ),
            child: Row(
              children: [
                Container(
                  width: 48,
                  height: 48,
                  decoration: BoxDecoration(
                    color: cs.secondary.withValues(alpha: 0.12),
                    borderRadius: BorderRadius.circular(12),
                  ),
                  child: Icon(Icons.school, color: cs.secondary, size: 26),
                ),
                const SizedBox(width: 16),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        dName,
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                          fontSize: 15,
                          fontWeight: FontWeight.bold,
                          color: cs.onSurface,
                        ),
                      ),
                      const SizedBox(height: 4),
                      Text(
                        '$count quiz${count != 1 ? 'zes' : ''} disponív${count != 1 ? 'eis' : 'el'}',
                        style: TextStyle(
                          fontSize: 13,
                          color: cs.onSurfaceVariant,
                        ),
                      ),
                    ],
                  ),
                ),
                Icon(Icons.chevron_right, color: cs.onSurfaceVariant),
              ],
            ),
          ),
        );
      },
    );
  }

  void _showTeacherQuiz(Map<String, dynamic> quizDoc) {
    final rawJson = quizDoc['quizJson'] as String? ?? '';
    final questions = _parseQuizJson(rawJson);
    if (questions.isEmpty) {
      _showSnack('Não foi possível carregar este quiz.');
      return;
    }
    final quizId = quizDoc['id'] as String;
    final name = (quizDoc['materialName'] as String? ?? 'Quiz')
        .replaceAll('.pdf', '')
        .replaceAll('_', ' ');
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      isDismissible: false,
      builder: (_) => _TeacherQuizInteractiveSheet(
        title: name,
        quizId: quizId,
        questions: questions,
        materialName: name,
      ),
    );
  }

  /// Parse do JSON gerado pelo modelo — tolerante a erros
  List<_QuizQuestion> _parseQuizJson(String raw) {
    try {
      // Extrair o primeiro array JSON encontrado na string
      final start = raw.indexOf('[');
      final end = raw.lastIndexOf(']');
      if (start == -1 || end == -1 || end <= start) return [];
      final jsonStr = raw.substring(start, end + 1);
      final decoded = _jsonDecode(jsonStr);
      if (decoded is! List) return [];
      return decoded
          .map<_QuizQuestion?>((e) {
            if (e is! Map) return null;
            final q = e['q'] as String?;
            final opts = (e['opts'] as List?)?.cast<String>();
            final ans = e['ans'] as int?;
            final exp = e['exp'] as String? ?? '';
            if (q == null || opts == null || ans == null) return null;
            if (opts.length < 2 || ans < 0 || ans >= opts.length) return null;
            return _QuizQuestion(
              question: q,
              options: opts,
              correctIndex: ans,
              explanation: exp,
            );
          })
          .whereType<_QuizQuestion>()
          .toList();
    } catch (e) {
      Logger.error('Quiz JSON parse error: $e');
      return [];
    }
  }

  dynamic _jsonDecode(String s) => jsonDecode(s);

  Future<void> _previewPDF(Map<String, String> mat, String name) async {
    final matId = mat['id']!;
    final matName = name.replaceAll('.pdf', '').replaceAll('_', ' ');

    // Mostrar loading
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => AlertDialog(
        content: Row(
          children: [
            CircularProgressIndicator(),
            const SizedBox(width: 16),
            Text('A carregar PDF...'),
          ],
        ),
      ),
    );

    try {
      // Obter o texto completo do PDF usando o método existente
      final teacherId = mat['teacherId'];
      if (teacherId == null) {
        Navigator.of(context).pop();
        _showSnack(
          'Erro: não foi possível identificar o professor do material.',
        );
        return;
      }

      final fullText = await MaterialsRAGService.getFullPDFText(
        matName,
        teacherId,
      );

      Navigator.of(context).pop(); // Fechar loading

      if (fullText.isEmpty) {
        _showSnack('Não foi possível carregar o conteúdo do PDF.');
        return;
      }

      // Mostrar o conteúdo em um diálogo scrollável melhorado
      showModalBottomSheet(
        context: context,
        isScrollControlled: true,
        backgroundColor: Colors.transparent,
        builder: (context) => Container(
          height: MediaQuery.of(context).size.height * 0.90,
          decoration: BoxDecoration(
            color: Theme.of(context).colorScheme.surface,
            borderRadius: const BorderRadius.vertical(top: Radius.circular(24)),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withValues(alpha: 0.1),
                blurRadius: 20,
                offset: const Offset(0, -4),
              ),
            ],
          ),
          child: Column(
            children: [
              // Handle bar
              Container(
                width: 40,
                height: 4,
                margin: const EdgeInsets.symmetric(vertical: 12),
                decoration: BoxDecoration(
                  color: Theme.of(
                    context,
                  ).colorScheme.onSurfaceVariant.withValues(alpha: 0.4),
                  borderRadius: BorderRadius.circular(2),
                ),
              ),

              // Header melhorado
              Container(
                padding: const EdgeInsets.symmetric(
                  horizontal: 24,
                  vertical: 16,
                ),
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    colors: [
                      Theme.of(context).colorScheme.primary,
                      Theme.of(
                        context,
                      ).colorScheme.primary.withValues(alpha: 0.8),
                    ],
                    begin: Alignment.topLeft,
                    end: Alignment.bottomRight,
                  ),
                  borderRadius: const BorderRadius.vertical(
                    top: Radius.circular(24),
                  ),
                ),
                child: Column(
                  children: [
                    Row(
                      children: [
                        Container(
                          width: 48,
                          height: 48,
                          decoration: BoxDecoration(
                            color: Colors.white.withValues(alpha: 0.2),
                            borderRadius: BorderRadius.circular(12),
                            border: Border.all(
                              color: Colors.white.withValues(alpha: 0.3),
                            ),
                          ),
                          child: Icon(
                            Icons.picture_as_pdf,
                            color: Colors.white,
                            size: 24,
                          ),
                        ),
                        const SizedBox(width: 16),
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                matName,
                                style: const TextStyle(
                                  fontSize: 18,
                                  fontWeight: FontWeight.bold,
                                  color: Colors.white,
                                ),
                                maxLines: 2,
                                overflow: TextOverflow.ellipsis,
                              ),
                              const SizedBox(height: 4),
                              Text(
                                'Pré-visualização do conteúdo completo',
                                style: TextStyle(
                                  fontSize: 13,
                                  color: Colors.white.withValues(alpha: 0.9),
                                ),
                              ),
                            ],
                          ),
                        ),
                        Container(
                          decoration: BoxDecoration(
                            color: Colors.white.withValues(alpha: 0.2),
                            borderRadius: BorderRadius.circular(12),
                          ),
                          child: IconButton(
                            onPressed: () => Navigator.of(context).pop(),
                            icon: const Icon(
                              Icons.close,
                              color: Colors.white,
                              size: 20,
                            ),
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 16),

                    // Stats bar
                    Container(
                      padding: const EdgeInsets.symmetric(
                        horizontal: 16,
                        vertical: 12,
                      ),
                      decoration: BoxDecoration(
                        color: Colors.white.withValues(alpha: 0.15),
                        borderRadius: BorderRadius.circular(12),
                        border: Border.all(
                          color: Colors.white.withValues(alpha: 0.2),
                        ),
                      ),
                      child: Row(
                        children: [
                          Icon(
                            Icons.description,
                            color: Colors.white.withValues(alpha: 0.9),
                            size: 18,
                          ),
                          const SizedBox(width: 8),
                          Expanded(
                            child: Text(
                              '${(fullText.length / 1000).toStringAsFixed(1)}K caracteres • ${fullText.split('\n').length} linhas',
                              style: TextStyle(
                                fontSize: 12,
                                color: Colors.white.withValues(alpha: 0.9),
                                fontWeight: FontWeight.w500,
                              ),
                            ),
                          ),
                          Container(
                            padding: const EdgeInsets.symmetric(
                              horizontal: 8,
                              vertical: 4,
                            ),
                            decoration: BoxDecoration(
                              color: Colors.white.withValues(alpha: 0.2),
                              borderRadius: BorderRadius.circular(8),
                            ),
                            child: Text(
                              'PDF',
                              style: TextStyle(
                                fontSize: 10,
                                color: Colors.white,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),

              // Content area melhorado
              Expanded(
                child: Container(
                  margin: const EdgeInsets.all(20),
                  decoration: BoxDecoration(
                    color: Theme.of(
                      context,
                    ).colorScheme.surfaceContainerHighest,
                    borderRadius: BorderRadius.circular(16),
                    border: Border.all(
                      color: Theme.of(
                        context,
                      ).colorScheme.outline.withValues(alpha: 0.1),
                    ),
                  ),
                  child: Column(
                    children: [
                      // Content header
                      Container(
                        padding: const EdgeInsets.symmetric(
                          horizontal: 20,
                          vertical: 16,
                        ),
                        decoration: BoxDecoration(
                          color: Theme.of(
                            context,
                          ).colorScheme.surfaceContainerHighest,
                          borderRadius: const BorderRadius.vertical(
                            top: Radius.circular(16),
                          ),
                        ),
                        child: Row(
                          children: [
                            Icon(
                              Icons.text_fields,
                              color: Theme.of(context).colorScheme.primary,
                              size: 18,
                            ),
                            const SizedBox(width: 8),
                            Text(
                              'Conteúdo do Material',
                              style: TextStyle(
                                fontSize: 14,
                                fontWeight: FontWeight.w600,
                                color: Theme.of(context).colorScheme.onSurface,
                              ),
                            ),
                            const Spacer(),
                            Container(
                              padding: const EdgeInsets.symmetric(
                                horizontal: 8,
                                vertical: 4,
                              ),
                              decoration: BoxDecoration(
                                color: Theme.of(
                                  context,
                                ).colorScheme.primary.withValues(alpha: 0.1),
                                borderRadius: BorderRadius.circular(8),
                              ),
                              child: Text(
                                'Selecionável',
                                style: TextStyle(
                                  fontSize: 10,
                                  color: Theme.of(context).colorScheme.primary,
                                  fontWeight: FontWeight.w500,
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),

                      // Text content
                      Expanded(
                        child: Container(
                          padding: const EdgeInsets.all(20),
                          child: SingleChildScrollView(
                            child: SelectableText(
                              fullText,
                              style: TextStyle(
                                fontSize: 14,
                                height: 1.7,
                                color: Theme.of(context).colorScheme.onSurface,
                                fontFamily: 'Roboto',
                                letterSpacing: 0.3,
                              ),
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),

              // Footer melhorado
              Container(
                padding: const EdgeInsets.all(20),
                decoration: BoxDecoration(
                  color: Theme.of(context).colorScheme.surfaceContainerHighest,
                  borderRadius: const BorderRadius.vertical(
                    bottom: Radius.circular(24),
                  ),
                ),
                child: Row(
                  children: [
                    Container(
                      padding: const EdgeInsets.all(8),
                      decoration: BoxDecoration(
                        color: Theme.of(
                          context,
                        ).colorScheme.primary.withValues(alpha: 0.1),
                        borderRadius: BorderRadius.circular(8),
                      ),
                      child: Icon(
                        Icons.info_outline,
                        color: Theme.of(context).colorScheme.primary,
                        size: 16,
                      ),
                    ),
                    const SizedBox(width: 12),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            'Texto extraído automaticamente do PDF',
                            style: TextStyle(
                              fontSize: 12,
                              color: Theme.of(
                                context,
                              ).colorScheme.onSurfaceVariant,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                          const SizedBox(height: 2),
                          Text(
                            'Formatação otimizada para melhor legibilidade',
                            style: TextStyle(
                              fontSize: 11,
                              color: Theme.of(context)
                                  .colorScheme
                                  .onSurfaceVariant
                                  .withValues(alpha: 0.8),
                            ),
                          ),
                        ],
                      ),
                    ),
                    Icon(
                      Icons.keyboard_arrow_up,
                      color: Theme.of(context).colorScheme.onSurfaceVariant,
                      size: 16,
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      );
    } catch (e) {
      Logger.error('Error previewing PDF: $e');
      Navigator.of(context).pop(); // Fechar loading
      _showSnack('Erro ao carregar o PDF. Tenta novamente.');
    }
  }

  void _showInteractiveQuiz(
    String title,
    List<_QuizQuestion> questions, {
    String? historyDocId,
  }) {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      isDismissible: false,
      builder: (_) => _InteractiveQuizSheet(
        title: title,
        questions: questions,
        historyDocId: historyDocId,
      ),
    );
  }

  void _showHistoryResultDialog(Map<String, dynamic> item, String matName) {
    final cs = Theme.of(context).colorScheme;
    final score = item['score'] as int?;
    final total = item['totalQuestions'] as int?;
    final isTeacher = item['teacherQuizId'] != null;
    final ts = item['completedAt'] ?? item['createdAt'];
    String dateStr = '';
    if (ts is Timestamp) {
      final dt = ts.toDate();
      dateStr =
          '${dt.day.toString().padLeft(2, '0')}/${dt.month.toString().padLeft(2, '0')}/${dt.year}';
    }

    showDialog(
      context: context,
      builder: (ctx) => AlertDialog(
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
        title: Text(
          matName,
          style: TextStyle(
            fontWeight: FontWeight.bold,
            color: cs.onSurface,
            fontSize: 16,
          ),
        ),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            if (score != null && total != null) ...[
              const SizedBox(height: 8),
              Container(
                width: 96,
                height: 96,
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  color: cs.primary.withValues(alpha: 0.1),
                ),
                child: Center(
                  child: Text(
                    '$score/$total',
                    style: TextStyle(
                      fontSize: 28,
                      fontWeight: FontWeight.bold,
                      color: cs.primary,
                    ),
                  ),
                ),
              ),
              const SizedBox(height: 8),
              Text(
                '${((score / total) * 100).toStringAsFixed(0)}% correcto',
                style: TextStyle(fontSize: 14, color: cs.onSurfaceVariant),
              ),
            ] else
              Text(
                'Sem resultado guardado.',
                style: TextStyle(fontSize: 14, color: cs.onSurfaceVariant),
              ),
            if (dateStr.isNotEmpty) ...[
              const SizedBox(height: 8),
              Text(
                isTeacher
                    ? 'Quiz do professor · $dateStr'
                    : 'Completado em $dateStr',
                style: TextStyle(fontSize: 12, color: cs.onSurfaceVariant),
              ),
            ],
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(ctx).pop(),
            child: const Text('Fechar'),
          ),
        ],
      ),
    );
  }

  void _showQuizFromHistory(String title, String rawJson) {
    final questions = _parseQuizJson(rawJson);
    if (questions.isEmpty) {
      _showSnack('Não foi possível carregar este quiz.');
      return;
    }
    _showInteractiveQuiz(title, questions);
  }

  void _showSnack(String msg) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text(msg), behavior: SnackBarBehavior.floating),
    );
  }

  @override
  Widget build(BuildContext context) {
    final cs = Theme.of(context).colorScheme;
    return PopScope(
      canPop: false,
      onPopInvokedWithResult: (didPop, _) {
        if (didPop) return;
        if (_selectedMaterialDisciplineId != null) {
          setState(() => _selectedMaterialDisciplineId = null);
          return;
        }
        if (_selectedHistoryDisciplineId != null) {
          setState(() => _selectedHistoryDisciplineId = null);
          return;
        }
        if (_selectedDisciplineId != null) {
          setState(() => _selectedDisciplineId = null);
          return;
        }
        context.go('/student-dashboard');
      },
      child: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topLeft,
            end: Alignment.bottomRight,
            colors: AppThemeExtras.of(context).authBackgroundGradient,
          ),
        ),
        child: Scaffold(
          backgroundColor: Colors.transparent,
          appBar: AppBar(
            backgroundColor: cs.surface,
            foregroundColor: cs.onSurface,
            elevation: 0,
            scrolledUnderElevation: 1,
            leading: IconButton(
              icon: const Icon(Icons.arrow_back),
              onPressed: () {
                if (_selectedMaterialDisciplineId != null) {
                  setState(() => _selectedMaterialDisciplineId = null);
                } else if (_selectedHistoryDisciplineId != null) {
                  setState(() => _selectedHistoryDisciplineId = null);
                } else if (_selectedDisciplineId != null) {
                  setState(() => _selectedDisciplineId = null);
                } else {
                  context.go('/student-dashboard');
                }
              },
            ),
            title: Row(
              children: [
                Container(
                  padding: const EdgeInsets.all(7),
                  decoration: BoxDecoration(
                    color: cs.primary.withValues(alpha: 0.12),
                    borderRadius: BorderRadius.circular(10),
                  ),
                  child: Icon(Icons.quiz_rounded, color: cs.primary, size: 20),
                ),
                const SizedBox(width: 10),
                Text(
                  'Quiz',
                  style: TextStyle(
                    fontWeight: FontWeight.bold,
                    fontSize: 20,
                    color: cs.onSurface,
                  ),
                ),
              ],
            ),
            bottom: PreferredSize(
              preferredSize: const Size.fromHeight(52),
              child: Container(
                margin: const EdgeInsets.fromLTRB(16, 0, 16, 10),
                decoration: BoxDecoration(
                  color: cs.surfaceContainerHighest,
                  borderRadius: BorderRadius.circular(12),
                ),
                child: TabBar(
                  controller: _tabController,
                  labelColor: cs.onPrimary,
                  unselectedLabelColor: cs.onSurfaceVariant,
                  indicatorSize: TabBarIndicatorSize.tab,
                  dividerColor: Colors.transparent,
                  indicator: BoxDecoration(
                    color: cs.primary,
                    borderRadius: BorderRadius.circular(10),
                  ),
                  labelStyle: const TextStyle(
                    fontWeight: FontWeight.w600,
                    fontSize: 12,
                  ),
                  unselectedLabelStyle: const TextStyle(
                    fontWeight: FontWeight.w500,
                    fontSize: 12,
                  ),
                  padding: const EdgeInsets.all(4),
                  tabs: const [
                    Tab(text: 'Gerar Quiz'),
                    Tab(text: 'Histórico'),
                    Tab(text: 'Professor'),
                  ],
                ),
              ),
            ),
          ),
          body: TabBarView(
            controller: _tabController,
            children: [
              _buildMaterialsTab(cs),
              _buildHistoryTab(cs),
              _buildTeacherQuizzesTab(cs),
            ],
          ),
        ),
      ),
    );
  }

  Map<String, List<Map<String, String>>> _groupMaterialsByDiscipline() {
    final Map<String, List<Map<String, String>>> groups = {};
    for (final mat in _materials) {
      final cid = mat['classId'];
      // Usar sempre o classId como chave quando existe;
      // materiais sem classId vão para '__geral__'
      final groupId = cid ?? '__geral__';
      groups.putIfAbsent(groupId, () => []).add(mat);
    }
    return groups;
  }

  Widget _buildMaterialsTab(ColorScheme cs) {
    if (_loadingMaterials) {
      return const Center(child: CircularProgressIndicator());
    }
    if (_materials.isEmpty) {
      return Center(
        child: Padding(
          padding: const EdgeInsets.all(32),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Icon(
                Icons.folder_open,
                size: 64,
                color: cs.onSurfaceVariant.withValues(alpha: 0.4),
              ),
              const SizedBox(height: 16),
              Text(
                'Nenhum material disponível.',
                textAlign: TextAlign.center,
                style: TextStyle(color: cs.onSurfaceVariant, fontSize: 16),
              ),
              const SizedBox(height: 8),
              Text(
                'Inscreve-te numa disciplina para aceder aos PDFs do professor.',
                textAlign: TextAlign.center,
                style: TextStyle(
                  color: cs.onSurfaceVariant.withValues(alpha: 0.7),
                  fontSize: 13,
                ),
              ),
            ],
          ),
        ),
      );
    }

    final groups = _groupMaterialsByDiscipline();

    // Vista de materiais de uma disciplina
    if (_selectedMaterialDisciplineId != null) {
      final mats = groups[_selectedMaterialDisciplineId] ?? [];
      final disciplineName =
          _materialClassNames[_selectedMaterialDisciplineId] ??
          (_selectedMaterialDisciplineId == '__geral__'
              ? 'Geral'
              : _selectedMaterialDisciplineId!);
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: const EdgeInsets.fromLTRB(8, 8, 16, 0),
            child: Row(
              children: [
                IconButton(
                  icon: Icon(Icons.arrow_back, color: cs.onSurface),
                  onPressed: () =>
                      setState(() => _selectedMaterialDisciplineId = null),
                ),
                const SizedBox(width: 4),
                Expanded(
                  child: Text(
                    disciplineName,
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                      color: cs.onSurface,
                    ),
                  ),
                ),
                Text(
                  '${mats.length} material${mats.length != 1 ? 'is' : ''}',
                  style: TextStyle(fontSize: 13, color: cs.onSurfaceVariant),
                ),
              ],
            ),
          ),
          const Divider(height: 1),
          Expanded(
            child: ListView.separated(
              padding: const EdgeInsets.all(16),
              itemCount: mats.length,
              separatorBuilder: (_, __) => const SizedBox(height: 12),
              itemBuilder: (context, i) {
                final mat = mats[i];
                final isGenerating = _generatingForId == mat['id'];
                final name = mat['name'] ?? 'Material';
                return _buildMaterialTile(mat, name, isGenerating, cs);
              },
            ),
          ),
        ],
      );
    }

    // Sem disciplinas reais OU só 1 disciplina: mostrar lista plana directamente
    final realDisciplineIds = groups.keys
        .where((k) => k != '__geral__' && _materialClassNames.containsKey(k))
        .toList();
    if (realDisciplineIds.length <= 1) {
      final allMats = groups.values.expand((l) => l).toList();
      return ListView.separated(
        padding: const EdgeInsets.all(16),
        itemCount: allMats.length,
        separatorBuilder: (_, __) => const SizedBox(height: 12),
        itemBuilder: (context, i) {
          final mat = allMats[i];
          return _buildMaterialTile(
            mat,
            mat['name'] ?? 'Material',
            _generatingForId == mat['id'],
            cs,
          );
        },
      );
    }

    final disciplineIds = realDisciplineIds;
    return ListView.separated(
      padding: const EdgeInsets.all(16),
      itemCount: disciplineIds.length,
      separatorBuilder: (_, __) => const SizedBox(height: 12),
      itemBuilder: (context, i) {
        final dId = disciplineIds[i];
        final dName =
            _materialClassNames[dId] ?? (dId == '__geral__' ? 'Geral' : dId);
        final count = groups[dId]!.length;
        return InkWell(
          borderRadius: BorderRadius.circular(16),
          onTap: () => setState(() => _selectedMaterialDisciplineId = dId),
          child: Container(
            padding: const EdgeInsets.all(20),
            decoration: BoxDecoration(
              color: cs.surface,
              borderRadius: BorderRadius.circular(16),
              border: Border.all(color: cs.outline.withValues(alpha: 0.15)),
              boxShadow: [
                BoxShadow(
                  color: cs.shadow.withValues(alpha: 0.05),
                  blurRadius: 8,
                  offset: const Offset(0, 2),
                ),
              ],
            ),
            child: Row(
              children: [
                Container(
                  width: 48,
                  height: 48,
                  decoration: BoxDecoration(
                    color: cs.secondary.withValues(alpha: 0.12),
                    borderRadius: BorderRadius.circular(12),
                  ),
                  child: Icon(Icons.school, color: cs.secondary, size: 26),
                ),
                const SizedBox(width: 16),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        dName,
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                          fontSize: 15,
                          fontWeight: FontWeight.bold,
                          color: cs.onSurface,
                        ),
                      ),
                      const SizedBox(height: 4),
                      Text(
                        '$count material${count != 1 ? 'is' : ''}',
                        style: TextStyle(
                          fontSize: 13,
                          color: cs.onSurfaceVariant,
                        ),
                      ),
                    ],
                  ),
                ),
                Icon(Icons.chevron_right, color: cs.onSurfaceVariant),
              ],
            ),
          ),
        );
      },
    );
  }

  Widget _buildMaterialTile(
    Map<String, String> mat,
    String name,
    bool isGenerating,
    ColorScheme cs,
  ) {
    final cleanName = name.replaceAll('.pdf', '').replaceAll('_', ' ');
    return Container(
      margin: const EdgeInsets.only(bottom: 4),
      decoration: BoxDecoration(
        color: cs.surface,
        borderRadius: BorderRadius.circular(16),
        border: Border.all(color: cs.outline.withValues(alpha: 0.12), width: 1),
        boxShadow: [
          BoxShadow(
            color: cs.shadow.withValues(alpha: 0.05),
            blurRadius: 10,
            offset: const Offset(0, 3),
          ),
        ],
      ),
      child: Material(
        color: Colors.transparent,
        child: InkWell(
          borderRadius: BorderRadius.circular(16),
          onTap: isGenerating
              ? null
              : () => _showMaterialOptions(mat, name, cs),
          child: Padding(
            padding: const EdgeInsets.all(16),
            child: Row(
              children: [
                Container(
                  width: 52,
                  height: 52,
                  decoration: BoxDecoration(
                    color: cs.secondaryContainer.withValues(alpha: 0.6),
                    borderRadius: BorderRadius.circular(14),
                    border: Border.all(
                      color: cs.secondary.withValues(alpha: 0.2),
                      width: 1,
                    ),
                  ),
                  child: Stack(
                    alignment: Alignment.center,
                    children: [
                      Icon(Icons.picture_as_pdf, color: cs.secondary, size: 26),
                      if (!isGenerating)
                        Positioned(
                          bottom: 2,
                          right: 2,
                          child: Container(
                            width: 16,
                            height: 16,
                            decoration: BoxDecoration(
                              color: cs.primary,
                              borderRadius: BorderRadius.circular(8),
                            ),
                            child: Icon(
                              Icons.play_arrow,
                              color: cs.onPrimary,
                              size: 10,
                            ),
                          ),
                        ),
                    ],
                  ),
                ),
                const SizedBox(width: 16),
                // Content
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        cleanName,
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                          fontWeight: FontWeight.w700,
                          fontSize: 15,
                          color: cs.onSurface,
                          letterSpacing: 0.2,
                        ),
                      ),
                      const SizedBox(height: 6),
                      Container(
                        padding: const EdgeInsets.symmetric(
                          horizontal: 10,
                          vertical: 4,
                        ),
                        decoration: BoxDecoration(
                          color: cs.primaryContainer.withValues(alpha: 0.6),
                          borderRadius: BorderRadius.circular(12),
                        ),
                        child: Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Icon(Icons.touch_app, size: 12, color: cs.primary),
                            const SizedBox(width: 4),
                            Text(
                              isGenerating ? 'A gerar...' : 'Toca para opções',
                              style: TextStyle(
                                fontSize: 11,
                                color: cs.primary,
                                fontWeight: FontWeight.w600,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
                // Action indicator
                Container(
                  width: 40,
                  height: 40,
                  decoration: BoxDecoration(
                    color: isGenerating
                        ? cs.primary.withValues(alpha: 0.1)
                        : cs.surfaceContainerHighest.withValues(alpha: 0.6),
                    borderRadius: BorderRadius.circular(12),
                    border: Border.all(
                      color: isGenerating
                          ? cs.primary.withValues(alpha: 0.2)
                          : cs.outline.withValues(alpha: 0.12),
                    ),
                  ),
                  child: isGenerating
                      ? Center(
                          child: SizedBox(
                            width: 18,
                            height: 18,
                            child: CircularProgressIndicator(
                              strokeWidth: 2,
                              color: cs.primary,
                            ),
                          ),
                        )
                      : Icon(
                          Icons.chevron_right,
                          color: cs.onSurfaceVariant,
                          size: 22,
                        ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  void _showMaterialOptions(
    Map<String, String> mat,
    String name,
    ColorScheme cs,
  ) {
    final cleanName = name.replaceAll('.pdf', '').replaceAll('_', ' ');

    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.transparent,
      isScrollControlled: true,
      builder: (context) => Container(
        decoration: BoxDecoration(
          color: cs.surface,
          borderRadius: const BorderRadius.vertical(top: Radius.circular(28)),
          boxShadow: [
            BoxShadow(
              color: cs.shadow.withValues(alpha: 0.12),
              blurRadius: 20,
              offset: const Offset(0, -4),
            ),
          ],
        ),
        child: SafeArea(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // Handle bar melhorado
              Container(
                width: 48,
                height: 5,
                margin: const EdgeInsets.symmetric(vertical: 16),
                decoration: BoxDecoration(
                  color: cs.onSurfaceVariant.withValues(alpha: 0.3),
                  borderRadius: BorderRadius.circular(3),
                ),
              ),

              // Header melhorado com gradient
              Container(
                margin: const EdgeInsets.symmetric(horizontal: 24),
                padding: const EdgeInsets.all(20),
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    colors: [
                      cs.primary.withValues(alpha: 0.06),
                      cs.secondary.withValues(alpha: 0.06),
                    ],
                    begin: Alignment.topLeft,
                    end: Alignment.bottomRight,
                  ),
                  borderRadius: BorderRadius.circular(20),
                  border: Border.all(color: cs.outline.withValues(alpha: 0.1)),
                ),
                child: Row(
                  children: [
                    // PDF Icon animado
                    Container(
                      width: 52,
                      height: 52,
                      decoration: BoxDecoration(
                        color: cs.primaryContainer.withValues(alpha: 0.5),
                        borderRadius: BorderRadius.circular(16),
                        border: Border.all(
                          color: cs.primary.withValues(alpha: 0.3),
                          width: 1.5,
                        ),
                      ),
                      child: Stack(
                        alignment: Alignment.center,
                        children: [
                          Icon(
                            Icons.picture_as_pdf,
                            color: cs.primary,
                            size: 28,
                          ),
                          Positioned(
                            top: 4,
                            right: 4,
                            child: Container(
                              width: 12,
                              height: 12,
                              decoration: BoxDecoration(
                                color: cs.secondary,
                                shape: BoxShape.circle,
                              ),
                              child: Icon(
                                Icons.star,
                                color: Colors.white,
                                size: 8,
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),

                    const SizedBox(width: 16),

                    // Title section
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            cleanName,
                            style: TextStyle(
                              fontSize: 18,
                              fontWeight: FontWeight.bold,
                              color: cs.onSurface,
                              letterSpacing: 0.2,
                            ),
                            maxLines: 2,
                            overflow: TextOverflow.ellipsis,
                          ),
                          const SizedBox(height: 6),
                          Container(
                            padding: const EdgeInsets.symmetric(
                              horizontal: 12,
                              vertical: 6,
                            ),
                            decoration: BoxDecoration(
                              color: cs.primaryContainer.withValues(alpha: 0.6),
                              borderRadius: BorderRadius.circular(20),
                            ),
                            child: Text(
                              'Material de estudo',
                              style: TextStyle(
                                fontSize: 11,
                                color: cs.primary,
                                fontWeight: FontWeight.w600,
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),

              const SizedBox(height: 24),

              // Instructions
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 24),
                child: Row(
                  children: [
                    Icon(Icons.lightbulb_outline, color: cs.tertiary, size: 20),
                    const SizedBox(width: 8),
                    Expanded(
                      child: Text(
                        'O que gostarias de fazer com este material?',
                        style: TextStyle(
                          fontSize: 15,
                          color: cs.onSurface,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    ),
                  ],
                ),
              ),

              const SizedBox(height: 20),

              // Options melhoradas
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 24),
                child: Column(
                  children: [
                    // Preview PDF option com design premium
                    _buildPremiumOptionTile(
                      icon: Icons.visibility_rounded,
                      title: 'Pré-visualizar PDF',
                      subtitle: 'Ler o conteúdo completo do material',
                      description: 'Texto formatado e otimizado para leitura',
                      color: cs.primary,
                      gradient: LinearGradient(
                        colors: [
                          cs.primary.withValues(alpha: 0.1),
                          cs.primary.withValues(alpha: 0.05),
                        ],
                      ),
                      onTap: () {
                        Navigator.of(context).pop();
                        _previewPDF(mat, name);
                      },
                    ),

                    const SizedBox(height: 16),

                    // Generate Quiz option com design premium
                    _buildPremiumOptionTile(
                      icon: Icons.quiz_rounded,
                      title: 'Gerar Quiz',
                      subtitle: 'Criar um quiz personalizado',
                      description: 'Baseado em IA com perguntas inteligentes',
                      color: cs.secondary,
                      gradient: LinearGradient(
                        colors: [
                          cs.secondary.withValues(alpha: 0.1),
                          cs.secondary.withValues(alpha: 0.05),
                        ],
                      ),
                      onTap: () {
                        Navigator.of(context).pop();
                        _generateQuiz(mat);
                      },
                    ),
                  ],
                ),
              ),

              const SizedBox(height: 32),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildPremiumOptionTile({
    required IconData icon,
    required String title,
    required String subtitle,
    required String description,
    required Color color,
    required Gradient gradient,
    required VoidCallback onTap,
  }) {
    final cs = Theme.of(context).colorScheme;
    return InkWell(
      onTap: onTap,
      borderRadius: BorderRadius.circular(20),
      child: Container(
        padding: const EdgeInsets.all(20),
        decoration: BoxDecoration(
          gradient: gradient,
          borderRadius: BorderRadius.circular(20),
          border: Border.all(color: color.withValues(alpha: 0.2), width: 1.5),
          boxShadow: [
            BoxShadow(
              color: color.withValues(alpha: 0.1),
              blurRadius: 12,
              offset: const Offset(0, 4),
            ),
          ],
        ),
        child: Row(
          children: [
            // Icon container premium
            Container(
              width: 56,
              height: 56,
              decoration: BoxDecoration(
                color: color.withValues(alpha: 0.15),
                borderRadius: BorderRadius.circular(16),
                border: Border.all(
                  color: color.withValues(alpha: 0.3),
                  width: 1,
                ),
              ),
              child: Stack(
                alignment: Alignment.center,
                children: [
                  Icon(icon, color: color, size: 28),
                  Positioned(
                    bottom: 2,
                    right: 2,
                    child: Container(
                      width: 14,
                      height: 14,
                      decoration: BoxDecoration(
                        color: color,
                        shape: BoxShape.circle,
                      ),
                      child: Icon(
                        Icons.arrow_forward,
                        color: Colors.white,
                        size: 8,
                      ),
                    ),
                  ),
                ],
              ),
            ),

            const SizedBox(width: 16),

            // Text content
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    title,
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                      color: cs.onSurface,
                      letterSpacing: 0.3,
                    ),
                  ),
                  const SizedBox(height: 4),
                  Text(
                    subtitle,
                    style: TextStyle(
                      fontSize: 13,
                      color: cs.onSurfaceVariant,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                  const SizedBox(height: 2),
                  Text(
                    description,
                    style: TextStyle(
                      fontSize: 11,
                      color: cs.onSurfaceVariant.withValues(alpha: 0.8),
                    ),
                  ),
                ],
              ),
            ),

            // Arrow indicator
            Container(
              width: 32,
              height: 32,
              decoration: BoxDecoration(
                color: color.withValues(alpha: 0.1),
                borderRadius: BorderRadius.circular(10),
              ),
              child: Icon(Icons.arrow_forward_ios, color: color, size: 15),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildScoreChip(Map<String, dynamic> item, ColorScheme cs) {
    final score = item['score'] as int;
    final total = item['totalQuestions'] as int? ?? 0;
    if (total == 0) return const SizedBox.shrink();
    final pct = (score / total * 100).round();
    final color = pct >= 80
        ? cs.tertiary
        : pct >= 50
        ? cs.secondary
        : cs.error;
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
      decoration: BoxDecoration(
        color: color.withValues(alpha: 0.12),
        borderRadius: BorderRadius.circular(20),
        border: Border.all(color: color.withValues(alpha: 0.3)),
      ),
      child: Text(
        '$score/$total · $pct%',
        style: TextStyle(
          fontSize: 11,
          fontWeight: FontWeight.w700,
          color: color,
        ),
      ),
    );
  }

  Map<String, List<Map<String, dynamic>>> _groupHistoryByDiscipline() {
    final Map<String, List<Map<String, dynamic>>> groups = {};
    for (final item in _history) {
      final cid = item['classId'] as String?;
      final groupId = (cid != null && _historyClassNames.containsKey(cid))
          ? cid
          : '__geral__';
      groups.putIfAbsent(groupId, () => []).add(item);
    }
    return groups;
  }

  Widget _buildHistoryTab(ColorScheme cs) {
    if (_loadingHistory) {
      return const Center(child: CircularProgressIndicator());
    }
    if (_history.isEmpty) {
      return Center(
        child: Padding(
          padding: const EdgeInsets.all(32),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Icon(
                Icons.history,
                size: 64,
                color: cs.onSurfaceVariant.withValues(alpha: 0.4),
              ),
              const SizedBox(height: 16),
              Text(
                'Ainda não geraste nenhum quiz.',
                textAlign: TextAlign.center,
                style: TextStyle(color: cs.onSurfaceVariant, fontSize: 16),
              ),
            ],
          ),
        ),
      );
    }

    final groups = _groupHistoryByDiscipline();
    final realDisciplineIds = groups.keys
        .where((k) => k != '__geral__' && _historyClassNames.containsKey(k))
        .toList();

    if (realDisciplineIds.isEmpty) {
      return _buildHistoryList(cs, _history);
    }

    if (_selectedHistoryDisciplineId != null) {
      final items = groups[_selectedHistoryDisciplineId] ?? [];
      final dName =
          _historyClassNames[_selectedHistoryDisciplineId] ??
          _selectedHistoryDisciplineId!;
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: const EdgeInsets.fromLTRB(8, 8, 16, 0),
            child: Row(
              children: [
                IconButton(
                  icon: Icon(Icons.arrow_back, color: cs.onSurface),
                  onPressed: () =>
                      setState(() => _selectedHistoryDisciplineId = null),
                ),
                const SizedBox(width: 4),
                Expanded(
                  child: Text(
                    dName,
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                      color: cs.onSurface,
                    ),
                  ),
                ),
                Text(
                  '${items.length} quiz${items.length != 1 ? 'zes' : ''}',
                  style: TextStyle(fontSize: 13, color: cs.onSurfaceVariant),
                ),
              ],
            ),
          ),
          const Divider(height: 1),
          Expanded(child: _buildHistoryList(cs, items)),
        ],
      );
    }

    return ListView.separated(
      padding: const EdgeInsets.all(16),
      itemCount: realDisciplineIds.length,
      separatorBuilder: (_, __) => const SizedBox(height: 12),
      itemBuilder: (context, i) {
        final dId = realDisciplineIds[i];
        final dName = _historyClassNames[dId] ?? dId;
        final count = groups[dId]!.length;
        return InkWell(
          borderRadius: BorderRadius.circular(16),
          onTap: () => setState(() => _selectedHistoryDisciplineId = dId),
          child: Container(
            padding: const EdgeInsets.all(20),
            decoration: BoxDecoration(
              color: cs.surface,
              borderRadius: BorderRadius.circular(16),
              border: Border.all(color: cs.outline.withValues(alpha: 0.15)),
              boxShadow: [
                BoxShadow(
                  color: cs.shadow.withValues(alpha: 0.05),
                  blurRadius: 8,
                  offset: const Offset(0, 2),
                ),
              ],
            ),
            child: Row(
              children: [
                Container(
                  width: 48,
                  height: 48,
                  decoration: BoxDecoration(
                    color: cs.primary.withValues(alpha: 0.1),
                    borderRadius: BorderRadius.circular(12),
                  ),
                  child: Icon(Icons.history_edu, color: cs.primary, size: 26),
                ),
                const SizedBox(width: 16),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        dName,
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                          fontSize: 15,
                          fontWeight: FontWeight.bold,
                          color: cs.onSurface,
                        ),
                      ),
                      const SizedBox(height: 4),
                      Text(
                        '$count quiz${count != 1 ? 'zes' : ''}',
                        style: TextStyle(
                          fontSize: 13,
                          color: cs.onSurfaceVariant,
                        ),
                      ),
                    ],
                  ),
                ),
                Icon(Icons.chevron_right, color: cs.onSurfaceVariant),
              ],
            ),
          ),
        );
      },
    );
  }

  Widget _buildHistoryList(ColorScheme cs, List<Map<String, dynamic>> items) {
    return ListView.separated(
      padding: const EdgeInsets.all(16),
      itemCount: items.length,
      separatorBuilder: (_, __) => const SizedBox(height: 12),
      itemBuilder: (context, i) {
        final item = items[i];
        final matName = (item['materialName'] as String? ?? 'Material')
            .replaceAll('.pdf', '')
            .replaceAll('_', ' ');
        final ts = item['createdAt'];
        String dateStr = '';
        if (ts is Timestamp) {
          final dt = ts.toDate();
          dateStr =
              '${dt.day.toString().padLeft(2, '0')}/${dt.month.toString().padLeft(2, '0')}/${dt.year}  ${dt.hour.toString().padLeft(2, '0')}:${dt.minute.toString().padLeft(2, '0')}';
        }
        return Container(
          decoration: BoxDecoration(
            color: cs.surface,
            borderRadius: BorderRadius.circular(16),
            border: Border.all(color: cs.outline.withValues(alpha: 0.15)),
            boxShadow: [
              BoxShadow(
                color: cs.shadow.withValues(alpha: 0.05),
                blurRadius: 8,
                offset: const Offset(0, 2),
              ),
            ],
          ),
          child: ListTile(
            contentPadding: const EdgeInsets.symmetric(
              horizontal: 16,
              vertical: 8,
            ),
            leading: Container(
              width: 44,
              height: 44,
              decoration: BoxDecoration(
                color: cs.primary.withValues(alpha: 0.1),
                borderRadius: BorderRadius.circular(10),
              ),
              child: Icon(Icons.quiz, color: cs.primary, size: 22),
            ),
            title: Text(
              matName,
              maxLines: 2,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(
                fontWeight: FontWeight.w600,
                fontSize: 14,
                color: cs.onSurface,
              ),
            ),
            subtitle: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                if (dateStr.isNotEmpty)
                  Text(
                    dateStr,
                    style: TextStyle(fontSize: 12, color: cs.onSurfaceVariant),
                  ),
                if (item['score'] != null) ...[
                  const SizedBox(height: 6),
                  _buildScoreChip(item, cs),
                ],
              ],
            ),
            trailing: Icon(
              Icons.chevron_right,
              color: cs.onSurfaceVariant,
              size: 18,
            ),
            onTap: () {
              final rawJson =
                  item['quizJson'] as String? ?? item['quizText'] as String?;
              if (rawJson != null && rawJson.isNotEmpty) {
                _showQuizFromHistory(matName, rawJson);
              } else {
                // Quiz sem JSON guardado (ex: quiz do professor) — mostrar resultado
                _showHistoryResultDialog(item, matName);
              }
            },
          ),
        );
      },
    );
  }
}

// ─── Modelo de dados para uma questão de quiz ───────────────────────────────

class _QuizQuestion {
  final String question;
  final List<String> options;
  final int correctIndex;
  final String explanation;
  const _QuizQuestion({
    required this.question,
    required this.options,
    required this.correctIndex,
    required this.explanation,
  });
}

// ─── Sheet interativa para quizzes gerados pelo aluno ─────────────────────────

class _InteractiveQuizSheet extends StatefulWidget {
  final String title;
  final List<_QuizQuestion> questions;
  final String? historyDocId;
  const _InteractiveQuizSheet({
    required this.title,
    required this.questions,
    this.historyDocId,
  });

  @override
  State<_InteractiveQuizSheet> createState() => _InteractiveQuizSheetState();
}

class _InteractiveQuizSheetState extends State<_InteractiveQuizSheet> {
  int _current = 0;
  late List<int> _chosen;
  bool _submitted = false;
  bool _saving = false;
  DateTime? _startTime;

  @override
  void initState() {
    super.initState();
    _chosen = List.filled(widget.questions.length, -1);
    _startTime = DateTime.now();
  }

  void _selectOption(int idx) {
    if (_submitted) return;
    setState(() => _chosen[_current] = idx);
  }

  void _next() {
    if (_current < widget.questions.length - 1) {
      setState(() => _current++);
    } else {
      _submit();
    }
  }

  void _prev() {
    if (_current > 0) setState(() => _current--);
  }

  int get _score => List.generate(
    widget.questions.length,
    (i) => _chosen[i] == widget.questions[i].correctIndex ? 1 : 0,
  ).fold(0, (a, b) => a + b);

  Future<void> _submit() async {
    setState(() {
      _submitted = true;
      _saving = true;
    });
    try {
      final user = FirebaseAuth.instance.currentUser;
      if (user != null && widget.historyDocId != null) {
        await FirebaseFirestore.instance
            .collection('quizHistory')
            .doc(user.uid)
            .collection('quizzes')
            .doc(widget.historyDocId)
            .update({
              'score': _score,
              'totalQuestions': widget.questions.length,
              'completedAt': FieldValue.serverTimestamp(),
            });
        await GamificationService.recordQuizActivity(
          user.uid,
          score: _score,
          totalQuestions: widget.questions.length,
          materialName: widget.title,
        );

        // Registrar tempo de estudo real
        if (_startTime != null) {
          final elapsedDuration = DateTime.now().difference(_startTime!);
          final elapsedMinutes = elapsedDuration.inMinutes;
          final elapsedSeconds = elapsedDuration.inSeconds % 60;
          if (elapsedMinutes > 0 || elapsedSeconds > 0) {
            Logger.info(
              'Quiz study time recorded: ${elapsedMinutes}m ${elapsedSeconds}s',
            );
            await GamificationService.recordStudyTime(user.uid, elapsedMinutes);
          }
        }
      }
    } catch (e) {
      Logger.error('Error saving quiz result: $e');
    } finally {
      if (mounted) setState(() => _saving = false);
    }
  }

  Widget _buildHandle(ColorScheme cs) => Container(
    margin: const EdgeInsets.only(top: 12, bottom: 4),
    width: 40,
    height: 4,
    decoration: BoxDecoration(
      color: cs.outline.withValues(alpha: 0.3),
      borderRadius: BorderRadius.circular(2),
    ),
  );

  @override
  Widget build(BuildContext context) {
    final cs = Theme.of(context).colorScheme;
    return DraggableScrollableSheet(
      initialChildSize: 0.93,
      minChildSize: 0.6,
      maxChildSize: 0.97,
      builder: (_, sc) => Container(
        decoration: BoxDecoration(
          color: cs.surface,
          borderRadius: const BorderRadius.vertical(top: Radius.circular(20)),
        ),
        child: Column(
          children: [
            _buildHandle(cs),
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
              child: Row(
                children: [
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          widget.title,
                          maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                            fontSize: 15,
                            fontWeight: FontWeight.bold,
                            color: cs.onSurface,
                          ),
                        ),
                        if (!_submitted)
                          Text(
                            'Pergunta ${_current + 1} de ${widget.questions.length}',
                            style: TextStyle(
                              fontSize: 12,
                              color: cs.onSurfaceVariant,
                            ),
                          ),
                      ],
                    ),
                  ),
                  if (_saving)
                    const SizedBox(
                      width: 24,
                      height: 24,
                      child: CircularProgressIndicator(strokeWidth: 2),
                    )
                  else
                    IconButton(
                      icon: Icon(Icons.close, color: cs.onSurfaceVariant),
                      onPressed: () => Navigator.of(context).pop(),
                    ),
                ],
              ),
            ),
            const Divider(height: 1),
            Expanded(
              child: _submitted
                  ? _buildResults(cs, sc)
                  : _buildQuestion(cs, sc),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildQuestion(ColorScheme cs, ScrollController sc) {
    final q = widget.questions[_current];
    final chosen = _chosen[_current];
    return ListView(
      controller: sc,
      padding: const EdgeInsets.fromLTRB(20, 16, 20, 24),
      children: [
        ClipRRect(
          borderRadius: BorderRadius.circular(4),
          child: LinearProgressIndicator(
            value: (_current + 1) / widget.questions.length,
            minHeight: 6,
            backgroundColor: cs.surfaceContainerHighest,
            valueColor: AlwaysStoppedAnimation(cs.primary),
          ),
        ),
        const SizedBox(height: 20),
        Text(
          q.question,
          style: TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.w600,
            color: cs.onSurface,
            height: 1.4,
          ),
        ),
        const SizedBox(height: 20),
        ...List.generate(q.options.length, (i) {
          final isSelected = chosen == i;
          return Padding(
            padding: const EdgeInsets.only(bottom: 12),
            child: InkWell(
              borderRadius: BorderRadius.circular(12),
              onTap: () => _selectOption(i),
              child: AnimatedContainer(
                duration: const Duration(milliseconds: 150),
                padding: const EdgeInsets.symmetric(
                  horizontal: 16,
                  vertical: 14,
                ),
                decoration: BoxDecoration(
                  color: isSelected
                      ? cs.primary.withValues(alpha: 0.12)
                      : cs.surfaceContainerHighest.withValues(alpha: 0.5),
                  borderRadius: BorderRadius.circular(12),
                  border: Border.all(
                    color: isSelected
                        ? cs.primary
                        : cs.outline.withValues(alpha: 0.2),
                    width: isSelected ? 2 : 1,
                  ),
                ),
                child: Row(
                  children: [
                    Expanded(
                      child: Text(
                        q.options[i],
                        style: TextStyle(
                          fontSize: 14,
                          color: isSelected ? cs.primary : cs.onSurface,
                          fontWeight: isSelected
                              ? FontWeight.w600
                              : FontWeight.normal,
                        ),
                      ),
                    ),
                    if (isSelected)
                      Icon(Icons.check_circle, color: cs.primary, size: 20),
                  ],
                ),
              ),
            ),
          );
        }),
        const SizedBox(height: 8),
        Row(
          children: [
            if (_current > 0) ...[
              Expanded(
                child: OutlinedButton(
                  onPressed: _prev,
                  style: OutlinedButton.styleFrom(
                    padding: const EdgeInsets.symmetric(vertical: 14),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(12),
                    ),
                  ),
                  child: const Text('Anterior'),
                ),
              ),
              const SizedBox(width: 12),
            ],
            Expanded(
              child: ElevatedButton(
                onPressed: chosen == -1 ? null : _next,
                style: ElevatedButton.styleFrom(
                  backgroundColor: cs.primary,
                  foregroundColor: cs.onPrimary,
                  padding: const EdgeInsets.symmetric(vertical: 14),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(12),
                  ),
                ),
                child: Text(
                  _current < widget.questions.length - 1
                      ? 'Próxima'
                      : 'Submeter',
                ),
              ),
            ),
          ],
        ),
      ],
    );
  }

  Widget _buildResults(ColorScheme cs, ScrollController sc) {
    final total = widget.questions.length;
    final score = _score;
    final pct = (score / total * 100).round();
    final isDark = cs.brightness == Brightness.dark;
    final correctColor = isDark ? cs.primary : const Color(0xFF22C55E);
    final wrongColor = isDark ? cs.secondary : const Color(0xFFEF4444);
    final scoreColor = pct >= 80
        ? correctColor
        : pct >= 50
        ? cs.tertiary
        : wrongColor;
    return ListView(
      controller: sc,
      padding: const EdgeInsets.fromLTRB(20, 20, 20, 32),
      children: [
        Container(
          padding: const EdgeInsets.symmetric(vertical: 28, horizontal: 20),
          decoration: BoxDecoration(
            color: scoreColor.withValues(alpha: 0.08),
            borderRadius: BorderRadius.circular(20),
            border: Border.all(color: scoreColor.withValues(alpha: 0.25)),
          ),
          child: Column(
            children: [
              Container(
                width: 80,
                height: 80,
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  color: scoreColor.withValues(alpha: 0.15),
                  border: Border.all(
                    color: scoreColor.withValues(alpha: 0.4),
                    width: 2,
                  ),
                ),
                child: Center(
                  child: Text(
                    '$score/$total',
                    style: TextStyle(
                      fontSize: 22,
                      fontWeight: FontWeight.bold,
                      color: scoreColor,
                    ),
                  ),
                ),
              ),
              const SizedBox(height: 12),
              Text(
                '$pct% de respostas correctas',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w600,
                  color: scoreColor,
                ),
              ),
            ],
          ),
        ),
        const SizedBox(height: 24),
        Text(
          'Revisão',
          style: TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.bold,
            color: cs.onSurface,
          ),
        ),
        const SizedBox(height: 12),
        ...List.generate(total, (i) {
          final q = widget.questions[i];
          final chosen = _chosen[i];
          final isCorrect = chosen == q.correctIndex;
          final revColor = isCorrect ? correctColor : wrongColor;
          return Container(
            margin: const EdgeInsets.only(bottom: 16),
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: revColor.withValues(alpha: 0.06),
              borderRadius: BorderRadius.circular(14),
              border: Border.all(color: revColor.withValues(alpha: 0.2)),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Icon(
                      isCorrect ? Icons.check_circle : Icons.cancel,
                      color: revColor,
                      size: 18,
                    ),
                    const SizedBox(width: 8),
                    Expanded(
                      child: Text(
                        'Pergunta ${i + 1}',
                        style: TextStyle(
                          fontSize: 12,
                          fontWeight: FontWeight.w600,
                          color: revColor,
                        ),
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 8),
                Text(
                  q.question,
                  style: TextStyle(
                    fontSize: 14,
                    fontWeight: FontWeight.w600,
                    color: cs.onSurface,
                  ),
                ),
                const SizedBox(height: 8),
                if (chosen >= 0 && chosen < q.options.length && !isCorrect)
                  Text(
                    'A tua resposta: ${q.options[chosen]}',
                    style: TextStyle(fontSize: 13, color: wrongColor),
                  ),
                Text(
                  'Resposta correcta: ${q.options[q.correctIndex]}',
                  style: TextStyle(
                    fontSize: 13,
                    color: isCorrect ? correctColor : cs.onSurface,
                    fontWeight: FontWeight.w500,
                  ),
                ),
                if (q.explanation.isNotEmpty) ...[
                  const SizedBox(height: 8),
                  Container(
                    padding: const EdgeInsets.all(10),
                    decoration: BoxDecoration(
                      color: cs.surfaceContainerHighest.withValues(alpha: 0.6),
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Icon(
                          Icons.info_outline,
                          size: 14,
                          color: cs.onSurfaceVariant,
                        ),
                        const SizedBox(width: 6),
                        Expanded(
                          child: Text(
                            q.explanation,
                            style: TextStyle(
                              fontSize: 12,
                              color: cs.onSurfaceVariant,
                              height: 1.4,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ],
            ),
          );
        }),
        const SizedBox(height: 8),
        ElevatedButton(
          onPressed: () => Navigator.of(context).pop(),
          style: ElevatedButton.styleFrom(
            backgroundColor: cs.primary,
            foregroundColor: cs.onPrimary,
            padding: const EdgeInsets.symmetric(vertical: 14),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(12),
            ),
          ),
          child: const Text('Fechar'),
        ),
      ],
    );
  }
}

// ─── Sheet interativa para quizzes do professor (submete resultado) ───────────

class _TeacherQuizInteractiveSheet extends StatefulWidget {
  final String title;
  final String quizId;
  final List<_QuizQuestion> questions;
  final String? materialName;
  const _TeacherQuizInteractiveSheet({
    required this.title,
    required this.quizId,
    required this.questions,
    this.materialName,
  });

  @override
  State<_TeacherQuizInteractiveSheet> createState() =>
      _TeacherQuizInteractiveSheetState();
}

class _TeacherQuizInteractiveSheetState
    extends State<_TeacherQuizInteractiveSheet> {
  int _current = 0;
  late List<int> _chosen;
  bool _submitted = false;
  bool _saving = false;
  DateTime? _startTime;

  @override
  void initState() {
    super.initState();
    _chosen = List.filled(widget.questions.length, -1);
    _startTime = DateTime.now();
  }

  void _selectOption(int idx) {
    if (_submitted) return;
    setState(() => _chosen[_current] = idx);
  }

  void _next() {
    if (_current < widget.questions.length - 1) {
      setState(() => _current++);
    } else {
      _submit();
    }
  }

  void _prev() {
    if (_current > 0) setState(() => _current--);
  }

  int get _score => List.generate(
    widget.questions.length,
    (i) => _chosen[i] == widget.questions[i].correctIndex ? 1 : 0,
  ).fold(0, (a, b) => a + b);

  Future<void> _submit() async {
    setState(() {
      _submitted = true;
      _saving = true;
    });
    try {
      final user = FirebaseAuth.instance.currentUser;
      if (user != null) {
        final score = _score;
        final total = widget.questions.length;
        final matName = widget.materialName ?? widget.title;

        // Guardar submissão no quiz do professor
        await FirebaseFirestore.instance
            .collection('teacherQuizzes')
            .doc(widget.quizId)
            .collection('submissions')
            .doc(user.uid)
            .set({
              'studentId': user.uid,
              'studentName':
                  user.displayName ?? user.email?.split('@')[0] ?? 'Aluno',
              'score': score,
              'total': total,
              'submittedAt': FieldValue.serverTimestamp(),
            });

        // Guardar no historial do aluno para aparecer em Quiz > Histórico
        await FirebaseFirestore.instance
            .collection('quizHistory')
            .doc(user.uid)
            .collection('quizzes')
            .add({
              'materialName': matName,
              'score': score,
              'totalQuestions': total,
              'teacherQuizId': widget.quizId,
              'createdAt': FieldValue.serverTimestamp(),
              'completedAt': FieldValue.serverTimestamp(),
            });

        // Registrar atividade no sistema de gamificação
        await GamificationService.recordQuizActivity(
          user.uid,
          score: score,
          totalQuestions: total,
          materialName: matName,
        );

        // Registrar tempo de estudo real
        if (_startTime != null) {
          final elapsedDuration = DateTime.now().difference(_startTime!);
          final elapsedMinutes = elapsedDuration.inMinutes;
          final elapsedSeconds = elapsedDuration.inSeconds % 60;
          if (elapsedMinutes > 0 || elapsedSeconds > 0) {
            Logger.info(
              'Quiz study time recorded: ${elapsedMinutes}m ${elapsedSeconds}s',
            );
            await GamificationService.recordStudyTime(user.uid, elapsedMinutes);
          }
        }
      }
    } catch (e) {
      Logger.error('Error submitting teacher quiz result: $e');
    } finally {
      if (mounted) setState(() => _saving = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    final cs = Theme.of(context).colorScheme;
    return DraggableScrollableSheet(
      initialChildSize: 0.93,
      minChildSize: 0.6,
      maxChildSize: 0.97,
      builder: (_, sc) => Container(
        decoration: BoxDecoration(
          color: cs.surface,
          borderRadius: const BorderRadius.vertical(top: Radius.circular(20)),
        ),
        child: Column(
          children: [
            // Handle
            Container(
              margin: const EdgeInsets.only(top: 12, bottom: 4),
              width: 40,
              height: 4,
              decoration: BoxDecoration(
                color: cs.outline.withValues(alpha: 0.3),
                borderRadius: BorderRadius.circular(2),
              ),
            ),
            // Header
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
              child: Row(
                children: [
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          widget.title,
                          maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                            fontSize: 15,
                            fontWeight: FontWeight.bold,
                            color: cs.onSurface,
                          ),
                        ),
                        if (!_submitted)
                          Text(
                            'Pergunta ${_current + 1} de ${widget.questions.length}',
                            style: TextStyle(
                              fontSize: 12,
                              color: cs.onSurfaceVariant,
                            ),
                          ),
                      ],
                    ),
                  ),
                  if (_saving)
                    const SizedBox(
                      width: 24,
                      height: 24,
                      child: CircularProgressIndicator(strokeWidth: 2),
                    )
                  else
                    IconButton(
                      icon: Icon(Icons.close, color: cs.onSurfaceVariant),
                      onPressed: () => Navigator.of(context).pop(),
                    ),
                ],
              ),
            ),
            const Divider(height: 1),
            Expanded(
              child: _submitted
                  ? _buildResults(cs, sc)
                  : _buildQuestion(cs, sc),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildQuestion(ColorScheme cs, ScrollController sc) {
    final q = widget.questions[_current];
    final chosen = _chosen[_current];
    return ListView(
      controller: sc,
      padding: const EdgeInsets.fromLTRB(20, 16, 20, 24),
      children: [
        ClipRRect(
          borderRadius: BorderRadius.circular(4),
          child: LinearProgressIndicator(
            value: (_current + 1) / widget.questions.length,
            minHeight: 6,
            backgroundColor: cs.surfaceContainerHighest,
            valueColor: AlwaysStoppedAnimation(cs.secondary),
          ),
        ),
        const SizedBox(height: 20),
        Text(
          q.question,
          style: TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.w600,
            color: cs.onSurface,
            height: 1.4,
          ),
        ),
        const SizedBox(height: 20),
        ...List.generate(q.options.length, (i) {
          final isSelected = chosen == i;
          return Padding(
            padding: const EdgeInsets.only(bottom: 12),
            child: InkWell(
              borderRadius: BorderRadius.circular(12),
              onTap: () => _selectOption(i),
              child: AnimatedContainer(
                duration: const Duration(milliseconds: 150),
                padding: const EdgeInsets.symmetric(
                  horizontal: 16,
                  vertical: 14,
                ),
                decoration: BoxDecoration(
                  color: isSelected
                      ? cs.secondary.withValues(alpha: 0.12)
                      : cs.surfaceContainerHighest.withValues(alpha: 0.4),
                  borderRadius: BorderRadius.circular(12),
                  border: Border.all(
                    color: isSelected
                        ? cs.secondary
                        : cs.outline.withValues(alpha: 0.2),
                    width: isSelected ? 2 : 1,
                  ),
                ),
                child: Row(
                  children: [
                    Expanded(
                      child: Text(
                        q.options[i],
                        style: TextStyle(
                          fontSize: 14,
                          color: isSelected ? cs.secondary : cs.onSurface,
                          fontWeight: isSelected
                              ? FontWeight.w600
                              : FontWeight.normal,
                        ),
                      ),
                    ),
                    if (isSelected)
                      Icon(Icons.check_circle, color: cs.secondary, size: 20),
                  ],
                ),
              ),
            ),
          );
        }),
        const SizedBox(height: 8),
        Row(
          children: [
            if (_current > 0) ...[
              Expanded(
                child: OutlinedButton(
                  onPressed: _prev,
                  style: OutlinedButton.styleFrom(
                    padding: const EdgeInsets.symmetric(vertical: 14),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(12),
                    ),
                  ),
                  child: const Text('Anterior'),
                ),
              ),
              const SizedBox(width: 12),
            ],
            Expanded(
              child: ElevatedButton(
                onPressed: chosen == -1 ? null : _next,
                style: ElevatedButton.styleFrom(
                  backgroundColor: cs.secondary,
                  foregroundColor: cs.onSecondary,
                  padding: const EdgeInsets.symmetric(vertical: 14),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(12),
                  ),
                ),
                child: Text(
                  _current < widget.questions.length - 1
                      ? 'Próxima'
                      : 'Submeter',
                ),
              ),
            ),
          ],
        ),
      ],
    );
  }

  Widget _buildResults(ColorScheme cs, ScrollController sc) {
    final total = widget.questions.length;
    final score = _score;
    final pct = (score / total * 100).round();
    final isDark = cs.brightness == Brightness.dark;
    final correctColor = isDark ? cs.primary : const Color(0xFF22C55E);
    final wrongColor = isDark ? cs.secondary : const Color(0xFFEF4444);
    final scoreColor = pct >= 80
        ? correctColor
        : pct >= 50
        ? cs.tertiary
        : wrongColor;
    return ListView(
      controller: sc,
      padding: const EdgeInsets.fromLTRB(20, 20, 20, 32),
      children: [
        Container(
          padding: const EdgeInsets.symmetric(vertical: 28, horizontal: 20),
          decoration: BoxDecoration(
            color: scoreColor.withValues(alpha: 0.08),
            borderRadius: BorderRadius.circular(20),
            border: Border.all(color: scoreColor.withValues(alpha: 0.25)),
          ),
          child: Column(
            children: [
              Container(
                width: 80,
                height: 80,
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  color: scoreColor.withValues(alpha: 0.15),
                  border: Border.all(
                    color: scoreColor.withValues(alpha: 0.4),
                    width: 2,
                  ),
                ),
                child: Center(
                  child: Text(
                    '$score/$total',
                    style: TextStyle(
                      fontSize: 22,
                      fontWeight: FontWeight.bold,
                      color: scoreColor,
                    ),
                  ),
                ),
              ),
              const SizedBox(height: 12),
              Text(
                '$pct% de respostas correctas',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w600,
                  color: scoreColor,
                ),
              ),
              const SizedBox(height: 4),
              Text(
                'Resultado enviado ao professor ✓',
                style: TextStyle(fontSize: 12, color: cs.onSurfaceVariant),
              ),
            ],
          ),
        ),
        const SizedBox(height: 24),
        Text(
          'Revisão',
          style: TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.bold,
            color: cs.onSurface,
          ),
        ),
        const SizedBox(height: 12),
        ...List.generate(total, (i) {
          final q = widget.questions[i];
          final chosen = _chosen[i];
          final isCorrect = chosen == q.correctIndex;
          final revColor = isCorrect ? correctColor : wrongColor;
          return Container(
            margin: const EdgeInsets.only(bottom: 16),
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: revColor.withValues(alpha: 0.06),
              borderRadius: BorderRadius.circular(14),
              border: Border.all(color: revColor.withValues(alpha: 0.2)),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Icon(
                      isCorrect ? Icons.check_circle : Icons.cancel,
                      color: revColor,
                      size: 18,
                    ),
                    const SizedBox(width: 8),
                    Expanded(
                      child: Text(
                        'Pergunta ${i + 1}',
                        style: TextStyle(
                          fontSize: 12,
                          fontWeight: FontWeight.w600,
                          color: revColor,
                        ),
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 8),
                Text(
                  q.question,
                  style: TextStyle(
                    fontSize: 14,
                    fontWeight: FontWeight.w600,
                    color: cs.onSurface,
                  ),
                ),
                const SizedBox(height: 8),
                if (chosen >= 0 && chosen < q.options.length && !isCorrect)
                  Text(
                    'A tua resposta: ${q.options[chosen]}',
                    style: TextStyle(fontSize: 13, color: wrongColor),
                  ),
                Text(
                  'Resposta correcta: ${q.options[q.correctIndex]}',
                  style: TextStyle(
                    fontSize: 13,
                    color: isCorrect ? correctColor : cs.onSurface,
                    fontWeight: FontWeight.w500,
                  ),
                ),
                if (q.explanation.isNotEmpty) ...[
                  const SizedBox(height: 8),
                  Container(
                    padding: const EdgeInsets.all(10),
                    decoration: BoxDecoration(
                      color: cs.surfaceContainerHighest.withValues(alpha: 0.6),
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Icon(
                          Icons.info_outline,
                          size: 14,
                          color: cs.onSurfaceVariant,
                        ),
                        const SizedBox(width: 6),
                        Expanded(
                          child: Text(
                            q.explanation,
                            style: TextStyle(
                              fontSize: 12,
                              color: cs.onSurfaceVariant,
                              height: 1.4,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ],
            ),
          );
        }),
        const SizedBox(height: 8),
        ElevatedButton(
          onPressed: () => Navigator.of(context).pop(),
          style: ElevatedButton.styleFrom(
            backgroundColor: cs.secondary,
            foregroundColor: cs.onSecondary,
            padding: const EdgeInsets.symmetric(vertical: 14),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(12),
            ),
          ),
          child: const Text('Fechar'),
        ),
      ],
    );
  }
}
