// lib/features/admin/tabs/unanswered_questions_tab.dart

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

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

  @override
  State<UnansweredQuestionsTab> createState() => _UnansweredQuestionsTabState();
}

class _UnansweredQuestionsTabState extends State<UnansweredQuestionsTab> {
  final TextEditingController _answerController = TextEditingController();
  
  String? _selectedDocId;
  String? _selectedQuestion;
  bool _isSubmitting = false;

  final String _unansweredCollection = 'unanswered_questions';
  final String _aiKnowledgeCollection = 'ai_training_data';

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

  void _showSnackBar(String message, bool isError) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message, style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold)),
        backgroundColor: isError ? Colors.redAccent : const Color(0xFF118A5E),
        behavior: SnackBarBehavior.floating,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
      ),
    );
  }

  Future<void> _submitFeedback() async {
    final answer = _answerController.text.trim();

    if (answer.isEmpty) {
      _showSnackBar('Please provide an answer before publishing.', true);
      return;
    }

    if (_selectedDocId == null || _selectedQuestion == null) return;

    setState(() => _isSubmitting = true);

    try {
      final batch = FirebaseFirestore.instance.batch();

      // 1. Add to the AI Training Data collection
      final newAiEntryRef = FirebaseFirestore.instance.collection(_aiKnowledgeCollection).doc();
      batch.set(newAiEntryRef, {
        'question': _selectedQuestion,
        'answer': answer,
        'timestamp': FieldValue.serverTimestamp(),
      });

      // 2. Delete the pending question from the Unanswered list
      final pendingQuestionRef = FirebaseFirestore.instance.collection(_unansweredCollection).doc(_selectedDocId);
      batch.delete(pendingQuestionRef);

      // Execute both operations simultaneously
      await batch.commit();

      _answerController.clear();
      setState(() {
        _selectedDocId = null;
        _selectedQuestion = null;
      });

      _showSnackBar('Feedback published! AI Knowledge Base updated.', false);
    } catch (e) {
      _showSnackBar('Failed to publish feedback: $e', true);
    } finally {
      if (mounted) setState(() => _isSubmitting = false);
    }
  }

  Widget _buildQuestionsList() {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        border: Border.all(color: Colors.grey.shade200),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 20),
            decoration: BoxDecoration(
              color: const Color(0xFFF9F9FA),
              borderRadius: const BorderRadius.vertical(top: Radius.circular(16)),
              border: Border(bottom: BorderSide(color: Colors.grey.shade200)),
            ),
            child: const Row(
              children: [
                Icon(Icons.live_help_rounded, color: Color.fromARGB(255, 204, 117, 4), size: 24),
                SizedBox(width: 12),
                Text('Pending Questions', style: TextStyle(fontWeight: FontWeight.bold, color: Color(0xFF111B21), fontSize: 16)),
              ],
            ),
          ),
          Expanded(
            child: StreamBuilder<QuerySnapshot>(
              stream: FirebaseFirestore.instance.collection(_unansweredCollection).orderBy('timestamp', descending: true).snapshots(),
              builder: (context, snapshot) {
                if (snapshot.connectionState == ConnectionState.waiting) {
                  return const Center(child: CircularProgressIndicator(color: Color.fromARGB(255, 204, 117, 4)));
                }

                final docs = snapshot.data?.docs ?? [];

                if (docs.isEmpty) {
                  return Center(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(Icons.check_circle_outline_rounded, size: 64, color: Colors.grey.shade300),
                        const SizedBox(height: 16),
                        Text('All caught up!', style: TextStyle(color: Colors.grey.shade600, fontSize: 18, fontWeight: FontWeight.bold)),
                        const SizedBox(height: 8),
                        Text('There are no unanswered questions.', style: TextStyle(color: Colors.grey.shade500, fontSize: 14)),
                      ],
                    ),
                  );
                }

                return ListView.separated(
                  padding: EdgeInsets.zero,
                  itemCount: docs.length,
                  separatorBuilder: (context, index) => const Divider(height: 1, thickness: 1),
                  itemBuilder: (context, index) {
                    final data = docs[index].data() as Map<String, dynamic>;
                    final docId = docs[index].id;
                    final question = data['question'] ?? 'Unknown Question';
                    final bool isSelected = _selectedDocId == docId;

                    return InkWell(
                      onTap: () {
                        setState(() {
                          _selectedDocId = docId;
                          _selectedQuestion = question;
                          _answerController.clear();
                        });
                      },
                      child: Container(
                        padding: const EdgeInsets.all(20),
                        decoration: BoxDecoration(
                          color: isSelected ? const Color.fromARGB(255, 204, 117, 4).withOpacity(0.08) : Colors.transparent,
                          border: Border(
                            left: BorderSide(
                              color: isSelected ? const Color.fromARGB(255, 204, 117, 4) : Colors.transparent,
                              width: 4,
                            ),
                          ),
                        ),
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Icon(Icons.help_outline_rounded, color: isSelected ? const Color.fromARGB(255, 204, 117, 4) : Colors.grey.shade400, size: 20),
                            const SizedBox(width: 12),
                            Expanded(
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(
                                    question,
                                    maxLines: 2,
                                    overflow: TextOverflow.ellipsis,
                                    style: TextStyle(
                                      fontWeight: isSelected ? FontWeight.bold : FontWeight.w500,
                                      fontSize: 15,
                                      color: isSelected ? const Color(0xFF111B21) : Colors.grey.shade800,
                                    ),
                                  ),
                                  const SizedBox(height: 6),
                                  Text('Needs Answer', style: TextStyle(color: Colors.redAccent.shade200, fontSize: 12, fontWeight: FontWeight.bold)),
                                ],
                              ),
                            ),
                            if (isSelected) const Icon(Icons.arrow_forward_ios_rounded, color: Color.fromARGB(255, 204, 117, 4), size: 16),
                          ],
                        ),
                      ),
                    );
                  },
                );
              },
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildAnswerForm() {
    if (_selectedDocId == null) {
      return Container(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(16),
          border: Border.all(color: Colors.grey.shade200),
        ),
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(Icons.forum_outlined, size: 64, color: Colors.grey.shade300),
              const SizedBox(height: 16),
              Text('Select a question to answer', style: TextStyle(color: Colors.grey.shade500, fontSize: 16, fontWeight: FontWeight.w500)),
            ],
          ),
        ),
      );
    }

    return Container(
      padding: const EdgeInsets.all(32),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        border: Border.all(color: Colors.grey.shade200),
        boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.02), blurRadius: 10, offset: const Offset(0, 4))],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Container(
                padding: const EdgeInsets.all(10),
                decoration: BoxDecoration(color: const Color.fromARGB(255, 204, 117, 4).withOpacity(0.1), shape: BoxShape.circle),
                child: const Icon(Icons.psychology_rounded, color: Color.fromARGB(255, 204, 117, 4), size: 28),
              ),
              const SizedBox(width: 16),
              const Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text('Provide Feedback', style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold, color: Color(0xFF111B21))),
                    Text('Your answer will train the Meta AI.', style: TextStyle(color: Color(0xFF54656F), fontSize: 13)),
                  ],
                ),
              ),
            ],
          ),
          const SizedBox(height: 32),
          
          Container(
            padding: const EdgeInsets.all(20),
            decoration: BoxDecoration(
              color: const Color(0xFFF9F9FA),
              borderRadius: BorderRadius.circular(12),
              border: Border.all(color: Colors.grey.shade200),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text('USER QUESTION', style: TextStyle(fontSize: 12, fontWeight: FontWeight.bold, color: Colors.grey, letterSpacing: 1.0)),
                const SizedBox(height: 8),
                Text(_selectedQuestion ?? '', style: const TextStyle(fontSize: 16, color: Color(0xFF111B21), fontWeight: FontWeight.w500, height: 1.4)),
              ],
            ),
          ),
          const SizedBox(height: 32),

          const Text('OFFICIAL ANSWER', style: TextStyle(fontWeight: FontWeight.w600, color: Color(0xFF111B21), fontSize: 13, letterSpacing: 1.0)),
          const SizedBox(height: 8),
          Expanded(
            child: TextField(
              controller: _answerController,
              maxLines: null,
              expands: true,
              textAlignVertical: TextAlignVertical.top,
              decoration: InputDecoration(
                hintText: 'Type the comprehensive and official answer here...',
                hintStyle: TextStyle(color: Colors.grey.shade400),
                filled: true,
                fillColor: const Color(0xFFF9F9FA),
                border: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: BorderSide.none),
                focusedBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: const BorderSide(color: Color(0xFF118A5E), width: 2)),
              ),
            ),
          ),
          const SizedBox(height: 24),

          Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              TextButton(
                onPressed: () {
                  setState(() {
                    _selectedDocId = null;
                    _selectedQuestion = null;
                    _answerController.clear();
                  });
                },
                style: TextButton.styleFrom(padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 20)),
                child: const Text('CANCEL', style: TextStyle(color: Colors.grey, fontWeight: FontWeight.bold, letterSpacing: 1.0)),
              ),
              const SizedBox(width: 16),
              ElevatedButton.icon(
                onPressed: _isSubmitting ? null : _submitFeedback,
                icon: _isSubmitting 
                    ? const SizedBox(width: 20, height: 20, child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white))
                    : const Icon(Icons.auto_awesome_rounded, color: Colors.white),
                label: Text(
                  _isSubmitting ? 'PUBLISHING...' : 'PUBLISH & TRAIN AI',
                  style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold, letterSpacing: 1.0, fontSize: 14),
                ),
                style: ElevatedButton.styleFrom(
                  backgroundColor: const Color(0xFF118A5E),
                  foregroundColor: Colors.white,
                  padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 20),
                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
                  elevation: 0,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF0F2F5), // Standard subtle background
      body: LayoutBuilder(
        builder: (context, constraints) {
          final isDesktop = constraints.maxWidth > 900;
          
          return Padding(
            padding: const EdgeInsets.all(24.0),
            child: isDesktop
                ? Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // List on the left
                      Expanded(
                        flex: 4,
                        child: _buildQuestionsList(),
                      ),
                      const SizedBox(width: 24),
                      // Form on the right
                      Expanded(
                        flex: 6,
                        child: _buildAnswerForm(),
                      ),
                    ],
                  )
                : Column(
                    children: [
                      if (_selectedDocId == null)
                        Expanded(child: _buildQuestionsList())
                      else ...[
                        Align(
                          alignment: Alignment.centerLeft,
                          child: TextButton.icon(
                            onPressed: () => setState(() => _selectedDocId = null),
                            icon: const Icon(Icons.arrow_back_rounded),
                            label: const Text('Back to Questions'),
                          ),
                        ),
                        const SizedBox(height: 16),
                        Expanded(child: _buildAnswerForm()),
                      ]
                    ],
                  ),
          );
        }
      ),
    );
  }
}