// lib/features/admin/tabs/feed_ai_tab.dart

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

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

  @override
  State<FeedAiTab> createState() => _FeedAiTabState();
}

class _FeedAiTabState extends State<FeedAiTab> {
  final TextEditingController _questionController = TextEditingController();
  final TextEditingController _answerController = TextEditingController();
  
  bool _isUploading = false;
  final String _collectionName = 'ai_training_data';

  @override
  void dispose() {
    _questionController.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> _uploadData() async {
    final question = _questionController.text.trim();
    final answer = _answerController.text.trim();

    if (question.isEmpty || answer.isEmpty) {
      _showSnackBar('Please fill in both the question and the answer.', true);
      return;
    }

    setState(() => _isUploading = true);

    try {
      await FirebaseFirestore.instance.collection(_collectionName).add({
        'question': question,
        'answer': answer,
        'timestamp': FieldValue.serverTimestamp(),
      });

      _questionController.clear();
      _answerController.clear();
      _showSnackBar('Successfully added to AI Knowledge Base!', false);
    } catch (e) {
      _showSnackBar('Failed to upload data: $e', true);
    } finally {
      if (mounted) setState(() => _isUploading = false);
    }
  }

  Future<void> _deleteData(String docId) async {
    try {
      await FirebaseFirestore.instance.collection(_collectionName).doc(docId).delete();
      _showSnackBar('Knowledge entry removed.', false);
    } catch (e) {
      _showSnackBar('Failed to delete entry: $e', true);
    }
  }

  Widget _buildUploadForm() {
    return Container(
      padding: const EdgeInsets.all(24),
      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(0xFF118A5E).withOpacity(0.1), shape: BoxShape.circle),
                child: const Icon(Icons.psychology_rounded, color: Color(0xFF118A5E), size: 28),
              ),
              const SizedBox(width: 16),
              const Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text('Train the AI', style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold, color: Color(0xFF111B21))),
                    Text('Add new Q&A pairs to improve the AI\'s knowledge.', style: TextStyle(color: Color(0xFF54656F), fontSize: 13)),
                  ],
                ),
              ),
            ],
          ),
          const SizedBox(height: 32),
          
          const Text('Common Question / User Prompt', style: TextStyle(fontWeight: FontWeight.w600, color: Color(0xFF111B21), fontSize: 14)),
          const SizedBox(height: 8),
          TextField(
            controller: _questionController,
            maxLines: 2,
            decoration: InputDecoration(
              hintText: 'e.g., How do I apply for campus housing?',
              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),

          const Text('Official AI Answer', style: TextStyle(fontWeight: FontWeight.w600, color: Color(0xFF111B21), fontSize: 14)),
          const SizedBox(height: 8),
          TextField(
            controller: _answerController,
            maxLines: 6,
            decoration: InputDecoration(
              hintText: 'e.g., To apply for housing, navigate to the Manage Accommodation tab and click "New Application"...',
              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: 32),

          SizedBox(
            width: double.infinity,
            child: ElevatedButton.icon(
              onPressed: _isUploading ? null : _uploadData,
              icon: _isUploading 
                  ? const SizedBox(width: 20, height: 20, child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white))
                  : const Icon(Icons.cloud_upload_rounded, color: Colors.white),
              label: Text(
                _isUploading ? 'UPLOADING...' : 'SAVE TO KNOWLEDGE BASE',
                style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold, letterSpacing: 1.0, fontSize: 15),
              ),
              style: ElevatedButton.styleFrom(
                backgroundColor: const Color(0xFF118A5E),
                foregroundColor: Colors.white,
                padding: const EdgeInsets.symmetric(vertical: 20),
                shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
                elevation: 0,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildKnowledgeBaseList() {
    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.storage_rounded, color: Color(0xFF54656F), size: 20),
                SizedBox(width: 12),
                Text('Current Knowledge Base', style: TextStyle(fontWeight: FontWeight.bold, color: Color(0xFF111B21), fontSize: 16)),
              ],
            ),
          ),
          Expanded(
            child: StreamBuilder<QuerySnapshot>(
              stream: FirebaseFirestore.instance.collection(_collectionName).orderBy('timestamp', descending: true).snapshots(),
              builder: (context, snapshot) {
                if (snapshot.connectionState == ConnectionState.waiting) {
                  return const Center(child: CircularProgressIndicator(color: Color(0xFF118A5E)));
                }
                
                final docs = snapshot.data?.docs ?? [];
                
                if (docs.isEmpty) {
                  return Center(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(Icons.find_in_page_rounded, size: 64, color: Colors.grey.shade300),
                        const SizedBox(height: 16),
                        Text('No data found.', style: TextStyle(color: Colors.grey.shade500, fontSize: 16, fontWeight: FontWeight.w500)),
                        const SizedBox(height: 8),
                        Text('Add Q&A pairs to train your AI.', style: TextStyle(color: Colors.grey.shade400, fontSize: 13)),
                      ],
                    ),
                  );
                }

                return ListView.separated(
                  padding: const EdgeInsets.all(16),
                  itemCount: docs.length,
                  separatorBuilder: (context, index) => const Divider(height: 24),
                  itemBuilder: (context, index) {
                    final data = docs[index].data() as Map<String, dynamic>;
                    return Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        const Padding(
                          padding: EdgeInsets.only(top: 4, right: 12),
                          child: Icon(Icons.circle, size: 10, color: Color(0xFF118A5E)),
                        ),
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(data['question'] ?? 'No Question', style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 15, color: Color(0xFF111B21))),
                              const SizedBox(height: 6),
                              Text(data['answer'] ?? 'No Answer', style: const TextStyle(fontSize: 14, color: Color(0xFF54656F), height: 1.4)),
                            ],
                          ),
                        ),
                        IconButton(
                          icon: const Icon(Icons.delete_outline_rounded, color: Colors.redAccent, size: 20),
                          tooltip: 'Delete Entry',
                          onPressed: () => _deleteData(docs[index].id),
                        ),
                      ],
                    );
                  },
                );
              },
            ),
          ),
        ],
      ),
    );
  }

  @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: [
                      // Upload Form on the left
                      Expanded(
                        flex: 4,
                        child: SingleChildScrollView(
                          child: _buildUploadForm(),
                        ),
                      ),
                      const SizedBox(width: 24),
                      // Existing Data on the right
                      Expanded(
                        flex: 6,
                        child: _buildKnowledgeBaseList(),
                      ),
                    ],
                  )
                : Column(
                    children: [
                      _buildUploadForm(),
                      const SizedBox(height: 24),
                      Expanded(child: _buildKnowledgeBaseList()),
                    ],
                  ),
          );
        }
      ),
    );
  }
}