import 'package:flutter/material.dart';
import 'package:flutter_animate/flutter_animate.dart';
import 'package:go_router/go_router.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import '../../../../core/services/chat_memory_service.dart';
import '../../../../core/theme/app_colors.dart';
import '../../../../core/utils/logger.dart';

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

  @override
  State<ChatHistoryPage> createState() => _ChatHistoryPageState();
}

class _ChatHistoryPageState extends State<ChatHistoryPage> {
  List<Map<String, dynamic>> _conversations = [];
  List<Map<String, dynamic>> _filteredConversations = [];
  bool _isLoading = true;
  final TextEditingController _searchController = TextEditingController();
  String _selectedDateFilter = 'all'; // all, today, yesterday, week, month
  final Set<String> _selectedConversationIds = {};
  bool _isSelectionMode = false;
  final Map<String, String> _materialNamesCache = {}; // materialId -> fileName
  String? _source; // 'chat' or 'intro'
  String? _previousConversationId;

  @override
  void initState() {
    super.initState();
    _loadConversations();
    _searchController.addListener(_filterConversations);
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    // Extract source and previous conversation ID from URL parameters
    final uri = GoRouterState.of(context).uri;
    _source = uri.queryParameters['source'];
    _previousConversationId = uri.queryParameters['conversationId'];
  }

  void _handleBackNavigation() {
    if (_source == 'chat' && _previousConversationId != null) {
      // Go back to the previous conversation
      context.go('/ai-tutor/$_previousConversationId');
    } else if (_source == 'chat') {
      // Go to new chat (no previous conversation)
      context.go('/ai-tutor');
    } else if (_source == 'intro') {
      // Go back to intro screen
      context.go('/ai-tutor');
    } else {
      // Default: go to intro screen (from dashboard or other sources)
      context.go('/ai-tutor');
    }
  }

  /// Fetch material names for given material IDs
  Future<void> _loadMaterialNames(List<String> materialIds) async {
    if (materialIds.isEmpty) return;

    final uncachedIds = materialIds
        .where((id) => !_materialNamesCache.containsKey(id))
        .toList();
    if (uncachedIds.isEmpty) return;

    try {
      final batches = <Future<QuerySnapshot>>[];
      for (int i = 0; i < uncachedIds.length; i += 10) {
        final batch = uncachedIds.skip(i).take(10).toList();
        batches.add(
          FirebaseFirestore.instance
              .collection('materials')
              .where(FieldPath.documentId, whereIn: batch)
              .get(),
        );
      }

      final results = await Future.wait(batches);
      for (final snapshot in results) {
        for (final doc in snapshot.docs) {
          final data = doc.data() as Map<String, dynamic>?;
          if (data != null) {
            final fileName = data['fileName'] as String?;
            if (fileName != null) {
              _materialNamesCache[doc.id] = fileName;
            }
          }
        }
      }

      if (mounted) {
        setState(() {});
      }
    } catch (e) {
      Logger.error('Error loading material names: $e');
    }
  }

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

  Future<void> _loadConversations() async {
    setState(() => _isLoading = true);
    try {
      final conversations = await ChatMemoryService.getConversations();

      // Collect all material IDs from all conversations
      final allMaterialIds = <String>[];
      for (final conv in conversations) {
        final materialIds = conv['selectedMaterialIds'] as List<String>? ?? [];
        allMaterialIds.addAll(materialIds);
      }

      // Load material names
      await _loadMaterialNames(allMaterialIds);

      if (mounted) {
        setState(() {
          _conversations = conversations;
          _filteredConversations = conversations;
          _isLoading = false;
        });
      }
    } catch (e) {
      Logger.error('Error loading conversations: $e');
      if (mounted) {
        setState(() => _isLoading = false);
      }
    }
  }

  void _toggleSelectionMode() {
    setState(() {
      _isSelectionMode = !_isSelectionMode;
      if (!_isSelectionMode) {
        _selectedConversationIds.clear();
      }
    });
  }

  void _toggleConversationSelection(String conversationId) {
    setState(() {
      if (_selectedConversationIds.contains(conversationId)) {
        _selectedConversationIds.remove(conversationId);
      } else {
        _selectedConversationIds.add(conversationId);
      }
    });
  }

  Future<void> _deleteSelectedConversations() async {
    if (_selectedConversationIds.isEmpty) return;

    final confirmed = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('Eliminar ${_selectedConversationIds.length} conversas'),
        content: const Text('Tem certeza que deseja eliminar estas conversas?'),
        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('Eliminar'),
          ),
        ],
      ),
    );

    if (confirmed != true) return;

    try {
      for (final id in _selectedConversationIds) {
        await ChatMemoryService.deleteConversation(id);
      }
      await _loadConversations();
      setState(() {
        _selectedConversationIds.clear();
        _isSelectionMode = false;
      });
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Row(
              children: [
                const Icon(Icons.delete_outline, color: Colors.white),
                const SizedBox(width: 12),
                const Text('Conversas eliminadas'),
              ],
            ),
            backgroundColor: Colors.orange,
            behavior: SnackBarBehavior.floating,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(12),
            ),
          ),
        );
      }
    } catch (e) {
      Logger.error('Error deleting conversations: $e');
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Row(
              children: [
                const Icon(Icons.error_outline, color: Colors.white),
                const SizedBox(width: 12),
                const Text('Erro ao eliminar conversas'),
              ],
            ),
            backgroundColor: Colors.orange,
            behavior: SnackBarBehavior.floating,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(12),
            ),
          ),
        );
      }
    }
  }

  void _filterConversations() {
    final searchQuery = _searchController.text.toLowerCase();
    setState(() {
      _filteredConversations = _conversations.where((conv) {
        // Filter by search query (title)
        final title = (conv['title'] as String? ?? '').toLowerCase();
        final matchesSearch = title.contains(searchQuery);

        // Filter by date
        final matchesDate = _matchesDateFilter(conv);

        return matchesSearch && matchesDate;
      }).toList();
    });
  }

  bool _matchesDateFilter(Map<String, dynamic> conv) {
    final updatedAt = conv['updatedAt'] as Timestamp?;
    if (updatedAt == null) return true;
    final date = updatedAt.toDate();
    final now = DateTime.now();
    final difference = now.difference(date);

    switch (_selectedDateFilter) {
      case 'today':
        return difference.inDays == 0;
      case 'yesterday':
        return difference.inDays == 1;
      case 'week':
        return difference.inDays < 7;
      case 'month':
        return difference.inDays < 30;
      default:
        return true;
    }
  }

  Future<void> _deleteConversation(String conversationId) async {
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Eliminar conversa'),
        content: const Text('Tem certeza que deseja eliminar esta conversa?'),
        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('Eliminar'),
          ),
        ],
      ),
    );

    if (confirmed != true) return;

    try {
      await ChatMemoryService.deleteConversation(conversationId);
      await _loadConversations();
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Row(
              children: [
                const Icon(Icons.delete_outline, color: Colors.white),
                const SizedBox(width: 12),
                const Text('Conversa eliminada'),
              ],
            ),
            backgroundColor: Colors.orange,
            behavior: SnackBarBehavior.floating,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(12),
            ),
          ),
        );
      }
    } catch (e) {
      Logger.error('Error deleting conversation: $e');
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Row(
              children: [
                const Icon(Icons.error_outline, color: Colors.white),
                const SizedBox(width: 12),
                const Text('Erro ao eliminar conversa'),
              ],
            ),
            backgroundColor: Colors.orange,
            behavior: SnackBarBehavior.floating,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(12),
            ),
          ),
        );
      }
    }
  }

  String _formatDate(Timestamp? timestamp) {
    if (timestamp == null) return '';
    final date = timestamp.toDate();
    final now = DateTime.now();
    final difference = now.difference(date);

    if (difference.inDays == 0) {
      return 'Hoje ${date.hour.toString().padLeft(2, '0')}:${date.minute.toString().padLeft(2, '0')}';
    } else if (difference.inDays == 1) {
      return 'Ontem';
    } else if (difference.inDays < 7) {
      return '${difference.inDays} dias atrás';
    } else {
      return '${date.day}/${date.month}/${date.year}';
    }
  }

  @override
  Widget build(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 PopScope(
      canPop: false,
      onPopInvokedWithResult: (didPop, result) {
        if (didPop) return;
        _handleBackNavigation();
      },
      child: Scaffold(
        body: 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: SafeArea(
            top: false,
            child: Column(
              children: [
                // Custom app bar
                Container(
                  padding: const EdgeInsets.symmetric(
                    horizontal: 8,
                    vertical: 15,
                  ),
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      colors: [cs.primary, orangeAccent],
                      begin: Alignment.topLeft,
                      end: Alignment.bottomRight,
                    ),
                    boxShadow: [
                      BoxShadow(
                        color: orangeAccent.withValues(alpha: 0.2),
                        blurRadius: 8,
                        offset: const Offset(0, 2),
                      ),
                    ],
                  ),
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      IconButton(
                        icon: const Icon(
                          Icons.arrow_back_ios_new,
                          color: Colors.white,
                          size: 20,
                        ),
                        onPressed: _handleBackNavigation,
                      ),
                      const SizedBox(width: 8),
                      Expanded(
                        child: Text(
                          _isSelectionMode
                              ? '${_selectedConversationIds.length} selecionadas'
                              : 'Histórico',
                          style: const TextStyle(
                            color: Colors.white,
                            fontSize: 20,
                            fontWeight: FontWeight.bold,
                          ),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                      if (_isSelectionMode)
                        IconButton(
                          icon: const Icon(Icons.delete, color: Colors.white),
                          onPressed: _selectedConversationIds.isEmpty
                              ? null
                              : _deleteSelectedConversations,
                        )
                      else
                        IconButton(
                          icon: const Icon(
                            Icons.checklist,
                            color: Colors.white,
                          ),
                          onPressed: _toggleSelectionMode,
                        ),
                      if (!_isSelectionMode)
                        IconButton(
                          icon: const Icon(Icons.refresh, color: Colors.white),
                          onPressed: _loadConversations,
                        ),
                      if (_isSelectionMode)
                        IconButton(
                          icon: const Icon(Icons.close, color: Colors.white),
                          onPressed: _toggleSelectionMode,
                        ),
                    ],
                  ),
                ),
                // Search and filters
                Padding(
                  padding: const EdgeInsets.all(16),
                  child: Column(
                    children: [
                      // Search bar
                      TextField(
                        controller: _searchController,
                        decoration: InputDecoration(
                          hintText: 'Pesquisar conversas...',
                          prefixIcon: const Icon(Icons.search),
                          suffixIcon: _searchController.text.isNotEmpty
                              ? IconButton(
                                  icon: const Icon(Icons.clear),
                                  onPressed: () {
                                    _searchController.clear();
                                  },
                                )
                              : null,
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(16),
                            borderSide: BorderSide(
                              color: orangeAccent.withValues(alpha: 0.3),
                            ),
                          ),
                          enabledBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(16),
                            borderSide: BorderSide(
                              color: orangeAccent.withValues(alpha: 0.3),
                            ),
                          ),
                          focusedBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(16),
                            borderSide: const BorderSide(
                              color: AppColors.primaryOrange,
                              width: 2,
                            ),
                          ),
                          filled: true,
                          fillColor: cs.surface,
                        ),
                      ),
                      const SizedBox(height: 12),
                      // Date filter chips
                      SingleChildScrollView(
                        scrollDirection: Axis.horizontal,
                        child: Row(
                          children: [
                            _buildDateFilterChip(
                              'Todas',
                              'all',
                              cs,
                              orangeAccent,
                            ),
                            const SizedBox(width: 8),
                            _buildDateFilterChip(
                              'Hoje',
                              'today',
                              cs,
                              orangeAccent,
                            ),
                            const SizedBox(width: 8),
                            _buildDateFilterChip(
                              'Ontem',
                              'yesterday',
                              cs,
                              orangeAccent,
                            ),
                            const SizedBox(width: 8),
                            _buildDateFilterChip(
                              'Semana',
                              'week',
                              cs,
                              orangeAccent,
                            ),
                            const SizedBox(width: 8),
                            _buildDateFilterChip(
                              'Mês',
                              'month',
                              cs,
                              orangeAccent,
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
                // Conversation list
                Expanded(
                  child: _isLoading
                      ? Center(
                          child: CircularProgressIndicator(color: orangeAccent),
                        )
                      : _filteredConversations.isEmpty
                      ? Center(
                          child: Padding(
                            padding: const EdgeInsets.all(32),
                            child: Column(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                Container(
                                  width: 80,
                                  height: 80,
                                  decoration: BoxDecoration(
                                    gradient: LinearGradient(
                                      colors: [cs.primary, orangeAccent],
                                      begin: Alignment.topLeft,
                                      end: Alignment.bottomRight,
                                    ),
                                    borderRadius: BorderRadius.circular(24),
                                    boxShadow: [
                                      BoxShadow(
                                        color: orangeAccent.withValues(
                                          alpha: 0.2,
                                        ),
                                        blurRadius: 16,
                                        offset: const Offset(0, 4),
                                      ),
                                    ],
                                  ),
                                  child: const Icon(
                                    Icons.chat_bubble_outline,
                                    color: Colors.white,
                                    size: 40,
                                  ),
                                ),
                                const SizedBox(height: 20),
                                Text(
                                  _conversations.isEmpty
                                      ? 'Sem conversas ainda'
                                      : 'Nenhuma conversa encontrada',
                                  style: TextStyle(
                                    color: cs.onSurface,
                                    fontSize: 18,
                                    fontWeight: FontWeight.w600,
                                  ),
                                ),
                                const SizedBox(height: 8),
                                Text(
                                  _conversations.isEmpty
                                      ? 'Começa uma conversa com o Vico!'
                                      : 'Tenta ajustar os filtros',
                                  style: TextStyle(
                                    color: cs.onSurfaceVariant.withValues(
                                      alpha: 0.7,
                                    ),
                                    fontSize: 14,
                                  ),
                                ),
                              ],
                            ),
                          ),
                        )
                      : ListView.separated(
                          padding: const EdgeInsets.symmetric(horizontal: 16),
                          itemCount: _filteredConversations.length,
                          separatorBuilder: (_, __) =>
                              const SizedBox(height: 12),
                          itemBuilder: (context, index) {
                            final conversation = _filteredConversations[index];
                            return _buildConversationCard(
                              conversation,
                              cs,
                              orangeAccent,
                              lightOrange,
                            );
                          },
                        ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildDateFilterChip(
    String label,
    String value,
    ColorScheme cs,
    Color orangeAccent,
  ) {
    final isSelected = _selectedDateFilter == value;
    return FilterChip(
      label: Text(label),
      selected: isSelected,
      onSelected: (selected) {
        setState(() {
          _selectedDateFilter = value;
        });
        _filterConversations();
      },
      backgroundColor: cs.surface,
      selectedColor: orangeAccent.withValues(alpha: 0.2),
      labelStyle: TextStyle(
        color: isSelected ? orangeAccent : cs.onSurface,
        fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
      ),
      side: BorderSide(
        color: isSelected ? orangeAccent : cs.outline.withValues(alpha: 0.3),
      ),
    );
  }

  Widget _buildConversationCard(
    Map<String, dynamic> conversation,
    ColorScheme cs,
    Color orangeAccent,
    Color lightOrange,
  ) {
    final isSelected = _selectedConversationIds.contains(conversation['id']);

    return Dismissible(
      key: Key(conversation['id']),
      direction: _isSelectionMode
          ? DismissDirection.none
          : DismissDirection.endToStart,
      onDismissed: _isSelectionMode
          ? null
          : (_) => _deleteConversation(conversation['id']),
      background: Container(
        decoration: BoxDecoration(
          color: Colors.red,
          borderRadius: BorderRadius.circular(16),
        ),
        alignment: Alignment.centerRight,
        padding: const EdgeInsets.only(right: 20),
        child: const Icon(Icons.delete, color: Colors.white),
      ),
      child: InkWell(
        onTap: () {
          if (_isSelectionMode) {
            _toggleConversationSelection(conversation['id']);
          } else {
            ChatMemoryService.setCurrentConversationId(conversation['id']);
            context.go('/ai-tutor/${conversation['id']}');
          }
        },
        borderRadius: BorderRadius.circular(20),
        child: Container(
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            color: isSelected
                ? orangeAccent.withValues(alpha: 0.1)
                : cs.surface,
            borderRadius: BorderRadius.circular(20),
            border: Border.all(
              color: isSelected
                  ? orangeAccent
                  : orangeAccent.withValues(alpha: 0.2),
              width: isSelected ? 2 : 1.5,
            ),
            boxShadow: [
              BoxShadow(
                color: orangeAccent.withValues(alpha: 0.08),
                blurRadius: 12,
                offset: const Offset(0, 4),
              ),
            ],
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  if (_isSelectionMode)
                    Padding(
                      padding: const EdgeInsets.only(right: 12),
                      child: Checkbox(
                        value: isSelected,
                        onChanged: (_) =>
                            _toggleConversationSelection(conversation['id']),
                        fillColor: WidgetStateProperty.resolveWith((states) {
                          if (states.contains(WidgetState.selected)) {
                            return orangeAccent;
                          }
                          return null;
                        }),
                      ),
                    )
                  else
                    Container(
                      width: 48,
                      height: 48,
                      decoration: BoxDecoration(
                        gradient: LinearGradient(
                          colors: [cs.primary, orangeAccent],
                          begin: Alignment.topLeft,
                          end: Alignment.bottomRight,
                        ),
                        borderRadius: BorderRadius.circular(14),
                        boxShadow: [
                          BoxShadow(
                            color: orangeAccent.withValues(alpha: 0.2),
                            blurRadius: 8,
                            offset: const Offset(0, 2),
                          ),
                        ],
                      ),
                      child: const Icon(
                        Icons.chat_bubble,
                        color: Colors.white,
                        size: 24,
                      ),
                    ),
                  const SizedBox(width: 12),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          conversation['title'],
                          style: TextStyle(
                            color: cs.onSurface,
                            fontSize: 16,
                            fontWeight: FontWeight.bold,
                          ),
                          maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                        ),
                        const SizedBox(height: 4),
                        Row(
                          children: [
                            Icon(
                              Icons.access_time,
                              size: 12,
                              color: cs.onSurfaceVariant,
                            ),
                            const SizedBox(width: 4),
                            Text(
                              _formatDate(conversation['updatedAt']),
                              style: TextStyle(
                                color: cs.onSurfaceVariant,
                                fontSize: 12,
                              ),
                            ),
                            const SizedBox(width: 12),
                            Icon(
                              Icons.message,
                              size: 12,
                              color: cs.onSurfaceVariant,
                            ),
                            const SizedBox(width: 4),
                            Text(
                              '${conversation['messageCount']} msgs',
                              style: TextStyle(
                                color: cs.onSurfaceVariant,
                                fontSize: 12,
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),
                  Icon(Icons.chevron_right, color: cs.onSurfaceVariant),
                ],
              ),
              if (conversation['selectedMaterialIds'] != null &&
                  (conversation['selectedMaterialIds'] as List).isNotEmpty)
                Padding(
                  padding: const EdgeInsets.only(top: 12),
                  child: Wrap(
                    spacing: 6,
                    runSpacing: 6,
                    children: (conversation['selectedMaterialIds'] as List)
                        .take(3)
                        .map<Widget>((id) {
                          final materialId = id as String;
                          final displayName =
                              _materialNamesCache[materialId] ?? materialId;
                          return Container(
                            padding: const EdgeInsets.symmetric(
                              horizontal: 8,
                              vertical: 4,
                            ),
                            decoration: BoxDecoration(
                              color: lightOrange.withValues(alpha: 0.15),
                              borderRadius: BorderRadius.circular(8),
                              border: Border.all(
                                color: lightOrange.withValues(alpha: 0.3),
                                width: 1,
                              ),
                            ),
                            child: Text(
                              displayName.length > 20
                                  ? '${displayName.substring(0, 20)}...'
                                  : displayName,
                              style: TextStyle(
                                color: lightOrange,
                                fontSize: 11,
                                fontWeight: FontWeight.w500,
                              ),
                            ),
                          );
                        })
                        .toList(),
                  ),
                ),
            ],
          ),
        ),
      ),
    ).animate().slideX(duration: 300.ms).fadeIn(duration: 300.ms);
  }
}
