// lib/features/admin/tabs/messages/meta_ai_panel.dart

import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'dart:async';
import 'dart:math';

class MetaAIPanel extends StatefulWidget {
  final String myEmail;
  final VoidCallback? onBack;

  const MetaAIPanel({
    super.key, 
    required this.myEmail,
    this.onBack,
  });

  @override
  State<MetaAIPanel> createState() => _MetaAIPanelState();
}

class _MetaAIPanelState extends State<MetaAIPanel> with SingleTickerProviderStateMixin {
  final TextEditingController _msgController = TextEditingController();
  late AnimationController _spinController;

  bool _isThinking = false;
  
  // Quick action chips
  final List<String> _suggestedQuestions = [
    "How do I manage exams?",
    "Where is the Library?",
    "How do I add new staff?",
    "Where do I see IT tickets?"
  ];

  final List<String> _commonGreetings = [
    "hi", "hello", "hey", "how are you", "how are you doing", "good morning", 
    "good afternoon", "good evening", "greetings", "what's up", "whats up", 
    "wassup", "hiya", "yo", "morning", "afternoon", "evening", "hie", "hallo"
  ];

  @override
  void initState() {
    super.initState();
    _spinController = AnimationController(vsync: this, duration: const Duration(seconds: 3))..repeat();
    _ensureWelcomeMessageExists();
  }

  @override
  void dispose() {
    _msgController.dispose();
    _spinController.dispose();
    super.dispose();
  }

  Future<void> _ensureWelcomeMessageExists() async {
    final collectionRef = FirebaseFirestore.instance.collection('users').doc(widget.myEmail).collection('ai_chat');
    final snapshot = await collectionRef.limit(1).get();
    
    if (snapshot.docs.isEmpty) {
      await collectionRef.add({
        'text': "Hello! I am your Connect Administration Assistant. You can ask me questions, or click one of the suggested topics below to get started.",
        'isMe': false,
        'timestamp': FieldValue.serverTimestamp(),
        'isTyping': false, 
      });
    }
  }

  String _formatTime(Timestamp? timestamp) {
    if (timestamp == null) return '...';
    final date = timestamp.toDate();
    final hour = date.hour > 12 ? date.hour - 12 : (date.hour == 0 ? 12 : date.hour);
    final period = date.hour >= 12 ? 'PM' : 'AM';
    return "$hour:${date.minute.toString().padLeft(2, '0')} $period";
  }

  // 🚀 MATH: Levenshtein Distance for spelling mistakes
  int _levenshteinDistance(String s1, String s2) {
    if (s1 == s2) return 0;
    if (s1.isEmpty) return s2.length;
    if (s2.isEmpty) return s1.length;

    List<int> v0 = List<int>.filled(s2.length + 1, 0);
    List<int> v1 = List<int>.filled(s2.length + 1, 0);

    for (int i = 0; i < v0.length; i++) {
      v0[i] = i;
    }

    for (int i = 0; i < s1.length; i++) {
      v1[0] = i + 1;
      for (int j = 0; j < s2.length; j++) {
        int cost = (s1[i] == s2[j]) ? 0 : 1;
        v1[j + 1] = min(v1[j] + 1, min(v0[j + 1] + 1, v0[j] + cost));
      }
      for (int j = 0; j < v0.length; j++) {
        v0[j] = v1[j];
      }
    }
    return v1[s2.length];
  }

  // 🚀 EXTRACT KEYWORDS (Ignores common filler words)
  List<String> _extractKeywords(String text) {
    final stopWords = {'how','do','i','where','is','the','what','can','you','me','to','for','a','an','in','on','at','of','and','my','find','see','get','about','are','am','with','it','from'};
    final cleaned = text.toLowerCase().replaceAll(RegExp(r'[^\w\s]'), '');
    return cleaned.split(RegExp(r'\s+')).where((w) => w.isNotEmpty && !stopWords.contains(w)).toList();
  }

  // 🚀 FETCH 100% FIRESTORE RESPONSE (Keyword based)
  Future<String> _fetchIntelligentResponse(String inputQuery) async {
    final lowerQuery = inputQuery.toLowerCase().trim();
    
    String cleanedQuery = lowerQuery.replaceAll(RegExp(r'[^\w\s]'), '');
    if (_commonGreetings.contains(cleanedQuery)) {
      return "Hello! I am your Connect Administration Assistant. I am here to help you navigate Rockview University's portal. Ask me any question about the modules or system!";
    }

    final userKeywords = _extractKeywords(inputQuery);
    if (userKeywords.isEmpty) return "Could you please provide more details?";
    
    try {
      final snapshot = await FirebaseFirestore.instance.collection('ai_training_data').get();
      
      String bestAnswer = "";
      String matchedQuestion = "";
      int bestScore = 0;
      bool wasFuzzyMatch = false;

      for (var doc in snapshot.docs) {
        final dbQuestion = (doc.data()['question'] ?? '').toString();
        final dbAnswer = doc.data()['answer'] ?? '';
        final dbKeywords = _extractKeywords(dbQuestion);
        
        int exactMatches = 0;
        int fuzzyMatches = 0;

        for (String uWord in userKeywords) {
          if (dbKeywords.contains(uWord)) {
            exactMatches += 2; // Exact keywords carry high weight
          } else {
            // Check for spelling typos (Fuzzy matching)
            for (String dbWord in dbKeywords) {
              if (uWord.length > 3 && dbWord.length > 3) {
                if (_levenshteinDistance(uWord, dbWord) <= 2) {
                  fuzzyMatches += 1;
                  break; 
                }
              }
            }
          }
        }

        int totalScore = exactMatches + fuzzyMatches;

        if (totalScore > bestScore) {
          bestScore = totalScore;
          bestAnswer = dbAnswer;
          matchedQuestion = dbQuestion;
          // Only flag as fuzzy if there were NO exact matches at all
          wasFuzzyMatch = (fuzzyMatches > 0 && exactMatches == 0);
        }
      }

      if (bestScore > 0) {
        // Output response
        String didYouMean = wasFuzzyMatch ? "*Did you mean: '$matchedQuestion'?*\n\n" : "";
        return "$didYouMean$bestAnswer";
      } else {
        // Forward to unanswered questions
        await FirebaseFirestore.instance.collection('unanswered_questions').add({
          'question': inputQuery,
          'askedBy': widget.myEmail,
          'timestamp': FieldValue.serverTimestamp(),
        });

        return "I could not find a direct answer to that right now.\n\nI have sent your question to the administration team. Please check back within 24 hours while they review and update my Knowledge Base.";
      }
      
    } catch (e) {
      return "I could not connect to the Knowledge Base. Please try again later.";
    }
  }

  // 🚀 SEND MESSAGE WORKFLOW
  Future<void> _sendMessage({String? predefinedText}) async {
    final text = predefinedText ?? _msgController.text.trim();
    if (text.isEmpty || _isThinking) return;

    _msgController.clear();
    setState(() => _isThinking = true);

    final collectionRef = FirebaseFirestore.instance.collection('users').doc(widget.myEmail).collection('ai_chat');

    await collectionRef.add({
      'text': text,
      'isMe': true,
      'timestamp': FieldValue.serverTimestamp(),
      'isTyping': false,
    });

    await Future.delayed(const Duration(seconds: 1));

    final String aiReply = await _fetchIntelligentResponse(text);

    try {
      await collectionRef.add({
        'text': aiReply,
        'isMe': false,
        'timestamp': FieldValue.serverTimestamp(),
        'isTyping': true,
      });
    } catch (e) {
      // ignored
    } finally {
      if (mounted) setState(() => _isThinking = false);
    }
  }

  Future<void> _clearChatHistory() async {
    final bool? confirm = await showDialog<bool>(
      context: context,
      builder: (ctx) => AlertDialog(
        title: const Text('Clear Chat?'),
        content: const Text('Are you sure you want to delete all messages? This action cannot be undone.'),
        actions: [
          TextButton(onPressed: () => Navigator.pop(ctx, false), child: const Text('CANCEL')),
          TextButton(onPressed: () => Navigator.pop(ctx, true), child: const Text('CLEAR', style: TextStyle(color: Colors.red))),
        ],
      ),
    );

    if (confirm == true) {
      final collectionRef = FirebaseFirestore.instance.collection('users').doc(widget.myEmail).collection('ai_chat');
      final snapshots = await collectionRef.get();
      
      final batch = FirebaseFirestore.instance.batch();
      for (var doc in snapshots.docs) {
        batch.delete(doc.reference);
      }
      await batch.commit();
      
      _ensureWelcomeMessageExists();
    }
  }

  Widget _buildGradientIcon({double size = 30}) {
    return RotationTransition(
      turns: _spinController,
      child: ShaderMask(
        shaderCallback: (bounds) => const SweepGradient(
          colors: [Color(0xFF4285F4), Color.fromARGB(255, 211, 146, 6), Color.fromARGB(255, 26, 112, 4), Color(0xFF4285F4)],
          stops: [0.0, 0.33, 0.66, 1.0],
        ).createShader(bounds),
        child: Icon(Icons.blur_on, color: Colors.white, size: size),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final chatStream = FirebaseFirestore.instance
        .collection('users')
        .doc(widget.myEmail)
        .collection('ai_chat')
        // We MUST order by timestamp descending for reverse listview to work
        .orderBy('timestamp', descending: true) 
        .snapshots();

    return Container(
      color: Colors.white,
      child: Column(
        children: [
          // HEADER
          Container(
            height: 66,
            padding: const EdgeInsets.symmetric(horizontal: 12),
            decoration: BoxDecoration(
              color: Colors.white,
              border: Border(bottom: BorderSide(color: Colors.grey.shade200, width: 1)),
            ),
            child: Row(
              children: [
                if (widget.onBack != null)
                  IconButton(icon: const Icon(Icons.arrow_back, color: Color(0xFF111B21)), onPressed: widget.onBack),
                const SizedBox(width: 8),
                _buildGradientIcon(size: 28),
                const SizedBox(width: 12),
                Expanded(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      const Text('Rock AI Assistant', maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(color: Color(0xFF17231C), fontSize: 16, fontWeight: FontWeight.w900)),
                      Text(
                        _isThinking ? 'searching knowledge base...' : 'Powered by Rock AI', 
                        style: TextStyle(color: _isThinking ? const Color.fromARGB(255, 9, 161, 103) : const Color(0xFF54656F), fontSize: 12, fontStyle: _isThinking ? FontStyle.italic : FontStyle.normal)
                      ),
                    ],
                  ),
                ),
                PopupMenuButton<String>(
                  icon: const Icon(Icons.more_vert_rounded, color: Color(0xFF54656F)),
                  onSelected: (val) {
                    if (val == 'clear') _clearChatHistory();
                  },
                  itemBuilder: (context) => [
                    const PopupMenuItem(value: 'clear', child: Text('Clear Chat History')),
                  ],
                ),
              ],
            ),
          ),

          // FIRESTORE CHAT HISTORY
          Expanded(
            child: Container(
              color: const Color(0xFFF5F7F6),
              child: StreamBuilder<QuerySnapshot>(
                stream: chatStream,
                builder: (context, snapshot) {
                  if (snapshot.connectionState == ConnectionState.waiting) {
                    return const Center(child: CircularProgressIndicator(color: Color(0xFF026930)));
                  }

                  // Documents are already reversed via the query!
                  final docs = snapshot.data?.docs ?? [];

                  return ListView.builder(
                    // 🚀 REVERSE LISTVIEW: This permanently anchors messages to the bottom. No more shaking!
                    reverse: true,
                    padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 18),
                    itemCount: docs.length + (_isThinking ? 1 : 0),
                    itemBuilder: (context, index) {

                      // If thinking, the indicator is always at the absolute bottom (index 0)
                      if (_isThinking && index == 0) {
                        return Align(
                          alignment: Alignment.centerLeft,
                          child: Container(
                            margin: const EdgeInsets.only(top: 12),
                            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                            decoration: BoxDecoration(
                              color: Colors.white,
                              borderRadius: BorderRadius.circular(16),
                              boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.04), blurRadius: 4, offset: const Offset(0, 2))],
                            ),
                            child: Row(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                _buildGradientIcon(size: 20),
                                const SizedBox(width: 12),
                                const Text('Thinking...', style: TextStyle(color: Color(0xFF54656F), fontSize: 13, fontStyle: FontStyle.italic)),
                              ],
                            ),
                          ),
                        );
                      }

                      // Adjust doc index based on whether the thinking indicator is taking up index 0
                      final docIndex = _isThinking ? index - 1 : index;
                      final doc = docs[docIndex];
                      
                      final data = doc.data() as Map<String, dynamic>;
                      final bool isMe = data['isMe'] ?? false;
                      final String text = data['text'] ?? '';
                      final String time = _formatTime(data['timestamp'] as Timestamp?);
                      final bool isTyping = data['isTyping'] ?? false;

                      return Align(
                        alignment: isMe ? Alignment.centerRight : Alignment.centerLeft,
                        child: Container(
                          // Using margin TOP instead of bottom because list is reversed
                          margin: const EdgeInsets.only(top: 12),
                          constraints: const BoxConstraints(maxWidth: 620),
                          decoration: BoxDecoration(
                            color: isMe ? const Color(0xFF026930) : Colors.white,
                            borderRadius: BorderRadius.only(
                              topLeft: const Radius.circular(16),
                              topRight: const Radius.circular(16),
                              bottomLeft: Radius.circular(isMe ? 16 : 0),
                              bottomRight: Radius.circular(isMe ? 0 : 16),
                            ),
                            border: isMe ? null : Border.all(color: Colors.grey.shade200),
                            boxShadow: isMe ? [] : [BoxShadow(color: Colors.black.withOpacity(0.04), blurRadius: 4, offset: const Offset(0, 2))],
                          ),
                          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              
                              // 🚀 TYPEWRITER TEXT EFFECT
                              isTyping 
                                ? TypewriterText(
                                    text: text, 
                                    isMe: isMe,
                                    onFinished: () {
                                      doc.reference.update({'isTyping': false});
                                    }
                                  )
                                : Text(
                                    text,
                                    style: TextStyle(fontSize: 15, color: isMe ? Colors.white : const Color(0xFF111B21), height: 1.4),
                                  ),

                              const SizedBox(height: 6),
                              Align(
                                alignment: Alignment.bottomRight,
                                child: Text(
                                  time,
                                  style: TextStyle(
                                    fontSize: 11,
                                    color: isMe ? Colors.white70 : const Color(0xFF8696A0),
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
                      );
                    },
                  );
                },
              ),
            ),
          ),

          // 🚀 QUICK ACTION CHIPS
          Container(
            padding: const EdgeInsets.only(top: 8, bottom: 8),
            color: Colors.white,
            child: SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              padding: const EdgeInsets.symmetric(horizontal: 16),
              physics: const BouncingScrollPhysics(),
              child: Row(
                children: _suggestedQuestions.map((q) {
                  return Padding(
                    padding: const EdgeInsets.only(right: 8),
                    child: ActionChip(
                      label: Text(q, style: const TextStyle(fontSize: 13, color: Color(0xFF026930), fontWeight: FontWeight.bold)),
                      backgroundColor: const Color(0xFF026930).withOpacity(0.1),
                      side: BorderSide.none,
                      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
                      onPressed: () => _sendMessage(predefinedText: q),
                    ),
                  );
                }).toList(),
              ),
            ),
          ),

          // INPUT BAR
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
            decoration: BoxDecoration(
              color: Colors.white,
              border: Border(top: BorderSide(color: Colors.grey.shade200, width: 1)),
            ),
            child: Row(
              children: [
                Expanded(
                  child: Container(
                    decoration: BoxDecoration(
                      color: const Color(0xFFF0F2F5),
                      borderRadius: BorderRadius.circular(24),
                    ),
                    child: TextField(
                      controller: _msgController,
                      minLines: 1,
                      maxLines: 3,
                      textInputAction: TextInputAction.send,
                      onSubmitted: (_) => _sendMessage(),
                      decoration: const InputDecoration(
                        hintText: 'Ask a question...',
                        hintStyle: TextStyle(color: Color(0xFF8696A0), fontSize: 14),
                        contentPadding: EdgeInsets.symmetric(horizontal: 20, vertical: 14),
                        border: InputBorder.none,
                      ),
                    ),
                  ),
                ),
                const SizedBox(width: 12),
                Container(
                  decoration: const BoxDecoration(
                    color: Color(0xFF026930),
                    shape: BoxShape.circle,
                  ),
                  child: IconButton(
                    icon: const Icon(Icons.send_rounded, color: Colors.white, size: 20),
                    onPressed: _sendMessage,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

// 🚀 CUSTOM TYPEWRITER WIDGET FOR AI TYPING ANIMATION
class TypewriterText extends StatefulWidget {
  final String text;
  final bool isMe;
  final VoidCallback onFinished;

  const TypewriterText({
    super.key, 
    required this.text, 
    required this.isMe, 
    required this.onFinished,
  });

  @override
  State<TypewriterText> createState() => _TypewriterTextState();
}

class _TypewriterTextState extends State<TypewriterText> {
  String _displayedText = "";
  Timer? _timer;
  int _currentIndex = 0;

  @override
  void initState() {
    super.initState();
    _startTyping();
  }

  void _startTyping() {
    // Very fast but smooth typing. 
    // Because the list is 'reverse: true', this text will naturally grow upwards without shaking!
    _timer = Timer.periodic(const Duration(milliseconds: 20), (timer) {
      if (!mounted) {
        timer.cancel();
        return;
      }
      if (_currentIndex < widget.text.length) {
        setState(() {
          _displayedText += widget.text[_currentIndex];
          _currentIndex++;
        });
      } else {
        _timer?.cancel();
        widget.onFinished(); 
      }
    });
  }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return RichText(
      text: TextSpan(
        style: TextStyle(
          fontSize: 15, 
          color: widget.isMe ? Colors.white : const Color(0xFF111B21), 
          height: 1.4,
          fontFamily: 'Roboto', 
        ),
        children: _parseFormatting(_displayedText),
      ),
    );
  }

  List<TextSpan> _parseFormatting(String text) {
    List<TextSpan> spans = [];
    text.splitMapJoin(
      RegExp(r'\*(.*?)\*'),
      onMatch: (m) {
        spans.add(TextSpan(text: m.group(1), style: const TextStyle(fontWeight: FontWeight.bold)));
        return '';
      },
      onNonMatch: (n) {
        spans.add(TextSpan(text: n));
        return '';
      },
    );
    return spans;
  }
}