import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_animate/flutter_animate.dart';
import 'package:flutter_markdown/flutter_markdown.dart';
import 'package:go_router/go_router.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import '../../../../core/services/chat_memory_service.dart';
import '../../../../core/services/materials_rag_service.dart';
import '../../../../core/services/rag_ai_service.dart';
import '../../../../core/theme/app_colors.dart';
import '../../../../core/utils/logger.dart';
import '../../../materials/presentation/pages/pdf_viewer_page.dart';

/// Simple AI Tutor chat interface page (for testing)
class TutorChatPageSimple extends StatefulWidget {
  final String? conversationId;

  const TutorChatPageSimple({super.key, this.conversationId});

  @override
  State<TutorChatPageSimple> createState() => _TutorChatPageSimpleState();
}

class _TutorChatPageSimpleState extends State<TutorChatPageSimple>
    with TickerProviderStateMixin {
  final TextEditingController _messageController = TextEditingController();
  final ScrollController _scrollController = ScrollController();
  final FocusNode _messageFocusNode = FocusNode();

  bool _isLoading = false;
  bool _materialsConfirmed = false;
  List<Map<String, dynamic>> _messages = [];

  List<Map<String, String>> _availableMaterials = [];
  Map<String, String> _classNames = {}; // classId → name
  Set<String> _selectedMaterialIds = {};

  @override
  void initState() {
    super.initState();
    _loadAvailableMaterials();
    if (widget.conversationId != null) {
      ChatMemoryService.setCurrentConversationId(widget.conversationId);
      _loadConversation(widget.conversationId!);
    }
  }

  Future<void> _loadAvailableMaterials() async {
    final materials =
        await MaterialsRAGService.getAvailableMaterialsForStudent();
    // Collect unique classIds that don't have a name yet
    final classIds = materials
        .map((m) => m['classId'])
        .whereType<String>()
        .toSet();
    final namesMap = <String, String>{};
    if (classIds.isNotEmpty) {
      final docs = await Future.wait(
        classIds.map(
          (id) =>
              FirebaseFirestore.instance.collection('classes').doc(id).get(),
        ),
      );
      for (final doc in docs.where((d) => d.exists)) {
        namesMap[doc.id] = doc.data()?['name'] as String? ?? doc.id;
      }
    }
    if (mounted) {
      setState(() {
        _availableMaterials = materials;
        _classNames = namesMap;
      });
    }
  }

  Future<void> _loadConversation(String conversationId) async {
    try {
      Logger.info('Loading conversation: $conversationId');
      final conversation = await ChatMemoryService.getConversation(
        conversationId,
      );
      if (conversation == null) {
        Logger.warning('Conversation not found: $conversationId');
        return;
      }

      final messages = await ChatMemoryService.getConversationMessages(
        conversationId: conversationId,
        limit: 50,
      );

      // Safely extract material IDs with type checking
      try {
        final materialIdsRaw = conversation['selectedMaterialIds'];
        if (materialIdsRaw != null && materialIdsRaw is List) {
          final materialIds = (materialIdsRaw as List)
              .where((item) => item is String)
              .cast<String>()
              .toSet();
          if (mounted) {
            setState(() {
              _selectedMaterialIds = materialIds;
              // Always set to true when loading from history to allow chat access
              _materialsConfirmed = true;
            });
          }
        } else {
          // No materials in conversation, but still allow chat access
          if (mounted) {
            setState(() {
              _materialsConfirmed = true;
            });
          }
        }
      } catch (e) {
        Logger.error('Error loading material IDs: $e');
        // Continue without materials but allow chat access
        if (mounted) {
          setState(() {
            _materialsConfirmed = true;
          });
        }
      }

      // Load messages from Firestore with safe casting
      final loadedMessages = messages.map((msg) {
        try {
          return <String, dynamic>{
            'content': msg['content']?.toString() ?? '',
            'isUser': msg['role']?.toString() == 'user',
            'timestamp': msg['createdAt'] is Timestamp
                ? (msg['createdAt'] as Timestamp).toDate()
                : DateTime.now(),
          };
        } catch (e) {
          Logger.error('Error mapping message: $e');
          // Return a safe fallback message
          return <String, dynamic>{
            'content': '[Mensagem indisponível]',
            'isUser': false,
            'timestamp': DateTime.now(),
          };
        }
      }).toList();

      if (mounted) {
        setState(() {
          _messages.clear();
          _messages.addAll(loadedMessages);
          _isLoading = false; // Ensure loading state is reset
        });
        _scrollToBottom();
        Logger.info(
          'Conversation loaded. _messages count: ${_messages.length}, _isLoading: $_isLoading, _materialsConfirmed: $_materialsConfirmed',
        );
      }
    } catch (e) {
      Logger.error('Error loading conversation: $e');
      // Show error to user
      if (mounted) {
        setState(() {
          _messages = [];
        });
      }
    }
  }

  @override
  void dispose() {
    _messageController.dispose();
    _scrollController.dispose();
    _messageFocusNode.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return PopScope(
      canPop: false,
      onPopInvoked: (didPop) {
        if (didPop) return;
        // Navigate back to dashboard instead of exiting app
        if (mounted) {
          context.go('/student-dashboard');
        }
      },
      child: Scaffold(
        backgroundColor: Theme.of(context).colorScheme.surfaceContainerLowest,
        appBar: PreferredSize(
          preferredSize: const Size.fromHeight(kToolbarHeight),
          child: Container(
            decoration: BoxDecoration(
              gradient: LinearGradient(
                colors: [
                  Theme.of(context).colorScheme.primary,
                  Theme.of(context).colorScheme.primary.withValues(alpha: 0.85),
                ],
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
              ),
              boxShadow: [
                BoxShadow(
                  color: Theme.of(
                    context,
                  ).colorScheme.primary.withValues(alpha: 0.3),
                  blurRadius: 8,
                  offset: const Offset(0, 2),
                ),
              ],
            ),
            child: SafeArea(
              top: false,
              child: Padding(
                padding: const EdgeInsets.symmetric(horizontal: 8),
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    IconButton(
                      onPressed: () => context.go('/student-dashboard'),
                      icon: const Icon(
                        Icons.arrow_back_ios_new,
                        color: Colors.white,
                        size: 20,
                      ),
                    ),
                    Container(
                      width: 38,
                      height: 38,
                      decoration: BoxDecoration(
                        color: const Color(0xFFF9EEE8),
                        borderRadius: BorderRadius.circular(12),
                      ),
                      child: Padding(
                        padding: const EdgeInsets.all(6),
                        child: Image.asset(
                          'assets/images/epvc.png',
                          fit: BoxFit.contain,
                        ),
                      ),
                    ),
                    const SizedBox(width: 10),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          const Text(
                            'Vico',
                            style: TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.bold,
                              color: Colors.white,
                            ),
                          ),
                          Row(
                            children: [
                              Container(
                                width: 7,
                                height: 7,
                                decoration: const BoxDecoration(
                                  color: Color(0xFF4ADE80),
                                  shape: BoxShape.circle,
                                ),
                              ),
                              const SizedBox(width: 4),
                              const Text(
                                'Online',
                                style: TextStyle(
                                  fontSize: 11,
                                  color: Colors.white70,
                                ),
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                    if (_materialsConfirmed)
                      TextButton.icon(
                        onPressed: () =>
                            _showMaterialsPicker(allowEmpty: false),
                        icon: const Icon(
                          Icons.folder_open,
                          size: 16,
                          color: Colors.white,
                        ),
                        label: Text(
                          '${_selectedMaterialIds.length}',
                          style: const TextStyle(
                            fontSize: 13,
                            fontWeight: FontWeight.w700,
                            color: Colors.white,
                          ),
                        ),
                        style: TextButton.styleFrom(
                          backgroundColor: Colors.white.withValues(alpha: 0.15),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(10),
                          ),
                          padding: const EdgeInsets.symmetric(
                            horizontal: 10,
                            vertical: 6,
                          ),
                          minimumSize: Size.zero,
                          tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                        ),
                      ),
                    IconButton(
                      onPressed: () {
                        final currentId =
                            ChatMemoryService.currentConversationId;
                        // If materials are confirmed, we're in chat mode
                        final source = _materialsConfirmed ? 'chat' : 'intro';
                        if (currentId != null) {
                          context.go(
                            '/chat-history?source=$source&conversationId=$currentId',
                          );
                        } else {
                          context.go('/chat-history?source=$source');
                        }
                      },
                      icon: const Icon(
                        Icons.history,
                        color: Colors.white,
                        size: 20,
                      ),
                    ),
                    if (_materialsConfirmed)
                      IconButton(
                        onPressed: () async {
                          final confirmed = await showDialog<bool>(
                            context: context,
                            builder: (context) => AlertDialog(
                              title: const Text('Nova conversa'),
                              content: const Text(
                                'Isto vai limpar o chat atual e guardá-lo no histórico. Continuar?',
                              ),
                              actions: [
                                TextButton(
                                  onPressed: () =>
                                      Navigator.pop(context, false),
                                  child: const Text('Cancelar'),
                                ),
                                TextButton(
                                  onPressed: () => Navigator.pop(context, true),
                                  style: TextButton.styleFrom(
                                    foregroundColor: Colors.red,
                                  ),
                                  child: const Text('Limpar'),
                                ),
                              ],
                            ),
                          );
                          if (confirmed == true) {
                            ChatMemoryService.setCurrentConversationId(null);
                            context.go('/ai-tutor');
                          }
                        },
                        icon: const Icon(
                          Icons.add_comment,
                          color: Colors.white,
                          size: 20,
                        ),
                        tooltip: 'Nova conversa',
                      ),
                    const SizedBox(width: 4),
                  ],
                ),
              ),
            ),
          ),
        ),
        body: _materialsConfirmed
            ? _buildChatBody(context)
            : _buildIntroScreen(context),
      ),
    );
  }

  // ── Intro screen shown before any material is selected ──────────────────
  Widget _buildIntroScreen(BuildContext context) {
    final cs = Theme.of(context).colorScheme;
    final isDark = Theme.of(context).brightness == Brightness.dark;
    final orangeAccent = isDark
        ? const Color(0xFFC47A2A)
        : const Color(0xFFF68D2D);
    final lightOrange = isDark
        ? const Color(0xFFD89035)
        : const Color(0xFFF7A960);

    return SafeArea(
      top: false,
      child: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: isDark
                ? [
                    cs.surfaceVariant,
                    orangeAccent.withValues(alpha: 0.3),
                    cs.surfaceContainerLowest,
                  ]
                : [
                    cs.primary.withValues(alpha: 0.08),
                    orangeAccent.withValues(alpha: 0.05),
                    cs.surfaceContainerLowest,
                  ],
            stops: const [0.0, 0.4, 1.0],
          ),
        ),
        child: LayoutBuilder(
          builder: (context, constraints) {
            return SingleChildScrollView(
              physics: const BouncingScrollPhysics(),
              child: ConstrainedBox(
                constraints: BoxConstraints(minHeight: constraints.maxHeight),
                child: IntrinsicHeight(
                  child: Padding(
                    padding: const EdgeInsets.only(
                      left: 24,
                      right: 24,
                      bottom: 24,
                      top: 52,
                    ),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        const Spacer(flex: 2),
                        // Avatar with animated-like glow (teal to orange gradient)
                        Container(
                          width: 140,
                          height: 140,
                          decoration: BoxDecoration(
                            color: const Color(0xFFF9EEE8),
                            borderRadius: BorderRadius.circular(32),
                            boxShadow: [
                              BoxShadow(
                                color: orangeAccent.withValues(alpha: 0.3),
                                blurRadius: 24,
                                offset: const Offset(0, 10),
                              ),
                            ],
                          ),
                          child: Padding(
                            padding: const EdgeInsets.all(20),
                            child: Image.asset(
                              'assets/images/epvc.png',
                              fit: BoxFit.contain,
                            ),
                          ),
                        ),
                        const SizedBox(height: 28),
                        // Title with orange accent
                        RichText(
                          textAlign: TextAlign.center,
                          text: TextSpan(
                            children: [
                              TextSpan(
                                text: 'Olá! Sou o ',
                                style: TextStyle(
                                  fontSize: 28,
                                  fontWeight: FontWeight.bold,
                                  color: cs.onSurface,
                                ),
                              ),
                              TextSpan(
                                text: 'Vico',
                                style: TextStyle(
                                  fontSize: 28,
                                  fontWeight: FontWeight.bold,
                                  color: orangeAccent,
                                ),
                              ),
                            ],
                          ),
                        ),
                        const SizedBox(height: 12),
                        // Subtitle
                        Text(
                          'O teu assistente de estudo inteligente',
                          textAlign: TextAlign.center,
                          style: TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.w500,
                            color: cs.onSurfaceVariant,
                          ),
                        ),
                        const SizedBox(height: 16),
                        // Description card with orange border accent
                        Container(
                          padding: const EdgeInsets.all(20),
                          decoration: BoxDecoration(
                            color: cs.surface,
                            borderRadius: BorderRadius.circular(20),
                            border: Border.all(
                              color: orangeAccent.withValues(alpha: 0.2),
                              width: 1.5,
                            ),
                            boxShadow: [
                              BoxShadow(
                                color: orangeAccent.withValues(alpha: 0.08),
                                blurRadius: 12,
                                offset: const Offset(0, 4),
                              ),
                            ],
                          ),
                          child: Column(
                            children: [
                              _buildFeatureRow(
                                icon: Icons.menu_book,
                                text:
                                    'Respondo com base nos materiais do teu professor',
                                cs: cs,
                                iconColor: cs.primary,
                              ),
                              const SizedBox(height: 14),
                              _buildFeatureRow(
                                icon: Icons.psychology,
                                text: 'Ajudo-te a perceber conceitos complexos',
                                cs: cs,
                                iconColor: orangeAccent,
                              ),
                              const SizedBox(height: 14),
                              _buildFeatureRow(
                                icon: Icons.quiz,
                                text: 'Prepara-te para testes e exames',
                                cs: cs,
                                iconColor: lightOrange,
                              ),
                            ],
                          ),
                        ),
                        const Spacer(flex: 3),
                        // Action button
                        _availableMaterials.isEmpty
                            ? Column(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  CircularProgressIndicator(
                                    color: orangeAccent,
                                    strokeWidth: 2.5,
                                  ),
                                  const SizedBox(height: 16),
                                  Text(
                                    'A carregar materiais…',
                                    style: TextStyle(
                                      fontSize: 14,
                                      color: cs.onSurfaceVariant,
                                    ),
                                  ),
                                ],
                              )
                            : Container(
                                width: double.infinity,
                                decoration: BoxDecoration(
                                  gradient: LinearGradient(
                                    colors: [cs.primary, orangeAccent],
                                    begin: Alignment.topLeft,
                                    end: Alignment.bottomRight,
                                  ),
                                  borderRadius: BorderRadius.circular(16),
                                  boxShadow: [
                                    BoxShadow(
                                      color: orangeAccent.withValues(
                                        alpha: 0.3,
                                      ),
                                      blurRadius: 12,
                                      offset: const Offset(0, 4),
                                    ),
                                  ],
                                ),
                                child: FilledButton.icon(
                                  onPressed: () =>
                                      _showMaterialsPicker(allowEmpty: true),
                                  icon: const Icon(
                                    Icons.folder_open_rounded,
                                    size: 22,
                                  ),
                                  label: const Text(
                                    'Escolher materiais para estudar',
                                    style: TextStyle(
                                      fontSize: 16,
                                      fontWeight: FontWeight.w600,
                                    ),
                                  ),
                                  style: FilledButton.styleFrom(
                                    padding: const EdgeInsets.symmetric(
                                      horizontal: 28,
                                      vertical: 18,
                                    ),
                                    shape: RoundedRectangleBorder(
                                      borderRadius: BorderRadius.circular(16),
                                    ),
                                    elevation: 0,
                                    backgroundColor: Colors.transparent,
                                    shadowColor: Colors.transparent,
                                  ),
                                ),
                              ),
                        const SizedBox(height: 16),
                        // Secondary hint with orange accent
                        RichText(
                          textAlign: TextAlign.center,
                          text: TextSpan(
                            children: [
                              TextSpan(
                                text: 'Seleciona um ou mais materiais para ',
                                style: TextStyle(
                                  fontSize: 13,
                                  color: cs.onSurfaceVariant.withValues(
                                    alpha: 0.7,
                                  ),
                                ),
                              ),
                              TextSpan(
                                text: 'começar',
                                style: TextStyle(
                                  fontSize: 13,
                                  color: orangeAccent,
                                  fontWeight: FontWeight.w600,
                                ),
                              ),
                            ],
                          ),
                        ),
                        const SizedBox(height: 8),
                      ],
                    ),
                  ),
                ),
              ),
            );
          },
        ),
      ),
    );
  }

  Widget _buildFeatureRow({
    required IconData icon,
    required String text,
    required ColorScheme cs,
    Color? iconColor,
  }) {
    final effectiveIconColor = iconColor ?? cs.primary;
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          padding: const EdgeInsets.all(8),
          decoration: BoxDecoration(
            color: effectiveIconColor.withValues(alpha: 0.1),
            borderRadius: BorderRadius.circular(10),
          ),
          child: Icon(icon, color: effectiveIconColor, size: 20),
        ),
        const SizedBox(width: 14),
        Expanded(
          child: Padding(
            padding: const EdgeInsets.only(top: 8),
            child: Text(
              text,
              style: TextStyle(
                fontSize: 14,
                color: cs.onSurfaceVariant,
                height: 1.4,
              ),
            ),
          ),
        ),
      ],
    );
  }

  // ── Chat body (messages + input) ──────────────────────────────────────────
  Widget _buildChatBody(BuildContext context) {
    final cs = Theme.of(context).colorScheme;
    return Container(
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          colors: [
            cs.primary.withValues(alpha: 0.06),
            cs.surfaceContainerLowest,
            cs.secondary.withValues(alpha: 0.04),
          ],
        ),
      ),
      child: Column(
        children: [
          Expanded(child: _buildMessagesArea(context)),
          if (_isLoading) _buildTypingIndicator(context),
          _buildInputArea(context),
        ],
      ),
    );
  }

  Widget _buildTypingIndicator(BuildContext context) {
    final cs = Theme.of(context).colorScheme;
    return Padding(
      padding: const EdgeInsets.only(left: 16, bottom: 4),
      child: Row(
        children: [
          Container(
            width: 32,
            height: 32,
            decoration: BoxDecoration(
              gradient: LinearGradient(
                colors: [cs.primary, cs.primary.withValues(alpha: 0.7)],
              ),
              borderRadius: BorderRadius.circular(10),
            ),
            child: const Icon(Icons.school, color: Colors.white, size: 18),
          ),
          const SizedBox(width: 8),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
            decoration: BoxDecoration(
              color: cs.surfaceContainerHighest,
              borderRadius: const BorderRadius.only(
                topLeft: Radius.circular(18),
                topRight: Radius.circular(18),
                bottomRight: Radius.circular(18),
                bottomLeft: Radius.circular(4),
              ),
            ),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(
                  'Vico está a escrever',
                  style: TextStyle(fontSize: 12, color: cs.onSurfaceVariant),
                ),
                const SizedBox(width: 6),
                SizedBox(
                  width: 24,
                  height: 12,
                  child: CircularProgressIndicator(
                    strokeWidth: 1.5,
                    color: cs.primary,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildMessagesArea(BuildContext context) {
    return ListView.builder(
      controller: _scrollController,
      padding: const EdgeInsets.fromLTRB(0, 16, 0, 8),
      itemCount: _messages.length,
      itemBuilder: (context, index) {
        final message = _messages[index];
        return _buildMessageBubble(message);
      },
    );
  }

  Widget _buildMessageBubble(Map<String, dynamic> message) {
    final isUser = message['isUser'] as bool;
    final content = message['content'] as String;
    final timestamp = message['timestamp'] as DateTime;
    final cs = Theme.of(context).colorScheme;

    return Padding(
          padding: EdgeInsets.only(
            top: 4,
            bottom: 4,
            left: isUser ? 48 : 16,
            right: isUser ? 16 : 48,
          ),
          child: Column(
            crossAxisAlignment: isUser
                ? CrossAxisAlignment.end
                : CrossAxisAlignment.start,
            children: [
              Row(
                mainAxisAlignment: isUser
                    ? MainAxisAlignment.end
                    : MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  if (!isUser) ...[
                    _buildVicoAvatar(cs),
                    const SizedBox(width: 8),
                  ],
                  Flexible(
                    child: Container(
                      padding: const EdgeInsets.symmetric(
                        horizontal: 14,
                        vertical: 12,
                      ),
                      decoration: BoxDecoration(
                        gradient: isUser
                            ? LinearGradient(
                                colors: [
                                  cs.primary,
                                  cs.secondary.withValues(alpha: 0.85),
                                ],
                                begin: Alignment.topLeft,
                                end: Alignment.bottomRight,
                              )
                            : null,
                        color: isUser ? null : cs.surfaceContainerHighest,
                        borderRadius: BorderRadius.only(
                          topLeft: const Radius.circular(18),
                          topRight: const Radius.circular(18),
                          bottomLeft: Radius.circular(isUser ? 18 : 4),
                          bottomRight: Radius.circular(isUser ? 4 : 18),
                        ),
                        border: isUser
                            ? null
                            : Border(
                                left: BorderSide(
                                  color: cs.primary.withValues(alpha: 0.5),
                                  width: 3,
                                ),
                              ),
                        boxShadow: [
                          BoxShadow(
                            color: (isUser ? cs.primary : Colors.black)
                                .withValues(alpha: 0.08),
                            blurRadius: 8,
                            offset: const Offset(0, 3),
                          ),
                        ],
                      ),
                      child: isUser
                          ? Text(
                              content,
                              style: const TextStyle(
                                color: Colors.white,
                                fontSize: 15,
                                height: 1.45,
                                fontWeight: FontWeight.w500,
                              ),
                            )
                          : MarkdownBody(
                              data: content,
                              styleSheet: MarkdownStyleSheet(
                                p: TextStyle(
                                  color: cs.onSurface,
                                  fontSize: 15,
                                  height: 1.5,
                                ),
                                strong: TextStyle(
                                  color: cs.onSurface,
                                  fontSize: 15,
                                  fontWeight: FontWeight.bold,
                                ),
                                em: TextStyle(
                                  color: cs.onSurface,
                                  fontSize: 15,
                                  fontStyle: FontStyle.italic,
                                ),
                                listBullet: TextStyle(
                                  color: cs.primary,
                                  fontSize: 15,
                                ),
                                code: TextStyle(
                                  backgroundColor: cs.primary.withValues(
                                    alpha: 0.1,
                                  ),
                                  color: cs.primary,
                                  fontSize: 13,
                                ),
                              ),
                            ),
                    ),
                  ),
                  if (isUser) ...[
                    const SizedBox(width: 8),
                    _buildUserAvatar(cs),
                  ],
                ],
              ),
              Padding(
                padding: EdgeInsets.only(
                  top: 3,
                  left: isUser ? 0 : 40,
                  right: isUser ? 40 : 0,
                ),
                child: Text(
                  _formatTimestamp(timestamp),
                  style: TextStyle(fontSize: 10, color: cs.onSurfaceVariant),
                ),
              ),
            ],
          ),
        )
        .animate()
        .fadeIn(duration: const Duration(milliseconds: 250))
        .slideY(
          begin: 0.08,
          end: 0,
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeOut,
        );
  }

  Widget _buildVicoAvatar(ColorScheme cs) {
    return Container(
      width: 32,
      height: 32,
      decoration: BoxDecoration(
        color: const Color(0xFFF9EEE8),
        borderRadius: BorderRadius.circular(10),
        boxShadow: [
          BoxShadow(
            color: cs.primary.withValues(alpha: 0.25),
            blurRadius: 6,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Padding(
        padding: const EdgeInsets.all(6),
        child: Image.asset('assets/images/epvc.png', fit: BoxFit.contain),
      ),
    );
  }

  Widget _buildUserAvatar(ColorScheme cs) {
    return Container(
      width: 32,
      height: 32,
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [cs.secondary, cs.secondary.withValues(alpha: 0.8)],
        ),
        borderRadius: BorderRadius.circular(10),
        boxShadow: [
          BoxShadow(
            color: cs.secondary.withValues(alpha: 0.25),
            blurRadius: 6,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: const Icon(Icons.person, color: Colors.white, size: 18),
    );
  }

  Widget _buildInputArea(BuildContext context) {
    // Get bottom padding to avoid system navigation bar
    final bottomPadding = MediaQuery.of(context).padding.bottom;

    return Container(
      padding: EdgeInsets.only(
        left: 16.0,
        right: 16.0,
        top: 16.0,
        bottom: bottomPadding + 16.0, // Add system navigation bar padding
      ),
      decoration: BoxDecoration(
        color: Theme.of(context).colorScheme.surface.withOpacity(0.95),
        borderRadius: const BorderRadius.vertical(top: Radius.circular(20)),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            blurRadius: 20,
            offset: const Offset(0, -5),
          ),
        ],
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // Chips dos materiais selecionados
          if (_availableMaterials.isNotEmpty)
            Padding(
              padding: const EdgeInsets.only(bottom: 8),
              child: Row(
                children: [
                  Expanded(
                    child: SingleChildScrollView(
                      scrollDirection: Axis.horizontal,
                      child: Row(
                        children: [
                          InkWell(
                            onTap: _showMaterialsPicker,
                            borderRadius: BorderRadius.circular(20),
                            child: Container(
                              padding: const EdgeInsets.symmetric(
                                horizontal: 12,
                                vertical: 6,
                              ),
                              decoration: BoxDecoration(
                                color: _selectedMaterialIds.isEmpty
                                    ? Theme.of(
                                        context,
                                      ).colorScheme.outline.withOpacity(0.15)
                                    : Theme.of(
                                        context,
                                      ).colorScheme.primary.withOpacity(0.12),
                                borderRadius: BorderRadius.circular(20),
                                border: Border.all(
                                  color: _selectedMaterialIds.isEmpty
                                      ? Theme.of(
                                          context,
                                        ).colorScheme.outline.withOpacity(0.4)
                                      : Theme.of(
                                          context,
                                        ).colorScheme.primary.withOpacity(0.5),
                                ),
                              ),
                              child: Row(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  Icon(
                                    Icons.attach_file,
                                    size: 14,
                                    color: _selectedMaterialIds.isEmpty
                                        ? Theme.of(
                                            context,
                                          ).colorScheme.onSurfaceVariant
                                        : Theme.of(context).colorScheme.primary,
                                  ),
                                  const SizedBox(width: 4),
                                  Text(
                                    _selectedMaterialIds.isEmpty
                                        ? 'Materiais'
                                        : '${_selectedMaterialIds.length} selecionado(s)',
                                    style: TextStyle(
                                      fontSize: 12,
                                      color: _selectedMaterialIds.isEmpty
                                          ? Theme.of(
                                              context,
                                            ).colorScheme.onSurfaceVariant
                                          : Theme.of(
                                              context,
                                            ).colorScheme.primary,
                                      fontWeight: FontWeight.w500,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ),
                          if (_selectedMaterialIds.isNotEmpty)
                            ..._selectedMaterialIds.map((id) {
                              final material = _availableMaterials.firstWhere(
                                (m) => m['id'] == id,
                                orElse: () => {'id': id, 'name': id},
                              );
                              final name = material['name'] ?? id;
                              final url = material['url'];
                              final cleanName = name
                                  .replaceAll('.pdf', '')
                                  .replaceAll('_', ' ');
                              final short = cleanName.length > 18
                                  ? '${cleanName.substring(0, 16)}…'
                                  : cleanName;
                              const chipBg = Color(0xFFF68D2D);
                              final isLast = _selectedMaterialIds.length == 1;
                              return Padding(
                                padding: const EdgeInsets.only(left: 6),
                                child: InkWell(
                                  onTap: url != null
                                      ? () {
                                          Navigator.push(
                                            context,
                                            MaterialPageRoute(
                                              builder: (context) =>
                                                  PdfViewerPage(
                                                    url: url,
                                                    fileName: name,
                                                  ),
                                            ),
                                          );
                                        }
                                      : null,
                                  borderRadius: BorderRadius.circular(20),
                                  child: Chip(
                                    label: Text(
                                      short,
                                      style: const TextStyle(
                                        fontSize: 11,
                                        color: Colors.white,
                                        fontWeight: FontWeight.w600,
                                      ),
                                    ),
                                    backgroundColor: chipBg,
                                    deleteIconColor: Colors.white.withValues(
                                      alpha: 0.85,
                                    ),
                                    deleteIcon: const Icon(
                                      Icons.close,
                                      size: 14,
                                    ),
                                    onDeleted: () {
                                      if (isLast) {
                                        ScaffoldMessenger.of(context)
                                          ..clearSnackBars()
                                          ..showSnackBar(
                                            SnackBar(
                                              behavior:
                                                  SnackBarBehavior.floating,
                                              margin:
                                                  const EdgeInsets.symmetric(
                                                    horizontal: 20,
                                                    vertical: 12,
                                                  ),
                                              backgroundColor: const Color(
                                                0xFFF68D2D,
                                              ),
                                              shape: RoundedRectangleBorder(
                                                borderRadius:
                                                    BorderRadius.circular(12),
                                              ),
                                              duration: const Duration(
                                                seconds: 2,
                                              ),
                                              content: const Row(
                                                children: [
                                                  Icon(
                                                    Icons.warning_amber_rounded,
                                                    color: Colors.white,
                                                    size: 20,
                                                  ),
                                                  SizedBox(width: 10),
                                                  Expanded(
                                                    child: Text(
                                                      'Tens de manter pelo menos um material selecionado.',
                                                      style: TextStyle(
                                                        color: Colors.white,
                                                        fontSize: 13,
                                                        fontWeight:
                                                            FontWeight.w500,
                                                      ),
                                                    ),
                                                  ),
                                                ],
                                              ),
                                            ),
                                          );
                                      } else {
                                        setState(
                                          () => _selectedMaterialIds.remove(id),
                                        );
                                      }
                                    },
                                    materialTapTargetSize:
                                        MaterialTapTargetSize.shrinkWrap,
                                    padding: const EdgeInsets.symmetric(
                                      horizontal: 4,
                                    ),
                                    visualDensity: VisualDensity.compact,
                                  ),
                                ),
                              );
                            }).toList(),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
          Container(
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(16),
              color: Theme.of(context).colorScheme.surface,
              border: Border.all(
                color: Theme.of(context).colorScheme.outline.withOpacity(0.5),
                width: 1,
              ),
            ),
            child: Row(
              children: [
                // Text field
                Expanded(
                  child: TextField(
                    controller: _messageController,
                    focusNode: _messageFocusNode,
                    autofocus: false,
                    style: TextStyle(
                      fontSize: 16,
                      color: Theme.of(context).colorScheme.onSurface,
                      fontWeight: FontWeight.w500,
                    ),
                    decoration: InputDecoration(
                      border: InputBorder.none,
                      contentPadding: const EdgeInsets.symmetric(
                        horizontal: 16,
                        vertical: 14,
                      ),
                      hintText: 'Faz a tua pergunta!',
                      hintStyle: TextStyle(
                        color: Theme.of(context).colorScheme.onSurfaceVariant,
                        fontWeight: FontWeight.w400,
                        fontSize: 16,
                      ),
                    ),
                    onSubmitted: (_) => _handleSendMessage(),
                    textInputAction: TextInputAction.send,
                    onChanged: (value) {
                      Logger.info(
                        'TextField changed. Text: "$value", isEmpty: ${value.isEmpty}',
                      );
                      setState(() {});
                    },
                  ),
                ),

                // Send button
                Padding(
                  padding: const EdgeInsets.only(right: 8.0),
                  child: Container(
                    width: 44,
                    height: 44,
                    decoration: BoxDecoration(
                      gradient: _messageController.text.isNotEmpty
                          ? LinearGradient(
                              colors: [
                                Theme.of(context).colorScheme.primary,
                                Theme.of(
                                  context,
                                ).colorScheme.primary.withOpacity(0.8),
                              ],
                              begin: Alignment.topLeft,
                              end: Alignment.bottomRight,
                            )
                          : null,
                      color: _messageController.text.isNotEmpty
                          ? null
                          : Theme.of(
                              context,
                            ).colorScheme.outline.withOpacity(0.3),
                      borderRadius: BorderRadius.circular(22),
                      boxShadow: _messageController.text.isNotEmpty
                          ? [
                              BoxShadow(
                                color: Theme.of(
                                  context,
                                ).colorScheme.primary.withOpacity(0.3),
                                blurRadius: 8,
                                offset: const Offset(0, 2),
                              ),
                            ]
                          : null,
                    ),
                    child: IconButton(
                      onPressed:
                          _messageController.text.isNotEmpty && !_isLoading
                          ? _handleSendMessage
                          : null,
                      icon: _isLoading
                          ? SizedBox(
                              width: 18,
                              height: 18,
                              child: CircularProgressIndicator(
                                strokeWidth: 2,
                                valueColor: AlwaysStoppedAnimation<Color>(
                                  Colors.white,
                                ),
                              ),
                            )
                          : Icon(Icons.send, color: Colors.white, size: 18),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // Group materials by classId; ungrouped go to '__geral__'
  Map<String, List<Map<String, String>>> _groupMaterialsByClass() {
    final groups = <String, List<Map<String, String>>>{};
    for (final m in _availableMaterials) {
      final cid = m['classId'];
      final key = (cid != null && _classNames.containsKey(cid))
          ? cid
          : '__geral__';
      groups.putIfAbsent(key, () => []).add(m);
    }
    return groups;
  }

  void _showMaterialsPicker({bool allowEmpty = true}) {
    final groups = _groupMaterialsByClass();
    final disciplineIds = groups.keys.where((k) => k != '__geral__').toList()
      ..sort((a, b) => (_classNames[a] ?? a).compareTo(_classNames[b] ?? b));
    if (groups.containsKey('__geral__')) disciplineIds.add('__geral__');

    showDialog(
      context: context,
      builder: (dialogContext) {
        final tempSelected = Set<String>.from(_selectedMaterialIds);
        // Disciplines start collapsed
        final expanded = <String, bool>{
          for (final k in disciplineIds) k: false,
        };
        final searchController = TextEditingController();
        String searchQuery = '';
        return StatefulBuilder(
          builder: (context, setDialogState) {
            final cs = Theme.of(context).colorScheme;
            // Filter groups by search query
            final filteredDisciplineIds = disciplineIds.where((groupKey) {
              if (searchQuery.isEmpty) return true;
              final q = searchQuery.toLowerCase();
              final label = groupKey == '__geral__'
                  ? 'geral'
                  : (_classNames[groupKey] ?? groupKey).toLowerCase();
              if (label.contains(q)) return true;
              return (groups[groupKey] ?? []).any(
                (m) => (m['name'] ?? '').toLowerCase().contains(q),
              );
            }).toList();
            // Auto-expand disciplines that match by material name (not discipline name)
            for (final groupKey in filteredDisciplineIds) {
              if (searchQuery.isNotEmpty) {
                final q = searchQuery.toLowerCase();
                final label = groupKey == '__geral__'
                    ? 'geral'
                    : (_classNames[groupKey] ?? groupKey).toLowerCase();
                if (!label.contains(q)) expanded[groupKey] = true;
              }
            }
            final viewInsets = MediaQuery.of(context).viewInsets;
            final screenHeight = MediaQuery.of(context).size.height;
            // Leave room for keyboard + dialog chrome (~360px for title/search/actions/padding)
            final listMaxHeight = (screenHeight - viewInsets.bottom - 360)
                .clamp(60.0, 340.0);
            return AlertDialog(
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(16),
              ),
              title: const Text(
                'Escolher Materiais',
                style: TextStyle(fontWeight: FontWeight.bold),
              ),
              content: SizedBox(
                width: double.maxFinite,
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // Search bar
                    TextField(
                      controller: searchController,
                      onChanged: (v) =>
                          setDialogState(() => searchQuery = v.trim()),
                      style: TextStyle(fontSize: 13, color: cs.onSurface),
                      decoration: InputDecoration(
                        hintText: 'Pesquisar disciplina ou material…',
                        hintStyle: TextStyle(
                          fontSize: 13,
                          color: cs.onSurfaceVariant,
                        ),
                        prefixIcon: Icon(
                          Icons.search,
                          size: 18,
                          color: cs.onSurfaceVariant,
                        ),
                        suffixIcon: searchQuery.isNotEmpty
                            ? IconButton(
                                icon: Icon(
                                  Icons.close,
                                  size: 16,
                                  color: cs.onSurfaceVariant,
                                ),
                                onPressed: () {
                                  searchController.clear();
                                  setDialogState(() => searchQuery = '');
                                },
                              )
                            : null,
                        isDense: true,
                        contentPadding: const EdgeInsets.symmetric(
                          horizontal: 12,
                          vertical: 10,
                        ),
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(10),
                          borderSide: BorderSide(
                            color: cs.outline.withValues(alpha: 0.4),
                          ),
                        ),
                        enabledBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(10),
                          borderSide: BorderSide(
                            color: cs.outline.withValues(alpha: 0.3),
                          ),
                        ),
                        focusedBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(10),
                          borderSide: BorderSide(color: cs.primary),
                        ),
                      ),
                    ),
                    const SizedBox(height: 12),
                    if (filteredDisciplineIds.isEmpty)
                      SizedBox(
                        height: 36,
                        child: Center(
                          child: Text(
                            'Nenhum resultado para "$searchQuery"',
                            style: TextStyle(
                              fontSize: 13,
                              color: cs.onSurfaceVariant,
                            ),
                            textAlign: TextAlign.center,
                          ),
                        ),
                      )
                    else
                      ConstrainedBox(
                        constraints: BoxConstraints(maxHeight: listMaxHeight),
                        child: ListView(
                          shrinkWrap: true,
                          children: filteredDisciplineIds.map((groupKey) {
                            // When searching, filter materials too
                            final allMats = groups[groupKey]!;
                            final mats = searchQuery.isEmpty
                                ? allMats
                                : allMats.where((m) {
                                    final q = searchQuery.toLowerCase();
                                    final label = groupKey == '__geral__'
                                        ? 'geral'
                                        : (_classNames[groupKey] ?? '')
                                              .toLowerCase();
                                    return label.contains(q) ||
                                        (m['name'] ?? '')
                                            .toLowerCase()
                                            .contains(q);
                                  }).toList();
                            final label = groupKey == '__geral__'
                                ? 'Geral'
                                : (_classNames[groupKey] ?? groupKey);
                            final isExpanded = expanded[groupKey] ?? false;
                            // Count how many in this group are selected
                            final selectedInGroup = mats
                                .where((m) => tempSelected.contains(m['id']))
                                .length;
                            return Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                // Discipline header row
                                InkWell(
                                  borderRadius: BorderRadius.circular(8),
                                  onTap: () => setDialogState(
                                    () => expanded[groupKey] = !isExpanded,
                                  ),
                                  child: Container(
                                    padding: const EdgeInsets.symmetric(
                                      horizontal: 8,
                                      vertical: 8,
                                    ),
                                    decoration: BoxDecoration(
                                      color: cs.primary.withValues(alpha: 0.07),
                                      borderRadius: BorderRadius.circular(8),
                                    ),
                                    child: Row(
                                      children: [
                                        Icon(
                                          Icons.folder_outlined,
                                          size: 16,
                                          color: cs.primary,
                                        ),
                                        const SizedBox(width: 6),
                                        Expanded(
                                          child: Text(
                                            label,
                                            style: TextStyle(
                                              fontSize: 13,
                                              fontWeight: FontWeight.w700,
                                              color: cs.primary,
                                            ),
                                          ),
                                        ),
                                        if (selectedInGroup > 0)
                                          Container(
                                            padding: const EdgeInsets.symmetric(
                                              horizontal: 6,
                                              vertical: 2,
                                            ),
                                            decoration: BoxDecoration(
                                              color: cs.primary.withValues(
                                                alpha: 0.15,
                                              ),
                                              borderRadius:
                                                  BorderRadius.circular(10),
                                            ),
                                            child: Text(
                                              '$selectedInGroup',
                                              style: TextStyle(
                                                fontSize: 11,
                                                fontWeight: FontWeight.bold,
                                                color: cs.primary,
                                              ),
                                            ),
                                          ),
                                        const SizedBox(width: 4),
                                        Icon(
                                          isExpanded
                                              ? Icons.expand_less
                                              : Icons.expand_more,
                                          size: 18,
                                          color: cs.onSurfaceVariant,
                                        ),
                                      ],
                                    ),
                                  ),
                                ),
                                // Material items
                                if (isExpanded)
                                  ...mats.map((material) {
                                    final id = material['id']!;
                                    final name = material['name']!;
                                    final cleanName = name
                                        .replaceAll('.pdf', '')
                                        .replaceAll('_', ' ');
                                    final isChecked = tempSelected.contains(id);
                                    return CheckboxListTile(
                                      value: isChecked,
                                      onChanged: (val) {
                                        setDialogState(() {
                                          if (val == true) {
                                            tempSelected.add(id);
                                          } else {
                                            tempSelected.remove(id);
                                          }
                                        });
                                      },
                                      title: Text(
                                        cleanName,
                                        style: const TextStyle(fontSize: 13),
                                        maxLines: 2,
                                        overflow: TextOverflow.ellipsis,
                                      ),
                                      controlAffinity:
                                          ListTileControlAffinity.leading,
                                      dense: true,
                                      contentPadding: const EdgeInsets.only(
                                        left: 16,
                                      ),
                                    );
                                  }),
                                const SizedBox(height: 6),
                              ],
                            );
                          }).toList(),
                        ),
                      ),
                  ],
                ),
              ),
              actions: [
                ElevatedButton(
                  onPressed: tempSelected.isEmpty
                      ? null
                      : () async {
                          final isFirst = !_materialsConfirmed;
                          final selectionChanged =
                              !tempSelected.containsAll(_selectedMaterialIds) ||
                              !_selectedMaterialIds.containsAll(tempSelected);

                          // Create new conversation if materials changed or first time
                          if (isFirst || selectionChanged) {
                            final newConversationId =
                                await ChatMemoryService.createConversation(
                                  selectedMaterialIds: tempSelected.toList(),
                                  title: 'Nova conversa',
                                );
                            ChatMemoryService.setCurrentConversationId(
                              newConversationId,
                            );

                            // Update title based on first message if exists
                            if (_messages.isNotEmpty &&
                                _messages.first['isUser'] == true) {
                              final firstMessage =
                                  _messages.first['content'] as String;
                              final title = firstMessage.length > 30
                                  ? '${firstMessage.substring(0, 30)}...'
                                  : firstMessage;
                              await ChatMemoryService.updateConversationTitle(
                                conversationId: newConversationId,
                                title: title,
                              );
                            }
                          } else {
                            // Update materials in existing conversation
                            final currentId =
                                ChatMemoryService.currentConversationId;
                            if (currentId != null) {
                              await ChatMemoryService.updateConversationMaterials(
                                conversationId: currentId,
                                selectedMaterialIds: tempSelected.toList(),
                              );
                            }
                          }

                          setState(() {
                            _selectedMaterialIds = tempSelected;
                            _materialsConfirmed = true;
                          });
                          if (isFirst) _addWelcomeMessage();
                          if (selectionChanged) {
                            RAGAIService.clearLastContext();
                          }
                          Navigator.of(dialogContext).pop();
                          _messageFocusNode.unfocus();
                        },
                  style: ElevatedButton.styleFrom(
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(10),
                    ),
                  ),
                  child: const Text('Confirmar'),
                ),
              ],
            );
          },
        );
      },
    );
  }

  void _addWelcomeMessage() {
    final welcomeText =
        'Olá! Estou pronto para te ajudar com os materiais que selecionaste. Faz a tua pergunta sempre que quiseres! 💪';
    final welcomeMessage = {
      'content': welcomeText,
      'isUser': false,
      'timestamp': DateTime.now(),
    };

    setState(() {
      _messages.add(welcomeMessage);
    });

    // Save welcome message to Firestore so the AI knows it already greeted the user
    ChatMemoryService.saveMessage(role: 'assistant', content: welcomeText);

    WidgetsBinding.instance.addPostFrameCallback((_) {
      _scrollToBottom();
    });
  }

  /// Get names of selected materials
  List<String> _getSelectedMaterialNames() {
    return _selectedMaterialIds.map((id) {
      final material = _availableMaterials.firstWhere(
        (m) => m['id'] == id,
        orElse: () => {'id': id, 'name': 'Material'},
      );
      return material['name'] ?? 'Material';
    }).toList();
  }

  /// Determine discipline name from selected materials
  String? _getDisciplineName() {
    if (_selectedMaterialIds.isEmpty) return null;
    // Find classId of first selected material
    final firstId = _selectedMaterialIds.first;
    final material = _availableMaterials.firstWhere(
      (m) => m['id'] == firstId,
      orElse: () => {},
    );
    final classId = material['classId'];
    if (classId != null && _classNames.containsKey(classId)) {
      return _classNames[classId];
    }
    return null;
  }

  /// Detect if current discipline is mathematics
  bool _isMathematics() {
    final discipline = _getDisciplineName();
    if (discipline == null) return false;
    final lower = discipline.toLowerCase();
    final mathKeywords = [
      'matemática',
      'matematica',
      'math',
      'álgebra',
      'algebra',
      'geometria',
      'cálculo',
      'calculo',
      'estatística',
      'estatistica',
      'física',
      'fisica',
      'química',
      'quimica',
    ];
    return mathKeywords.any((k) => lower.contains(k));
  }

  Future<void> _handleSendMessage() async {
    if (_messageController.text.trim().isEmpty) return;

    final userMessage = _messageController.text.trim();
    Logger.info(
      'Attempting to send message. currentConversationId: ${ChatMemoryService.currentConversationId}',
    );

    // Update conversation title if it's still the default "Nova conversa"
    final currentId = ChatMemoryService.currentConversationId;
    if (currentId != null) {
      final conversation = await ChatMemoryService.getConversation(currentId);
      if (conversation != null && conversation['title'] == 'Nova conversa') {
        final title = ChatMemoryService.generateConversationTitle(userMessage);
        await ChatMemoryService.updateConversationTitle(
          conversationId: currentId,
          title: title,
        );
      }
    }

    // Add user message
    setState(() {
      _messages.add(<String, dynamic>{
        'content': userMessage,
        'isUser': true,
        'timestamp': DateTime.now(),
      });
      _isLoading = true;
    });

    _messageController.clear();
    _scrollToBottom();

    try {
      // Use RAGAIService with memory, PDFs, and O GOAT identity
      Logger.info('USING RAG AI SERVICE');

      final replyText = await RAGAIService.ask(
        userMessage,
        selectedMaterialIds: _selectedMaterialIds.isEmpty
            ? null
            : _selectedMaterialIds.toList(),
        selectedMaterialNames: _selectedMaterialIds.isEmpty
            ? null
            : _getSelectedMaterialNames(),
        disciplineName: _getDisciplineName(),
        isMathematics: _isMathematics(),
      );

      final preview = replyText.length > 50
          ? replyText.substring(0, 50)
          : replyText;
      Logger.info('Ollama response received: $preview...');

      setState(() {
        _messages.add(<String, dynamic>{
          'content': replyText,
          'isUser': false,
          'timestamp': DateTime.now(),
        });
        _isLoading = false;
      });
    } catch (e) {
      // Fallback to error message if API fails
      Logger.error('RAG AI Service error: $e');
      final aiResponse =
          'Desculpe, ocorreu um erro ao processar a pergunta. Tente novamente.';

      setState(() {
        _messages.add(<String, dynamic>{
          'content': aiResponse,
          'isUser': false,
          'timestamp': DateTime.now(),
        });
        _isLoading = false;
      });
    }

    _scrollToBottom();
  }

  void _scrollToBottom() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (_scrollController.hasClients) {
        _scrollController.animateTo(
          _scrollController.position.maxScrollExtent,
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeOut,
        );
      }
    });
  }

  String _formatTimestamp(DateTime timestamp) {
    final now = DateTime.now();
    final difference = now.difference(timestamp);

    if (difference.inMinutes < 1) {
      return 'Agora';
    } else if (difference.inMinutes < 60) {
      return '${difference.inMinutes} min atrás';
    } else if (difference.inHours < 24) {
      return '${difference.inHours} h atrás';
    } else {
      return '${difference.inDays} dias atrás';
    }
  }
}

/// Widget para texto com scrolling horizontal (Marquee)
class MarqueeText extends StatefulWidget {
  final String text;
  final TextStyle style;
  final Duration duration;
  final double scrollSpeed;

  const MarqueeText({
    super.key,
    required this.text,
    required this.style,
    this.duration = const Duration(seconds: 8),
    this.scrollSpeed = 50.0,
  });

  @override
  State<MarqueeText> createState() => _MarqueeTextState();
}

class _MarqueeTextState extends State<MarqueeText>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double> _animation;
  final GlobalKey _textKey = GlobalKey();
  double _textWidth = 0;
  double _containerWidth = 0;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(duration: widget.duration, vsync: this);
    _animation = Tween<double>(begin: 0, end: 1).animate(_controller);

    WidgetsBinding.instance.addPostFrameCallback((_) {
      _measureText();
    });
  }

  void _measureText() {
    final RenderBox? textRenderBox =
        _textKey.currentContext?.findRenderObject() as RenderBox?;
    if (textRenderBox != null) {
      _textWidth = textRenderBox.size.width;
      final RenderBox? containerRenderBox =
          context.findRenderObject() as RenderBox?;
      if (containerRenderBox != null) {
        _containerWidth = containerRenderBox.size.width;
        if (_textWidth > _containerWidth) {
          _controller.repeat();
        }
      }
    }
  }

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

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: _animation,
      builder: (context, child) {
        return LayoutBuilder(
          builder: (context, constraints) {
            if (_textWidth <= constraints.maxWidth) {
              return Text(widget.text, style: widget.style, key: _textKey);
            }

            return Stack(
              children: [
                Positioned(
                  left: -(_textWidth - constraints.maxWidth) * _animation.value,
                  child: Text(widget.text, style: widget.style, key: _textKey),
                ),
              ],
            );
          },
        );
      },
    );
  }
}
