// lib/features/admin/tabs/qa/resolved_qa_sub_tab.dart

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart'; // <-- FOR COMPUTE
import 'package:http/http.dart' as http;
import 'package:intl/intl.dart';

import '../../../../core/networks/api_client.dart';

const Color _standardGold = Color.fromARGB(255, 204, 117, 4);
const Color _darkGreen = Color.fromARGB(255, 2, 105, 48);

// 🚀 SAFE BACKGROUND ISOLATE WITH UTF-8 BYTE DECODING
List<dynamic> _parseResolvedBackground(dynamic bodyData) {
  try {
    String text;
    if (bodyData is Uint8List || bodyData is List<int>) {
      text = utf8.decode(bodyData as List<int>, allowMalformed: true);
    } else {
      text = bodyData.toString();
    }
    
    final parsed = json.decode(text);
    
    if (parsed is Map && parsed.containsKey('data')) {
      return parsed['data'] is List ? parsed['data'] : [];
    }
    
    return parsed is List ? parsed : [];
  } catch (e) {
    debugPrint("JSON Parse error in background isolate: $e");
    return [];
  }
}

class ResolvedQaSubTab extends StatefulWidget {
  final String adminName;
  const ResolvedQaSubTab({super.key, required this.adminName});

  @override
  State<ResolvedQaSubTab> createState() => _ResolvedQaSubTabState();
}

class _ResolvedQaSubTabState extends State<ResolvedQaSubTab> {
  // 🚀 CHANGED TO MAP FOR GROUPING BY AUTHOR
  Map<String, List<Map<String, dynamic>>> _groupedQuestions = {};
  int _totalResolvedCount = 0;
  bool _isLoading = true;

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

  // 🚀 SAFE BOOLEAN CHECKER FOR MYSQL/LARAVEL
  bool _isResolved(dynamic val) {
    if (val == true || val == 1 || val == '1') return true;
    return false;
  }

  Future<void> _fetchData() async {
    setState(() => _isLoading = true);
    try {
      final response = await ApiClient.offlineFirstGet(
        // 🚀 UPDATED URL TO MATCH YOUR BACKEND EXACTLY
        Uri.parse('${ApiClient.baseUrl}/admin/qna/questions'),
        headers: await ApiClient.getHeaders()
      );

      if (response.statusCode == 200) {
        final List<dynamic> decodedData = await compute(_parseResolvedBackground, response.bodyBytes);
        
        if (mounted) {
          setState(() {
            // 1. Filter strictly for resolved
            final List<Map<String, dynamic>> rawResolved = decodedData.reversed
                .where((q) => _isResolved(q['is_resolved']))
                .map((e) => Map<String, dynamic>.from(e))
                .toList();

            _totalResolvedCount = rawResolved.length;

            // 2. 🚀 GROUP BY AUTHOR NAME
            _groupedQuestions = {};
            for (var question in rawResolved) {
              final String author = question['author_name'] ?? 'Unknown User';
              if (!_groupedQuestions.containsKey(author)) {
                _groupedQuestions[author] = [];
              }
              _groupedQuestions[author]!.add(question);
            }
            
            _isLoading = false;
          });
        }
      } else {
        if (mounted) setState(() => _isLoading = false);
      }
    } catch (e) {
      if (mounted) setState(() => _isLoading = false);
    }
  }

  String _formatDate(String isoString) {
    if (isoString.isEmpty) return "";
    try {
      final date = DateTime.parse(isoString);
      return DateFormat('MMM dd, yyyy • h:mm a').format(date);
    } catch (e) {
      return isoString;
    }
  }

  Future<void> _deleteQuestionAction(int questionId, String authorName) async {
    final success = await ApiClient.deleteQuestion(questionId);
    if (success && mounted) {
      setState(() {
        if (_groupedQuestions.containsKey(authorName)) {
          _groupedQuestions[authorName]!.removeWhere((q) => q['id'] == questionId);
          _totalResolvedCount--;
          
          // Remove the bucket entirely if it's empty
          if (_groupedQuestions[authorName]!.isEmpty) {
            _groupedQuestions.remove(authorName);
          }
        }
      });
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('Question successfully deleted.', style: TextStyle(fontWeight: FontWeight.bold)), backgroundColor: Colors.redAccent),
      );
    }
  }

  void _showEditReplyDialog(Map<String, dynamic> questionData) {
    final TextEditingController replyController = TextEditingController();
    bool isSubmitting = false;

    // Pre-fill existing answer
    final List answers = questionData['answers'] ?? [];
    if (answers.isNotEmpty) {
      replyController.text = answers.first['content'] ?? '';
    }

    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) {
        return StatefulBuilder(
          builder: (context, setDialogState) {
            return Dialog(
              shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
              backgroundColor: Colors.white,
              child: Container(
                width: 550,
                padding: const EdgeInsets.all(32),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Container(
                          padding: const EdgeInsets.all(12),
                          decoration: BoxDecoration(color: _standardGold.withOpacity(0.1), shape: BoxShape.circle),
                          child: const Icon(Icons.edit_document, color: _standardGold, size: 28),
                        ),
                        const SizedBox(width: 16),
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              const Text('Edit Official Response', style: TextStyle(fontSize: 20, fontWeight: FontWeight.w900, color: Colors.black87)),
                              const SizedBox(height: 4),
                              Text('Replying to: ${questionData['title']}', style: TextStyle(fontSize: 13, color: Colors.grey.shade600, fontStyle: FontStyle.italic)),
                            ],
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 32),
                    TextField(
                      controller: replyController,
                      maxLines: 6,
                      cursorColor: _standardGold,
                      decoration: InputDecoration(
                        hintText: 'Type your official administrative response here...',
                        filled: true,
                        fillColor: Colors.grey.shade50,
                        border: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: BorderSide(color: Colors.grey.shade200)),
                        focusedBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: const BorderSide(color: _standardGold, width: 2)),
                      ),
                    ),
                    const SizedBox(height: 32),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: [
                        TextButton(
                          onPressed: isSubmitting ? null : () => Navigator.pop(context),
                          child: Text('CANCEL', style: TextStyle(color: Colors.grey.shade500, fontWeight: FontWeight.bold, letterSpacing: 1.0)),
                        ),
                        const SizedBox(width: 16),
                        ElevatedButton(
                          style: ElevatedButton.styleFrom(
                            backgroundColor: _darkGreen,
                            foregroundColor: Colors.white,
                            padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 18),
                            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
                            elevation: 0,
                          ),
                          onPressed: isSubmitting
                              ? null
                              : () async {
                                  if (replyController.text.trim().isEmpty) return;
                                  setDialogState(() => isSubmitting = true);

                                  final answerData = {
                                    "author_name": widget.adminName,
                                    "content": replyController.text.trim()
                                  };

                                  final success = await ApiClient.replyToQuestion(questionData['id'], answerData);

                                  if (success && mounted) {
                                    await _fetchData();
                                    Navigator.pop(context);
                                    ScaffoldMessenger.of(context).showSnackBar(
                                      const SnackBar(content: Text('Response updated successfully.', style: TextStyle(fontWeight: FontWeight.bold)), backgroundColor: _darkGreen),
                                    );
                                  } else {
                                    setDialogState(() => isSubmitting = false);
                                    ScaffoldMessenger.of(context).showSnackBar(
                                      const SnackBar(content: Text('Failed to update response.', style: TextStyle(fontWeight: FontWeight.bold)), backgroundColor: Colors.redAccent),
                                    );
                                  }
                                },
                          child: isSubmitting
                              ? const SizedBox(height: 20, width: 20, child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white))
                              : const Text('UPDATE RESPONSE', style: TextStyle(fontWeight: FontWeight.bold, letterSpacing: 1.0)),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            );
          },
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    if (_isLoading) return const Center(child: CircularProgressIndicator(color: _darkGreen));

    return Scaffold(
      backgroundColor: Colors.transparent,
      body: _groupedQuestions.isEmpty
        ? _buildEmptyState()
        : RefreshIndicator(
            onRefresh: _fetchData,
            color: _standardGold,
            child: ListView.separated(
              padding: const EdgeInsets.all(32),
              itemCount: _groupedQuestions.keys.length,
              separatorBuilder: (context, index) => const SizedBox(height: 16),
              itemBuilder: (context, index) {
                final String authorKey = _groupedQuestions.keys.elementAt(index);
                final List<Map<String, dynamic>> authorQuestions = _groupedQuestions[authorKey]!;
                
                // 🚀 CALLS THE NEW BEAUTIFUL AUTHOR BUCKET WIDGET
                return _ExpandableResolvedAuthorBucket(
                  key: ValueKey(authorKey), 
                  authorName: authorKey,
                  questions: authorQuestions,
                  index: index,
                  formatDate: _formatDate,
                  onDelete: _deleteQuestionAction,
                  onEdit: _showEditReplyDialog,
                );
              },
            ),
          ),
    );
  }

  Widget _buildHeader() {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 32),
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border(bottom: BorderSide(color: Colors.grey.shade200)),
      ),
      child: Center(
        child: ConstrainedBox(
          constraints: const BoxConstraints(maxWidth: 800),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text(
                      'Resolved Queries',
                      style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold, color: Colors.black87),
                    ),
                    const SizedBox(height: 6),
                    Text(
                      'Past questions that have received an official response.',
                      style: TextStyle(fontSize: 14, color: Colors.grey.shade600),
                    ),
                  ],
                ),
              ),
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                decoration: BoxDecoration(
                  color: _darkGreen.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(20),
                  border: Border.all(color: _darkGreen.withOpacity(0.3)),
                ),
                child: Text(
                  '$_totalResolvedCount Resolved',
                  style: const TextStyle(color: _darkGreen, fontWeight: FontWeight.bold, fontSize: 14),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildEmptyState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Container(
            padding: const EdgeInsets.all(24),
            decoration: BoxDecoration(color: Colors.grey.shade100, shape: BoxShape.circle),
            child: const Icon(Icons.task_alt_rounded, size: 64, color: Colors.grey),
          ),
          const SizedBox(height: 24),
          const Text('No Resolved Questions', style: TextStyle(fontSize: 22, fontWeight: FontWeight.w900, color: Colors.black87)),
          const SizedBox(height: 8),
          Text('Answers will appear here once you resolve pending queries.', style: TextStyle(color: Colors.grey.shade500, fontSize: 15)),
        ],
      ),
    );
  }
}

// =====================================================================
// 🚀 NEW: AUTHOR BUCKET EXPANDABLE ACCORDION FOR RESOLVED QA
// =====================================================================
class _ExpandableResolvedAuthorBucket extends StatefulWidget {
  final String authorName;
  final List<Map<String, dynamic>> questions;
  final int index;
  final String Function(String) formatDate;
  final Function(int, String) onDelete;
  final Function(Map<String, dynamic>) onEdit;

  const _ExpandableResolvedAuthorBucket({
    super.key,
    required this.authorName,
    required this.questions,
    required this.index,
    required this.formatDate,
    required this.onDelete,
    required this.onEdit,
  });

  @override
  State<_ExpandableResolvedAuthorBucket> createState() => _ExpandableResolvedAuthorBucketState();
}

class _ExpandableResolvedAuthorBucketState extends State<_ExpandableResolvedAuthorBucket> {
  bool _isExpanded = false;

  void _toggleExpand() {
    setState(() {
      _isExpanded = !_isExpanded;
    });
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedContainer(
      duration: const Duration(milliseconds: 300),
      curve: Curves.easeInOut,
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border.all(
          color: _isExpanded ? _darkGreen.withOpacity(0.5) : Colors.grey.shade200, 
          width: _isExpanded ? 1.5 : 1.0
        ),
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          if (_isExpanded)
            BoxShadow(color: _darkGreen.withOpacity(0.05), blurRadius: 15, offset: const Offset(0, 8))
          else
            BoxShadow(color: Colors.black.withOpacity(0.02), blurRadius: 8, offset: const Offset(0, 2))
        ],
      ),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(12),
        child: Material(
          color: Colors.transparent,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // --- 🚀 AUTHOR HEADER (ALWAYS VISIBLE) ---
              InkWell(
                onTap: _toggleExpand,
                child: Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 16),
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Container(
                        width: 40,
                        height: 40,
                        decoration: BoxDecoration(
                          color: _isExpanded ? _darkGreen : Colors.grey.shade100,
                          shape: BoxShape.circle,
                        ),
                        alignment: Alignment.center,
                        child: Text(
                          '${widget.index + 1}', 
                          style: TextStyle(
                            fontSize: 16, 
                            fontWeight: FontWeight.bold, 
                            color: _isExpanded ? Colors.white : Colors.grey.shade600
                          ),
                        ),
                      ),
                      const SizedBox(width: 16),
                      
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              widget.authorName,
                              style: TextStyle(
                                fontSize: 16, 
                                fontWeight: FontWeight.w800, 
                                color: _isExpanded ? _darkGreen : Colors.black87
                              ),
                            ),
                            const SizedBox(height: 4),
                            Text(
                              'Resolved communications', 
                              style: TextStyle(fontSize: 13, color: Colors.grey.shade500, fontWeight: FontWeight.w500)
                            ),
                          ],
                        ),
                      ),
                      const SizedBox(width: 16),

                      // 🚀 RESOLVED BADGE & CHEVRON
                      Row(
                        children: [
                          Container(
                            padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
                            decoration: BoxDecoration(
                              color: _darkGreen.withOpacity(0.1), 
                              borderRadius: BorderRadius.circular(20)
                            ),
                            child: Row(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                const Icon(Icons.check_circle, size: 12, color: _darkGreen),
                                const SizedBox(width: 6),
                                Text('${widget.questions.length} RESOLVED', style: const TextStyle(color: _darkGreen, fontSize: 11, fontWeight: FontWeight.w900, letterSpacing: 1.0)),
                              ],
                            ),
                          ),
                          const SizedBox(width: 12),
                          AnimatedRotation(
                            turns: _isExpanded ? 0.5 : 0.0,
                            duration: const Duration(milliseconds: 300),
                            child: Icon(Icons.keyboard_arrow_down_rounded, color: Colors.grey.shade400, size: 28),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ),

              // --- 🚀 EXPANDABLE NESTED QUESTIONS ---
              AnimatedSize(
                duration: const Duration(milliseconds: 300),
                curve: Curves.fastOutSlowIn,
                alignment: Alignment.topCenter,
                child: SizedBox(
                  height: _isExpanded ? null : 0.0,
                  child: Column(
                    children: [
                      const Divider(height: 1, thickness: 1),
                      Container(
                        color: Colors.grey.shade50,
                        padding: const EdgeInsets.all(20),
                        child: Column(
                          children: List.generate(widget.questions.length, (qIndex) {
                            final question = widget.questions[qIndex];
                            final List answers = question['answers'] ?? [];
                            final String officialAnswer = answers.isNotEmpty ? answers.first['content'] : '';
                            
                            return Container(
                              margin: EdgeInsets.only(bottom: qIndex == widget.questions.length - 1 ? 0 : 16),
                              decoration: BoxDecoration(
                                color: Colors.white,
                                borderRadius: BorderRadius.circular(8),
                                border: Border.all(color: Colors.grey.shade200)
                              ),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Padding(
                                    padding: const EdgeInsets.all(20),
                                    child: Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        Row(
                                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                          children: [
                                            Expanded(
                                              child: Text(
                                                question['title'] ?? 'Untitled', 
                                                style: const TextStyle(fontSize: 15, fontWeight: FontWeight.w800, color: Colors.black87)
                                              ),
                                            ),
                                            Text(
                                              widget.formatDate(question['created_at'] ?? ''), 
                                              style: TextStyle(fontSize: 12, color: Colors.grey.shade400, fontWeight: FontWeight.w600)
                                            ),
                                          ],
                                        ),
                                        const SizedBox(height: 12),
                                        Text(
                                          question['body'] ?? 'No details provided.', 
                                          style: const TextStyle(fontSize: 14, color: Colors.black87, height: 1.5)
                                        ),
                                      ],
                                    ),
                                  ),

                                  // Official Response Inside Nested Card
                                  if (officialAnswer.isNotEmpty)
                                    Container(
                                      width: double.infinity,
                                      padding: const EdgeInsets.all(20),
                                      decoration: BoxDecoration(
                                        color: _standardGold.withOpacity(0.05),
                                        border: Border(
                                          top: BorderSide(color: _standardGold.withOpacity(0.1), width: 1),
                                          bottom: BorderSide(color: _standardGold.withOpacity(0.1), width: 1),
                                        ),
                                      ),
                                      child: Column(
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        children: [
                                          const Row(
                                            children: [
                                              Icon(Icons.verified_rounded, color: _standardGold, size: 16),
                                              SizedBox(width: 8),
                                              Text('OFFICIAL RESPONSE', style: TextStyle(fontSize: 11, fontWeight: FontWeight.w900, color: _standardGold, letterSpacing: 1.5)),
                                            ],
                                          ),
                                          const SizedBox(height: 12),
                                          Text(officialAnswer, style: const TextStyle(fontSize: 14, color: Colors.black87, height: 1.6, fontWeight: FontWeight.w500)),
                                        ],
                                      ),
                                    ),
                                  
                                  // Action Buttons
                                  Container(
                                    padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                                    decoration: BoxDecoration(
                                      color: Colors.white,
                                      border: Border(top: BorderSide(color: Colors.grey.shade100)),
                                      borderRadius: const BorderRadius.vertical(bottom: Radius.circular(8))
                                    ),
                                    child: Row(
                                      mainAxisAlignment: MainAxisAlignment.end,
                                      children: [
                                        TextButton.icon(
                                          onPressed: () => widget.onDelete(question['id'], widget.authorName),
                                          icon: const Icon(Icons.delete_outline_rounded, size: 16),
                                          label: const Text('Delete Log', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 13)),
                                          style: TextButton.styleFrom(foregroundColor: Colors.redAccent),
                                        ),
                                        const SizedBox(width: 16),
                                        OutlinedButton.icon(
                                          onPressed: () => widget.onEdit(question),
                                          icon: const Icon(Icons.edit_rounded, size: 16),
                                          label: const Text('Edit Response', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 13, letterSpacing: 0.5)),
                                          style: OutlinedButton.styleFrom(
                                            foregroundColor: Colors.black87,
                                            side: BorderSide(color: Colors.grey.shade300, width: 1.5),
                                            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
                                            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(6)),
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                ],
                              ),
                            );
                          }),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}