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

import 'dart:io';

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

import '../../../../core/services/connect_social_service.dart';
import 'channels_utils.dart';

class FirebaseCommentsSheet extends StatefulWidget {
  final int postId;
  final String currentUserName;
  final String currentUserEmail;
  final String? currentUserPic;
  final String? postAuthorEmail;
  final List<dynamic> registeredUsers;
  final VoidCallback onCommentAdded;

  const FirebaseCommentsSheet({
    super.key,
    required this.postId,
    required this.currentUserName,
    required this.currentUserEmail,
    this.currentUserPic,
    this.postAuthorEmail,
    required this.registeredUsers,
    required this.onCommentAdded,
  });

  @override
  State<FirebaseCommentsSheet> createState() => _FirebaseCommentsSheetState();
}

class _FirebaseCommentsSheetState extends State<FirebaseCommentsSheet> {
  final _commentController = TextEditingController();
  final _focusNode = FocusNode();
  final _picker = ImagePicker();

  List<Map<String, dynamic>> _comments = [];
  bool _loading = true;
  bool _sending = false;
  String? _error;
  int? _replyingToId;
  String? _replyingToName;
  File? _selectedImage;
  bool _showMentions = false;
  List<dynamic> _mentionResults = [];

  @override
  void initState() {
    super.initState();
    _loadComments();
    _commentController.addListener(_handleMentions);
  }

  @override
  void dispose() {
    _commentController.removeListener(_handleMentions);
    _commentController.dispose();
    _focusNode.dispose();
    super.dispose();
  }

  String _cleanError(Object error) => error.toString().replaceFirst(RegExp(r'^Exception:\s*'), '').trim();

  int _int(dynamic value) => int.tryParse('${value ?? 0}') ?? 0;

  Future<void> _loadComments() async {
    if (!mounted) return;
    setState(() {
      _loading = true;
      _error = null;
    });
    try {
      final comments = await ConnectSocialService.getComments(widget.postId);
      if (!mounted) return;
      setState(() {
        _comments = comments;
        _loading = false;
      });
    } catch (e) {
      if (!mounted) return;
      setState(() {
        _loading = false;
        _error = _cleanError(e);
      });
    }
  }

  void _handleMentions() {
    final text = _commentController.text;
    final cursor = _commentController.selection.baseOffset;
    if (cursor < 0 || cursor > text.length) return;
    final before = text.substring(0, cursor);
    final at = before.lastIndexOf('@');
    if (at < 0) {
      if (_showMentions) setState(() => _showMentions = false);
      return;
    }
    final query = before.substring(at + 1);
    if (query.contains(RegExp(r'[,;:!?\n]')) || query.length > 40) {
      if (_showMentions) setState(() => _showMentions = false);
      return;
    }
    final clean = query.toLowerCase().trim();
    final results = widget.registeredUsers.where((u) {
      final name = (u['full_name'] ?? u['name'] ?? '').toString().toLowerCase();
      return clean.isEmpty || name.contains(clean);
    }).take(8).toList();
    setState(() {
      _mentionResults = results;
      _showMentions = true;
    });
  }

  void _insertMention(dynamic user) {
    final name = (user['full_name'] ?? user['name'] ?? '').toString().trim();
    if (name.isEmpty) return;
    final value = _commentController.value;
    final cursor = value.selection.baseOffset < 0 ? value.text.length : value.selection.baseOffset;
    final before = value.text.substring(0, cursor);
    final at = before.lastIndexOf('@');
    if (at < 0) return;
    final replacement = '@$name ';
    final next = value.text.replaceRange(at, cursor, replacement);
    _commentController.value = TextEditingValue(
      text: next,
      selection: TextSelection.collapsed(offset: at + replacement.length),
    );
    setState(() => _showMentions = false);
    _focusNode.requestFocus();
  }

  Future<void> _pickImage() async {
    final picked = await _picker.pickImage(source: ImageSource.gallery, imageQuality: 80);
    if (picked == null) return;
    final file = File(picked.path);
    if (await file.length() > 8 * 1024 * 1024) {
      if (mounted) ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('Comment picture must not exceed 8 MB.'), backgroundColor: Colors.redAccent));
      return;
    }
    setState(() => _selectedImage = file);
    _focusNode.requestFocus();
  }

  void _startReply(Map<String, dynamic> comment) {
    setState(() {
      _replyingToId = _int(comment['id']);
      _replyingToName = (comment['author_name'] ?? 'User').toString();
    });
    _focusNode.requestFocus();
  }

  Future<void> _submit() async {
    final text = _commentController.text.trim();
    if (_sending || (text.isEmpty && _selectedImage == null)) return;
    setState(() => _sending = true);

    try {
      final created = await ConnectSocialService.createComment(
        postId: widget.postId,
        content: text,
        parentId: _replyingToId,
        image: _selectedImage,
      );
      if (!mounted) return;
      setState(() {
        _comments.add(created);
        _commentController.clear();
        _selectedImage = null;
        _replyingToId = null;
        _replyingToName = null;
        _showMentions = false;
      });
      widget.onCommentAdded();

      // The PHP comments endpoint creates the social notification on the server.
      // This avoids stale/duplicate Firestore notification counts for PHP-backed posts.
    } catch (e) {
      if (mounted) ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(_cleanError(e)), backgroundColor: Colors.red.shade700));
    } finally {
      if (mounted) setState(() => _sending = false);
    }
  }

  String _time(dynamic raw) {
    final date = DateTime.tryParse('${raw ?? ''}')?.toLocal();
    if (date == null) return 'Just now';
    final diff = DateTime.now().difference(date);
    if (diff.inMinutes < 1) return 'Just now';
    if (diff.inHours < 1) return '${diff.inMinutes}m';
    if (diff.inHours < 24) return '${diff.inHours}h';
    if (diff.inDays < 7) return '${diff.inDays}d';
    return '${date.day}/${date.month}/${date.year}';
  }

  List<Widget> _commentThreads() {
    final roots = _comments.where((c) => c['parent_id'] == null || _int(c['parent_id']) <= 0).toList();
    final widgets = <Widget>[];
    for (final root in roots) {
      widgets.add(_commentTile(root));
      final rootId = _int(root['id']);
      final replies = _comments.where((c) => _int(c['parent_id']) == rootId).toList();
      for (final reply in replies) {
        widgets.add(Padding(padding: const EdgeInsets.only(left: 46), child: _commentTile(reply, isReply: true)));
      }
      widgets.add(const SizedBox(height: 8));
    }
    return widgets;
  }

  Widget _commentTile(Map<String, dynamic> comment, {bool isReply = false}) {
    final name = (comment['author_name'] ?? 'Rockview User').toString();
    final content = (comment['content'] ?? '').toString();
    final imageUrl = (comment['image_url'] ?? '').toString();
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 5),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          buildSmartFbAvatar(comment['author_profile_picture']?.toString(), name, radius: isReply ? 14 : 17),
          const SizedBox(width: 8),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 9),
                  decoration: BoxDecoration(color: const Color(0xFFF0F2F5), borderRadius: BorderRadius.circular(15)),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(name, style: const TextStyle(fontSize: 13, fontWeight: FontWeight.w800, color: FbFeedColors.textMain)),
                      if (content.isNotEmpty) ...[
                        const SizedBox(height: 2),
                        Text(content, style: const TextStyle(fontSize: 14, height: 1.35, color: FbFeedColors.textMain)),
                      ],
                      if (imageUrl.isNotEmpty) ...[
                        const SizedBox(height: 8),
                        GestureDetector(
                          onTap: () => showZoomableImage(context, imageUrl),
                          child: ClipRRect(borderRadius: BorderRadius.circular(10), child: buildSmartFbImage(imageUrl, width: double.infinity, height: 180, fit: BoxFit.cover)),
                        ),
                      ],
                    ],
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(left: 8, top: 4),
                  child: Row(
                    children: [
                      Text(_time(comment['created_at']), style: const TextStyle(fontSize: 11, color: FbFeedColors.textSecondary)),
                      const SizedBox(width: 14),
                      InkWell(onTap: () => _startReply(comment), child: const Text('Reply', style: TextStyle(fontSize: 11, fontWeight: FontWeight.w800, color: FbFeedColors.textSecondary))),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.sizeOf(context);
    final bottom = MediaQuery.of(context).viewInsets.bottom;
    return Center(
      child: ConstrainedBox(
        constraints: BoxConstraints(maxWidth: 620, maxHeight: size.height * .92),
        child: Container(
          margin: EdgeInsets.only(top: size.width < 600 ? 18 : 38),
          decoration: const BoxDecoration(color: Colors.white, borderRadius: BorderRadius.vertical(top: Radius.circular(20))),
          child: Column(
            children: [
              Padding(
                padding: const EdgeInsets.fromLTRB(16, 10, 8, 10),
                child: Row(
                  children: [
                    const Expanded(child: Text('Comments', style: TextStyle(fontWeight: FontWeight.w800, fontSize: 18))),
                    IconButton(onPressed: _loadComments, icon: const Icon(Icons.refresh_rounded), tooltip: 'Refresh'),
                    IconButton(onPressed: () => Navigator.pop(context), icon: const Icon(Icons.close_rounded)),
                  ],
                ),
              ),
              const Divider(height: 1),
              Expanded(
                child: _loading
                    ? const Center(child: CircularProgressIndicator(color: FbFeedColors.blue))
                    : _error != null
                        ? Center(child: Padding(padding: const EdgeInsets.all(24), child: Column(mainAxisSize: MainAxisSize.min, children: [const Icon(Icons.error_outline_rounded, size: 44, color: Colors.redAccent), const SizedBox(height: 10), Text(_error!, textAlign: TextAlign.center), const SizedBox(height: 12), FilledButton.icon(onPressed: _loadComments, icon: const Icon(Icons.refresh_rounded), label: const Text('Try again'))])))
                        : _comments.isEmpty
                            ? const Center(child: Padding(padding: EdgeInsets.all(24), child: Text('No comments yet. Be the first to respond.', textAlign: TextAlign.center, style: TextStyle(color: FbFeedColors.textSecondary))))
                            : ListView(padding: const EdgeInsets.all(14), physics: const BouncingScrollPhysics(), children: _commentThreads()),
              ),
              Container(
                padding: EdgeInsets.fromLTRB(12, 8, 12, 12 + bottom),
                decoration: BoxDecoration(color: Colors.white, boxShadow: [BoxShadow(color: Colors.black.withOpacity(.06), blurRadius: 12, offset: const Offset(0, -3))]),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    if (_showMentions && _mentionResults.isNotEmpty)
                      Container(
                        constraints: const BoxConstraints(maxHeight: 160),
                        margin: const EdgeInsets.only(bottom: 8),
                        decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(12), border: Border.all(color: Colors.grey.shade200)),
                        child: ListView.builder(
                          shrinkWrap: true,
                          itemCount: _mentionResults.length,
                          itemBuilder: (_, index) {
                            final user = _mentionResults[index];
                            final name = (user['full_name'] ?? user['name'] ?? 'User').toString();
                            return ListTile(dense: true, leading: buildSmartFbAvatar(user['profile_picture']?.toString(), name, radius: 14), title: Text(name, style: const TextStyle(fontWeight: FontWeight.w600)), onTap: () => _insertMention(user));
                          },
                        ),
                      ),
                    if (_replyingToId != null)
                      Container(
                        width: double.infinity,
                        margin: const EdgeInsets.only(bottom: 7),
                        padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 7),
                        decoration: BoxDecoration(color: FbFeedColors.bg, borderRadius: BorderRadius.circular(10), border: const Border(left: BorderSide(color: FbFeedColors.blue, width: 3))),
                        child: Row(children: [Expanded(child: Text('Replying to $_replyingToName', style: const TextStyle(fontSize: 12, fontWeight: FontWeight.w700))), IconButton(onPressed: () => setState(() { _replyingToId = null; _replyingToName = null; }), icon: const Icon(Icons.close_rounded, size: 17), constraints: const BoxConstraints(), padding: const EdgeInsets.all(4))]),
                      ),
                    if (_selectedImage != null)
                      Container(
                        height: 90,
                        width: 120,
                        margin: const EdgeInsets.only(bottom: 8),
                        child: Stack(fit: StackFit.expand, children: [ClipRRect(borderRadius: BorderRadius.circular(10), child: Image.file(_selectedImage!, fit: BoxFit.cover)), Positioned(top: 4, right: 4, child: CircleAvatar(radius: 13, backgroundColor: Colors.white, child: IconButton(padding: EdgeInsets.zero, iconSize: 15, onPressed: () => setState(() => _selectedImage = null), icon: const Icon(Icons.close_rounded))))]),
                      ),
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.end,
                      children: [
                        IconButton(onPressed: _sending ? null : _pickImage, icon: const Icon(Icons.photo_camera_back_rounded, color: FbFeedColors.blue), tooltip: 'Add picture'),
                        Expanded(
                          child: TextField(
                            controller: _commentController,
                            focusNode: _focusNode,
                            minLines: 1,
                            maxLines: 5,
                            decoration: InputDecoration(hintText: _replyingToId == null ? 'Write a comment...' : 'Write a reply...', filled: true, fillColor: FbFeedColors.bg, border: OutlineInputBorder(borderRadius: BorderRadius.circular(22), borderSide: BorderSide.none), contentPadding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10)),
                          ),
                        ),
                        const SizedBox(width: 5),
                        CircleAvatar(
                          backgroundColor: FbFeedColors.blue,
                          child: IconButton(onPressed: _sending ? null : _submit, icon: _sending ? const SizedBox(width: 17, height: 17, child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white)) : const Icon(Icons.send_rounded, color: Colors.white, size: 19)),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
