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

import 'dart:io';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';
import 'package:dio/dio.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:open_filex/open_filex.dart';

import '../../../../core/services/chat_media_service.dart';


const Color _bubbleGreen = Color.fromARGB(255, 2, 105, 48);
const Color _bubbleGold = Color.fromARGB(255, 204, 117, 4);
const Color _bubbleInk = Color(0xFF17231C);
const Color _bubbleMuted = Color(0xFF66756C);
const Color _bubbleBorder = Color(0xFFE0E8E3);

class ChatMessageBubble extends StatefulWidget {
  final String text;
  final String time;
  final bool isMe;
  final bool isRead;
  final bool isGroup;          
  final String? senderName;    
  final String? senderPic; 
  final String? replyToText;
  final String? replyToSender;
  
  // 🚀 FILE HANDLING FIELDS
  final String? fileUrl;
  final String? fileName;
  final String? fileType;
  final String? downloadUrl;
  final int? fileSizeBytes;
  final String? localPath;

  final VoidCallback? onAvatarTap;
  final VoidCallback? onReply;
  final VoidCallback? onForward;

  const ChatMessageBubble({
    super.key,
    required this.text,
    required this.time,
    required this.isMe,
    this.isRead = false,
    this.isGroup = false,
    this.senderName,
    this.senderPic,
    this.replyToText,
    this.replyToSender,
    this.fileUrl,
    this.fileName,
    this.fileType,
    this.downloadUrl,
    this.fileSizeBytes,
    this.localPath,
    this.onAvatarTap,
    this.onReply,
    this.onForward,
  });

  @override
  State<ChatMessageBubble> createState() => _ChatMessageBubbleState();
}

class _ChatMessageBubbleState extends State<ChatMessageBubble> {
  bool _isHovered = false;
  bool _isExpanded = false;
  bool _isDownloading = false;
  bool _mediaHeadersReady = false;
  Map<String, String> _mediaHeaders = const <String, String>{};
  Offset _tapPosition = Offset.zero;

  @override
  void initState() {
    super.initState();
    if (_needsProtectedMediaHeaders()) {
      _loadMediaHeaders();
    } else {
      _mediaHeadersReady = true;
    }
  }

  @override
  void didUpdateWidget(covariant ChatMessageBubble oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.fileUrl != widget.fileUrl ||
        oldWidget.downloadUrl != widget.downloadUrl) {
      if (_needsProtectedMediaHeaders()) {
        _mediaHeadersReady = false;
        _loadMediaHeaders();
      } else if (!_mediaHeadersReady) {
        setState(() => _mediaHeadersReady = true);
      }
    }
  }

  bool _needsProtectedMediaHeaders() {
    return _isProtectedChatMedia(widget.fileUrl) ||
        _isProtectedChatMedia(widget.downloadUrl);
  }

  Future<void> _loadMediaHeaders() async {
    try {
      final headers = await ChatMediaService.downloadHeaders();
      if (!mounted) return;
      setState(() {
        _mediaHeaders = headers;
        _mediaHeadersReady = true;
      });
    } catch (_) {
      if (!mounted) return;
      setState(() => _mediaHeadersReady = true);
    }
  }

  bool _isProtectedChatMedia(String? url) {
    return url != null && url.contains('/api/chat_media_download.php');
  }

  ImageProvider? _getAvatarProvider(String? imageString) {
    if (imageString == null || imageString.isEmpty) return null;
    if (imageString.startsWith('http')) return NetworkImage(imageString);
    try {
      String clean = imageString.contains(',') ? imageString.split(',').last : imageString;
      return MemoryImage(base64Decode(clean.replaceAll(RegExp(r'\s+'), '')));
    } catch (e) { return null; }
  }

  void _storePosition(TapDownDetails details) => _tapPosition = details.globalPosition;

  void _showContextMenu() {
    final RenderObject? overlay = Overlay.of(context).context.findRenderObject();
    if (overlay is! RenderBox) return;

    showMenu<String>(
      context: context,
      position: RelativeRect.fromRect(_tapPosition & const Size(40, 40), Offset.zero & overlay.size),
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      elevation: 4, color: Colors.white,
      items: [
        const PopupMenuItem(value: 'Reply', child: Row(children: [Icon(Icons.reply_rounded, color: Color(0xFF026930), size: 20), SizedBox(width: 12), Text('Reply', style: TextStyle(fontSize: 14))])),
        const PopupMenuItem(value: 'Forward', child: Row(children: [Icon(Icons.shortcut_rounded, color: Colors.blue, size: 20), SizedBox(width: 12), Text('Forward', style: TextStyle(fontSize: 14))])),
        const PopupMenuItem(value: 'Copy', child: Row(children: [Icon(Icons.copy_rounded, color: Colors.grey, size: 20), SizedBox(width: 12), Text('Copy', style: TextStyle(fontSize: 14))])),
      ],
    ).then((value) {
      if (value == 'Reply' && widget.onReply != null) widget.onReply!();
      if (value == 'Copy') {
        Clipboard.setData(ClipboardData(text: widget.text));
        ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('Copied', style: TextStyle(color: Colors.white)), backgroundColor: Colors.black87, duration: Duration(seconds: 1)));
      }
      if (value == 'Forward') {
        _showForwardDialog();
      }
    });
  }

  void _showForwardDialog() {
    showDialog(
      context: context,
      builder: (context) => _ForwardMessageDialog(messageText: widget.text),
    );
  }

  // 🚀 FULL-SCREEN ZOOMABLE IMAGE VIEWER
  void _showZoomableImage(BuildContext context, ImageProvider imageProvider) {
    showDialog(
      context: context,
      barrierColor: Colors.black.withOpacity(0.9),
      builder: (ctx) => Dialog(
        backgroundColor: Colors.transparent,
        insetPadding: EdgeInsets.zero,
        child: Stack(
          fit: StackFit.expand,
          children: [
            InteractiveViewer(
              panEnabled: true,
              minScale: 0.5,
              maxScale: 4.0,
              child: Image(image: imageProvider),
            ),
            Positioned(
              top: 24,
              right: 24,
              child: IconButton(
                icon: const Icon(Icons.close_rounded, color: Colors.white, size: 32),
                onPressed: () => Navigator.pop(ctx),
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 🚀 NATIVE DOCUMENT READER LOGIC (WITH SMART DESKTOP FOLDER FALLBACK)
  Future<void> _handleFileClick() async {
    if (widget.fileUrl == null && widget.downloadUrl == null && widget.localPath == null) return;

    final remoteDownloadUrl = widget.downloadUrl ?? widget.fileUrl;
    String? targetPath;

    // 1. Check if the file is already the local original path
    try {
      if (widget.localPath != null && File(widget.localPath!).existsSync()) {
        targetPath = widget.localPath;
      }
    } catch (_) {}

    // 2. Check if we already downloaded it previously
    if (targetPath == null) {
      Directory? dir;
      try {
        if (Platform.isWindows || Platform.isMacOS || Platform.isLinux) {
          dir = await getDownloadsDirectory();
        } else if (Platform.isAndroid || Platform.isIOS) {
          dir = await getTemporaryDirectory(); 
        }
      } catch (_) {}
      
      dir ??= await getApplicationDocumentsDirectory(); 
      final savePath = '${dir.path}/${widget.fileName}';
      
      if (File(savePath).existsSync()) {
        targetPath = savePath;
      } else if (remoteDownloadUrl != null) {
        // 3. If it doesn't exist anywhere, Download it NOW
        setState(() => _isDownloading = true);
        try {
          final protected = _isProtectedChatMedia(remoteDownloadUrl);
          final headers = protected
              ? await ChatMediaService.downloadHeaders()
              : const <String, String>{};
          await Dio().download(
            remoteDownloadUrl,
            savePath,
            options: Options(headers: headers),
          );
          targetPath = savePath;
          if (mounted) {
            ScaffoldMessenger.of(context).showSnackBar(SnackBar(
              content: Text('Saved to device:\n$savePath', style: const TextStyle(fontSize: 12)),
              duration: const Duration(seconds: 3),
              backgroundColor: const Color(0xFF026930)
            ));
          }
        } catch (e) {
          if (mounted) {
            ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('Error downloading file.'), backgroundColor: Colors.redAccent));
          }
        }
        if (mounted) setState(() => _isDownloading = false);
      }
    }

    // 4. OPEN THE FILE DIRECTLY OR OPEN ITS FOLDER
    if (targetPath != null && File(targetPath).existsSync()) {
      final result = await OpenFilex.open(targetPath);
      
      // 🚀 IF OS CANNOT OPEN IT DIRECTLY (e.g. no MS Word installed), OPEN THE FOLDER ITSELF!
      if (result.type != ResultType.done && mounted) {
        try {
          // This opens the File Explorer / Finder directly to where the file is!
          final folderPath = File(targetPath).parent.path;
          await OpenFilex.open(folderPath);
          
          if (mounted) {
            ScaffoldMessenger.of(context).showSnackBar(
              const SnackBar(
                content: Text('No default app found. Opening file location...'), 
                backgroundColor: Colors.orange
              )
            );
          }
        } catch (e) {
          // Ultimate fallback, just tell them where it is
          if (mounted) {
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(content: Text('File saved at:\n$targetPath'), backgroundColor: const Color(0xFF026930))
            );
          }
        }
      }
    }
  }

  String _formatFileSize(int? bytes) {
    if (bytes == null || bytes <= 0) return '';
    if (bytes < 1024) return '$bytes B';
    final kb = bytes / 1024;
    if (kb < 1024) return '${kb.toStringAsFixed(kb < 10 ? 1 : 0)} KB';
    final mb = kb / 1024;
    if (mb < 1024) return '${mb.toStringAsFixed(mb < 10 ? 1 : 0)} MB';
    final gb = mb / 1024;
    return '${gb.toStringAsFixed(1)} GB';
  }

  // 🚀 DYNAMIC FILE ICON GENERATOR
  IconData _getFileIcon(String ext) {
    switch (ext) {
      case 'pdf': return Icons.picture_as_pdf_rounded;
      case 'doc': case 'docx': return Icons.description_rounded;
      case 'xls': case 'xlsx': case 'csv': return Icons.table_chart_rounded;
      case 'ppt': case 'pptx': return Icons.slideshow_rounded;
      case 'zip': case 'rar': case '7z': return Icons.folder_zip_rounded;
      case 'txt': return Icons.text_snippet_rounded;
      case 'mp3': case 'wav': case 'ogg': return Icons.audio_file_rounded;
      case 'mp4': case 'mov': case 'mkv': return Icons.video_file_rounded;
      default: return Icons.insert_drive_file_rounded;
    }
  }

  // 🚀 DYNAMIC FILE COLOR GENERATOR
  Color _getFileColor(String ext) {
    switch (ext) {
      case 'pdf': return Colors.redAccent;
      case 'doc': case 'docx': return Colors.blueAccent;
      case 'xls': case 'xlsx': case 'csv': return Colors.green.shade600;
      case 'ppt': case 'pptx': return Colors.orangeAccent;
      case 'zip': case 'rar': case '7z': return Colors.brown.shade400;
      case 'txt': return Colors.grey.shade600;
      case 'mp3': case 'wav': case 'ogg': return Colors.purpleAccent;
      case 'mp4': case 'mov': case 'mkv': return Colors.pinkAccent;
      default: return const Color(0xFF026930);
    }
  }

  // Responsive attachment renderer. The file/download behaviour is unchanged;
  // only the presentation adapts to the width of the message bubble.
  Widget _buildAttachment(BuildContext context) {
    if (widget.fileUrl == null && widget.localPath == null) {
      return const SizedBox.shrink();
    }

    final safeFileName = (widget.fileName ?? '').toLowerCase();
    final fileExt = safeFileName.contains('.') ? safeFileName.split('.').last : '';
    final isImage = widget.fileType == 'image' ||
        ['png', 'jpg', 'jpeg', 'gif', 'webp'].contains(fileExt);

    var useLocal = false;
    try {
      if (widget.localPath != null && File(widget.localPath!).existsSync()) {
        useLocal = true;
      }
    } catch (_) {}

    return LayoutBuilder(
      builder: (context, constraints) {
        final finiteWidth = constraints.maxWidth.isFinite ? constraints.maxWidth : 280.0;
        final previewWidth = finiteWidth < 280 ? finiteWidth : 280.0;
        final documentHeight = previewWidth < 220 ? 118.0 : 142.0;

        if (!isImage) {
          final fileColor = _getFileColor(fileExt);
          final fileIcon = _getFileIcon(fileExt);

          return GestureDetector(
            onTap: _handleFileClick,
            child: Container(
              margin: const EdgeInsets.only(bottom: 8),
              width: previewWidth,
              height: documentHeight,
              clipBehavior: Clip.antiAlias,
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(13),
                border: Border.all(color: _bubbleBorder),
              ),
              child: Stack(
                children: [
                  Column(
                    children: [
                      Expanded(
                        child: Container(
                          width: double.infinity,
                          color: fileColor.withOpacity(.07),
                          child: Stack(
                            alignment: Alignment.center,
                            children: [
                              Icon(fileIcon, size: 56, color: fileColor.withOpacity(.14)),
                              Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  Container(
                                    width: previewWidth * .42,
                                    height: 5,
                                    margin: const EdgeInsets.only(bottom: 7),
                                    decoration: BoxDecoration(
                                      color: fileColor.withOpacity(.18),
                                      borderRadius: BorderRadius.circular(4),
                                    ),
                                  ),
                                  Container(
                                    width: previewWidth * .32,
                                    height: 5,
                                    margin: const EdgeInsets.only(bottom: 7),
                                    decoration: BoxDecoration(
                                      color: fileColor.withOpacity(.18),
                                      borderRadius: BorderRadius.circular(4),
                                    ),
                                  ),
                                  Container(
                                    width: previewWidth * .48,
                                    height: 5,
                                    decoration: BoxDecoration(
                                      color: fileColor.withOpacity(.18),
                                      borderRadius: BorderRadius.circular(4),
                                    ),
                                  ),
                                ],
                              ),
                            ],
                          ),
                        ),
                      ),
                      Container(
                        height: 46,
                        padding: const EdgeInsets.symmetric(horizontal: 11),
                        color: Colors.white,
                        child: Row(
                          children: [
                            Icon(fileIcon, color: fileColor, size: 22),
                            const SizedBox(width: 8),
                            Expanded(
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(
                                    widget.fileName ?? 'Document',
                                    maxLines: 1,
                                    overflow: TextOverflow.ellipsis,
                                    style: const TextStyle(
                                      fontWeight: FontWeight.w800,
                                      fontSize: 12.5,
                                      color: _bubbleInk,
                                    ),
                                  ),
                                  if (_formatFileSize(widget.fileSizeBytes).isNotEmpty) ...[
                                    const SizedBox(height: 2),
                                    Text(
                                      _formatFileSize(widget.fileSizeBytes),
                                      style: const TextStyle(
                                        fontSize: 10,
                                        color: _bubbleMuted,
                                        fontWeight: FontWeight.w600,
                                      ),
                                    ),
                                  ],
                                ],
                              ),
                            ),
                            Icon(
                              useLocal ? Icons.open_in_new_rounded : Icons.download_rounded,
                              color: _bubbleMuted,
                              size: 18,
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                  if (_isDownloading)
                    Positioned.fill(
                      child: ColoredBox(
                        color: Colors.black26,
                        child: const Center(
                          child: SizedBox(
                            width: 28,
                            height: 28,
                            child: CircularProgressIndicator(
                              color: Colors.white,
                              strokeWidth: 2.6,
                            ),
                          ),
                        ),
                      ),
                    ),
                ],
              ),
            ),
          );
        }

        ImageProvider? imageProvider;
        if (useLocal) {
          imageProvider = FileImage(File(widget.localPath!));
        } else if (widget.fileUrl != null && widget.fileUrl!.isNotEmpty) {
          final protected = _isProtectedChatMedia(widget.fileUrl);
          if (protected && !_mediaHeadersReady) {
            return Container(
              width: previewWidth,
              height: previewWidth < 200 ? 180.0 : previewWidth,
              alignment: Alignment.center,
              decoration: BoxDecoration(
                color: const Color(0xFFF0F3F1),
                borderRadius: BorderRadius.circular(12),
                border: Border.all(color: _bubbleBorder),
              ),
              child: const SizedBox(
                width: 24,
                height: 24,
                child: CircularProgressIndicator(
                  strokeWidth: 2.3,
                  color: _bubbleGreen,
                ),
              ),
            );
          }
          imageProvider = NetworkImage(
            widget.fileUrl!,
            headers: protected ? _mediaHeaders : null,
          );
        }

        if (imageProvider == null) return const SizedBox.shrink();

        final imageHeight = previewWidth < 200 ? 180.0 : previewWidth;
        return Padding(
          padding: const EdgeInsets.only(bottom: 7),
          child: Stack(
            alignment: Alignment.center,
            children: [
              GestureDetector(
                onTap: () => _showZoomableImage(context, imageProvider!),
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(12),
                  child: Image(
                    image: imageProvider,
                    width: previewWidth,
                    height: imageHeight,
                    fit: BoxFit.cover,
                    errorBuilder: (ctx, err, stack) => Container(
                      width: previewWidth,
                      height: imageHeight,
                      color: const Color(0xFFF0F3F1),
                      alignment: Alignment.center,
                      child: const Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Icon(Icons.broken_image_outlined, color: _bubbleMuted, size: 40),
                          SizedBox(height: 7),
                          Text('Image unavailable', style: TextStyle(color: _bubbleMuted, fontSize: 11.5)),
                        ],
                      ),
                    ),
                  ),
                ),
              ),
              if (!useLocal && widget.fileUrl != null && widget.fileUrl!.isNotEmpty)
                Material(
                  color: Colors.black.withOpacity(.48),
                  shape: const CircleBorder(),
                  child: InkWell(
                    customBorder: const CircleBorder(),
                    onTap: _handleFileClick,
                    child: Padding(
                      padding: const EdgeInsets.all(11),
                      child: _isDownloading
                          ? const SizedBox(
                              width: 26,
                              height: 26,
                              child: CircularProgressIndicator(color: Colors.white, strokeWidth: 2.5),
                            )
                          : const Icon(Icons.download_rounded, color: Colors.white, size: 26),
                    ),
                  ),
                ),
            ],
          ),
        );
      },
    );
  }

  List<TextSpan> _formatText(String text) {
    List<TextSpan> spans = [];
    text.splitMapJoin(
      RegExp(r'\*(.*?)\*|_(.*?)_|~(.*?)~'),
      onMatch: (m) {
        if (m.group(1) != null) spans.add(TextSpan(text: m.group(1), style: const TextStyle(fontWeight: FontWeight.bold)));
        else if (m.group(2) != null) spans.add(TextSpan(text: m.group(2), style: const TextStyle(fontStyle: FontStyle.italic)));
        else if (m.group(3) != null) spans.add(TextSpan(text: m.group(3), style: const TextStyle(decoration: TextDecoration.lineThrough)));
        return '';
      },
      onNonMatch: (n) {
        spans.add(TextSpan(text: n));
        return '';
      },
    );
    return spans;
  }

  @override
  Widget build(BuildContext context) {
    final showSenderInfo = widget.isGroup && !widget.isMe;
    final senderColor = (widget.senderName?.length ?? 0) % 2 == 0
        ? const Color(0xFF8A3F6E)
        : _bubbleGreen;
    final validAvatar = _getAvatarProvider(widget.senderPic);
    final showAvatar = showSenderInfo && validAvatar != null;

    var cleanText = widget.text.replaceAll(RegExp(r'\*(.*?)\*'), r'$1').trim();
    if (cleanText == '📷 Photo' || cleanText.startsWith('📄 Document')) {
      cleanText = '';
    }

    final isLongText = cleanText.length > 300;
    final displayText = (isLongText && !_isExpanded)
        ? '${cleanText.substring(0, 300)}...'
        : cleanText;

    return LayoutBuilder(
      builder: (context, constraints) {
        final available = constraints.maxWidth.isFinite
            ? constraints.maxWidth
            : MediaQuery.of(context).size.width;
        final ratio = available < 420 ? .84 : .72;
        final calculated = available * ratio;
        final maxBubbleWidth = calculated > 560 ? 560.0 : calculated;

        return Align(
          alignment: widget.isMe ? Alignment.centerRight : Alignment.centerLeft,
          child: Padding(
            padding: EdgeInsets.only(
              left: widget.isMe ? 28 : 0,
              right: widget.isMe ? 0 : 28,
            ),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                if (showAvatar)
                  GestureDetector(
                    onTap: widget.onAvatarTap,
                    child: Container(
                      margin: const EdgeInsets.only(right: 7, top: 3),
                      child: CircleAvatar(
                        radius: 15,
                        backgroundColor: const Color(0xFFE7ECE9),
                        backgroundImage: validAvatar,
                      ),
                    ),
                  ),
                Flexible(
                  child: MouseRegion(
                    onEnter: (_) {
                      if (mounted) setState(() => _isHovered = true);
                    },
                    onExit: (_) {
                      if (mounted) setState(() => _isHovered = false);
                    },
                    child: GestureDetector(
                      onTapDown: _storePosition,
                      onLongPress: _showContextMenu,
                      child: Stack(
                        clipBehavior: Clip.none,
                        children: [
                          Container(
                            margin: const EdgeInsets.only(bottom: 9),
                            constraints: BoxConstraints(maxWidth: maxBubbleWidth),
                            decoration: BoxDecoration(
                              color: widget.isMe
                                  ? const Color(0xFFE3F2E7)
                                  : Colors.white,
                              borderRadius: BorderRadius.only(
                                topLeft: Radius.circular(widget.isMe ? 15 : 5),
                                topRight: Radius.circular(widget.isMe ? 5 : 15),
                                bottomLeft: const Radius.circular(15),
                                bottomRight: const Radius.circular(15),
                              ),
                              border: Border.all(
                                color: widget.isMe
                                    ? _bubbleGreen.withOpacity(.12)
                                    : _bubbleBorder,
                              ),
                              boxShadow: [
                                BoxShadow(
                                  color: Colors.black.withOpacity(.025),
                                  blurRadius: 5,
                                  offset: const Offset(0, 2),
                                ),
                              ],
                            ),
                            child: Padding(
                              padding: EdgeInsets.fromLTRB(
                                11,
                                9,
                                _isHovered ? 24 : 11,
                                7,
                              ),
                              child: Column(
                                mainAxisSize: MainAxisSize.min,
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  if (showSenderInfo && widget.senderName != null)
                                    Padding(
                                      padding: const EdgeInsets.only(bottom: 5),
                                      child: Text(
                                        widget.senderName!,
                                        maxLines: 1,
                                        overflow: TextOverflow.ellipsis,
                                        style: TextStyle(
                                          fontWeight: FontWeight.w900,
                                          fontSize: 12.5,
                                          color: senderColor,
                                        ),
                                      ),
                                    ),
                                  if (widget.replyToText != null &&
                                      widget.replyToText!.isNotEmpty)
                                    Container(
                                      margin: const EdgeInsets.only(bottom: 7),
                                      clipBehavior: Clip.antiAlias,
                                      decoration: BoxDecoration(
                                        color: Colors.black.withOpacity(.035),
                                        borderRadius: BorderRadius.circular(10),
                                      ),
                                      child: IntrinsicHeight(
                                        child: Row(
                                          mainAxisSize: MainAxisSize.min,
                                          children: [
                                            Container(width: 4, color: senderColor),
                                            Flexible(
                                              child: Padding(
                                                padding: const EdgeInsets.all(8),
                                                child: Column(
                                                  crossAxisAlignment: CrossAxisAlignment.start,
                                                  children: [
                                                    Text(
                                                      widget.replyToSender ?? 'User',
                                                      style: TextStyle(
                                                        fontWeight: FontWeight.w900,
                                                        fontSize: 11.5,
                                                        color: senderColor,
                                                      ),
                                                    ),
                                                    const SizedBox(height: 3),
                                                    Text(
                                                      widget.replyToText!,
                                                      maxLines: 3,
                                                      overflow: TextOverflow.ellipsis,
                                                      style: const TextStyle(
                                                        fontSize: 12,
                                                        color: _bubbleMuted,
                                                      ),
                                                    ),
                                                  ],
                                                ),
                                              ),
                                            ),
                                          ],
                                        ),
                                      ),
                                    ),
                                  _buildAttachment(context),
                                  if (cleanText.isNotEmpty)
                                    RichText(
                                      text: TextSpan(
                                        style: const TextStyle(
                                          fontSize: 14.5,
                                          color: _bubbleInk,
                                          height: 1.36,
                                        ),
                                        children: _formatText(displayText),
                                      ),
                                    ),
                                  if (isLongText && !_isExpanded)
                                    InkWell(
                                      onTap: () => setState(() => _isExpanded = true),
                                      child: const Padding(
                                        padding: EdgeInsets.only(top: 4),
                                        child: Text(
                                          'Read more',
                                          style: TextStyle(
                                            color: _bubbleGreen,
                                            fontWeight: FontWeight.w800,
                                            fontSize: 12.5,
                                          ),
                                        ),
                                      ),
                                    ),
                                  const SizedBox(height: 4),
                                  Align(
                                    alignment: Alignment.bottomRight,
                                    child: Row(
                                      mainAxisSize: MainAxisSize.min,
                                      children: [
                                        Text(
                                          widget.time,
                                          style: const TextStyle(fontSize: 10.5, color: _bubbleMuted),
                                        ),
                                        if (widget.isMe) ...[
                                          const SizedBox(width: 4),
                                          Icon(
                                            Icons.done_all_rounded,
                                            size: 15,
                                            color: widget.isRead ? _bubbleGreen : Colors.grey.shade500,
                                          ),
                                        ],
                                      ],
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ),
                          if (_isHovered)
                            Positioned(
                              top: 5,
                              right: 5,
                              child: Material(
                                color: Colors.white,
                                shape: const CircleBorder(),
                                elevation: 1,
                                child: InkWell(
                                  customBorder: const CircleBorder(),
                                  onTapDown: _storePosition,
                                  onTap: _showContextMenu,
                                  child: const Padding(
                                    padding: EdgeInsets.all(3),
                                    child: Icon(
                                      Icons.keyboard_arrow_down_rounded,
                                      size: 18,
                                      color: _bubbleMuted,
                                    ),
                                  ),
                                ),
                              ),
                            ),
                        ],
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }
}

// ============================================================================
// 🚀 PIXEL-PERFECT WHATSAPP FORWARD MESSAGE DIALOG
// ============================================================================
class _ForwardMessageDialog extends StatefulWidget {
  final String messageText;
  const _ForwardMessageDialog({required this.messageText});

  @override
  State<_ForwardMessageDialog> createState() => _ForwardMessageDialogState();
}

class _ForwardMessageDialogState extends State<_ForwardMessageDialog> {
  final Set<String> _selectedEmails = {};
  String _searchQuery = '';

  ImageProvider? _getAvatarProvider(String? imageString) {
    if (imageString == null || imageString.isEmpty) return null;
    if (imageString.startsWith('http')) return NetworkImage(imageString);
    try {
      String clean = imageString.contains(',') ? imageString.split(',').last : imageString;
      return MemoryImage(base64Decode(clean.replaceAll(RegExp(r'\s+'), '')));
    } catch (e) { return null; }
  }

  @override
  Widget build(BuildContext context) {
    final stream = FirebaseFirestore.instance.collection('users').snapshots();
    final size = MediaQuery.of(context).size;
    final dialogWidth = size.width < 500 ? size.width - 24 : 460.0;
    final dialogHeight = size.height < 700 ? size.height - 44 : 610.0;

    return Dialog(
      insetPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 22),
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
      backgroundColor: Colors.white,
      child: SizedBox(
        width: dialogWidth,
        height: dialogHeight,
        child: Column(
          children: [
            // 1. Header
            Padding(
              padding: const EdgeInsets.fromLTRB(16, 16, 16, 8),
              child: Row(
                children: [
                  IconButton(
                    icon: const Icon(Icons.close_rounded, color: Color(0xFF54656F)),
                    onPressed: () => Navigator.pop(context),
                  ),
                  const SizedBox(width: 12),
                  const Expanded(
                    child: Text('Forward message to', style: TextStyle(fontSize: 18, color: Color(0xFF111B21), fontWeight: FontWeight.w500)),
                  ),
                  IconButton(
                    icon: const Icon(Icons.person_add_alt_1_outlined, color: Color(0xFF54656F)),
                    onPressed: () {},
                  ),
                ],
              ),
            ),

            // 2. Search Bar
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 8),
              child: TextField(
                onChanged: (val) => setState(() => _searchQuery = val.toLowerCase()),
                decoration: InputDecoration(
                  hintText: 'Search name, number or @username',
                  hintStyle: const TextStyle(color: Color(0xFF8696A0), fontSize: 14),
                  prefixIcon: const Icon(Icons.search_rounded, color: Color(0xFF8696A0), size: 20),
                  contentPadding: const EdgeInsets.symmetric(vertical: 0),
                  border: OutlineInputBorder(borderRadius: BorderRadius.circular(24), borderSide: const BorderSide(color: Color(0xFF026930), width: 1.5)),
                  enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(24), borderSide: const BorderSide(color: Color(0xFF026930), width: 1.5)),
                  focusedBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(24), borderSide: const BorderSide(color: Color(0xFF026930), width: 2)),
                ),
              ),
            ),

            // 3. User List
            Expanded(
              child: StreamBuilder<QuerySnapshot>(
                stream: stream,
                builder: (context, snapshot) {
                  if (!snapshot.hasData) return const Center(child: CircularProgressIndicator(color: Color(0xFF026930)));
                  
                  final users = snapshot.data!.docs.where((doc) {
                    final data = doc.data() as Map<String, dynamic>;
                    final name = (data['name'] ?? '').toString().toLowerCase();
                    return _searchQuery.isEmpty || name.contains(_searchQuery);
                  }).toList();

                  return ListView.builder(
                    physics: const BouncingScrollPhysics(),
                    itemCount: users.length + 2, // +2 for Status and Header
                    itemBuilder: (context, index) {
                      
                      // 🌟 MY STATUS ROW
                      if (index == 0) {
                        if (_searchQuery.isNotEmpty) return const SizedBox.shrink();
                        return Padding(
                          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                          child: Row(
                            children: [
                              Checkbox(
                                value: false,
                                onChanged: (v) {},
                                activeColor: const Color(0xFF026930),
                                shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(4)),
                              ),
                              const SizedBox(width: 8),
                              Container(
                                width: 44, height: 44,
                                decoration: const BoxDecoration(color: Color(0xFFCC7504), shape: BoxShape.circle),
                                child: const Icon(Icons.blur_circular_rounded, color: Colors.white),
                              ),
                              const SizedBox(width: 16),
                              Expanded(
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: const [
                                    Text('My status', style: TextStyle(fontSize: 16, color: Color(0xFF111B21))),
                                    SizedBox(height: 2),
                                    Text('8 contacts excluded', style: TextStyle(fontSize: 13, color: Color(0xFF54656F))),
                                  ],
                                ),
                              ),
                              const Icon(Icons.more_horiz_rounded, color: Color(0xFF54656F)),
                            ],
                          ),
                        );
                      }

                      // 🌟 RECENT CHATS HEADER
                      if (index == 1) {
                        if (_searchQuery.isNotEmpty) return const SizedBox.shrink();
                        return const Padding(
                          padding: EdgeInsets.fromLTRB(28, 16, 24, 8),
                          child: Text('Recent chats', style: TextStyle(color: Color(0xFF54656F), fontSize: 13, fontWeight: FontWeight.bold)),
                        );
                      }

                      // 🌟 CONTACT ROWS
                      final data = users[index - 2].data() as Map<String, dynamic>;
                      final email = data['email'] ?? '';
                      final name = data['name'] ?? 'User';
                      final isSelected = _selectedEmails.contains(email);

                      return InkWell(
                        onTap: () {
                          setState(() {
                            if (isSelected) _selectedEmails.remove(email);
                            else _selectedEmails.add(email);
                          });
                        },
                        child: Padding(
                          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                          child: Row(
                            children: [
                              Checkbox(
                                value: isSelected,
                                onChanged: (v) {
                                  setState(() {
                                    if (v == true) _selectedEmails.add(email);
                                    else _selectedEmails.remove(email);
                                  });
                                },
                                activeColor: const Color(0xFF026930),
                                shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(4)),
                              ),
                              const SizedBox(width: 8),
                              CircleAvatar(
                                radius: 22,
                                backgroundColor: Colors.grey.shade200,
                                backgroundImage: _getAvatarProvider(data['profile_picture']),
                                child: _getAvatarProvider(data['profile_picture']) == null ? const Icon(Icons.person, color: Colors.grey) : null,
                              ),
                              const SizedBox(width: 16),
                              Expanded(
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text(name, style: const TextStyle(fontSize: 16, color: Color(0xFF111B21))),
                                    const SizedBox(height: 2),
                                    Text(data['role'] ?? 'User', style: const TextStyle(fontSize: 13, color: Color(0xFF54656F))),
                                  ],
                                ),
                              ),
                            ],
                          ),
                        ),
                      );
                    },
                  );
                }
              ),
            ),

            // 4. Bottom Action Bar (Appears when items are selected)
            AnimatedContainer(
              duration: const Duration(milliseconds: 200),
              height: _selectedEmails.isNotEmpty ? 68 : 0,
              color: const Color(0xFFF0F2F5),
              padding: const EdgeInsets.symmetric(horizontal: 24),
              child: _selectedEmails.isNotEmpty
                ? Row(
                    children: [
                      IconButton(
                        icon: const Icon(Icons.close_rounded, color: Color(0xFF54656F)),
                        onPressed: () => setState(() => _selectedEmails.clear()),
                      ),
                      const SizedBox(width: 8),
                      Text('${_selectedEmails.length} selected', style: const TextStyle(color: Color(0xFF54656F), fontSize: 14)),
                      const Spacer(),
                      FloatingActionButton(
                        onPressed: () {
                          Navigator.pop(context);
                          ScaffoldMessenger.of(context).showSnackBar(
                            SnackBar(content: Text('Message forwarded to ${_selectedEmails.length} contacts.'), backgroundColor: const Color(0xFF026930)),
                          );
                        },
                        backgroundColor: const Color(0xFF026930),
                        elevation: 2,
                        child: const Icon(Icons.send_rounded, color: Colors.white),
                      )
                    ],
                  )
                : const SizedBox.shrink(),
            )
          ],
        ),
      ),
    );
  }
}