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

import 'dart:async';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:open_filex/open_filex.dart';
import 'package:path_provider/path_provider.dart';
import 'package:share_plus/share_plus.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../../../core/networks/api_client.dart';
import '../../../../core/services/connect_social_service.dart';
import '../../../../core/services/database_service.dart';
import 'channels_comments_sheet.dart';
import 'channels_utils.dart';
import 'hover_scale_button.dart';

class ChannelsPanel extends StatefulWidget {
  final VoidCallback? onBack;
  final Function(String email, String name, String? pic)? onStartChat;

  const ChannelsPanel({super.key, this.onBack, this.onStartChat});

  @override
  State<ChannelsPanel> createState() => _ChannelsPanelState();
}

class _ChannelsPanelState extends State<ChannelsPanel> {
  final _scrollController = ScrollController();
  final _searchController = TextEditingController();
  final ImagePicker _picker = ImagePicker();

  List<Map<String, dynamic>> _posts = [];
  List<dynamic> _allUsers = [];
  Set<int> _savedPostIds = <int>{};
  final Set<int> _processingLikes = <int>{};

  String _currentUserEmail = '';
  String _currentUserName = 'Rockview User';
  String? _currentUserPic;
  bool _loading = true;
  bool _refreshing = false;
  String? _error;
  Timer? _refreshTimer;

  bool _showNotifications = false;
  bool _notificationsLoading = false;
  String? _notificationsError;
  int _unreadNotifications = 0;
  List<Map<String, dynamic>> _notifications = <Map<String, dynamic>>[];

  @override
  void initState() {
    super.initState();
    _initialize();
    _refreshTimer = Timer.periodic(const Duration(seconds: 20), (_) async {
      await _loadPosts(silent: true);
      await _loadNotificationCount();
    });
  }

  @override
  void dispose() {
    _refreshTimer?.cancel();
    _scrollController.dispose();
    _searchController.dispose();
    super.dispose();
  }

  Future<void> _initialize() async {
    await Future.wait<void>([
      _loadCurrentUser(),
      _loadSavedPosts(),
      _loadUsers(),
    ]);
    await Future.wait<void>([
      _loadPosts(),
      _loadNotificationCount(),
    ]);
  }

  Future<void> _loadCurrentUser() async {
    final user = await DatabaseService.getLocalUser();
    if (!mounted || user == null) return;
    setState(() {
      _currentUserEmail = user.email.toLowerCase().trim();
      _currentUserName = user.fullName.trim().isEmpty ? user.email : user.fullName.trim();
      _currentUserPic = user.profilePicture;
    });
  }

  Future<void> _loadUsers() async {
    try {
      final results = await Future.wait([
        ApiClient.getAdmins(),
        ApiClient.getStaff(),
      ]);
      final seen = <String>{};
      final users = <dynamic>[];
      for (final list in results) {
        for (final user in list) {
          final email = (user['email'] ?? '').toString().trim().toLowerCase();
          if (email.isEmpty || !seen.add(email)) continue;
          users.add(user);
        }
      }
      if (mounted) setState(() => _allUsers = users);
    } catch (_) {
      // The feed itself must continue working even if contact sync is unavailable.
    }
  }

  Future<void> _loadSavedPosts() async {
    final prefs = await SharedPreferences.getInstance();
    final values = prefs.getStringList('rockview_connect_saved_posts') ?? const <String>[];
    if (!mounted) return;
    setState(() {
      _savedPostIds = values.map(int.tryParse).whereType<int>().toSet();
    });
  }

  Future<void> _toggleSavePost(int postId) async {
    setState(() {
      if (!_savedPostIds.add(postId)) _savedPostIds.remove(postId);
    });
    final prefs = await SharedPreferences.getInstance();
    await prefs.setStringList(
      'rockview_connect_saved_posts',
      _savedPostIds.map((id) => '$id').toList(),
    );
  }

  Future<void> _loadPosts({bool silent = false}) async {
    if (!mounted) return;
    if (!silent) {
      setState(() {
        _loading = true;
        _error = null;
      });
    } else if (_refreshing) {
      return;
    }

    _refreshing = true;
    try {
      final posts = await ConnectSocialService.getPosts(
        limit: 40,
        search: _searchController.text.trim(),
      );
      if (!mounted) return;
      setState(() {
        _posts = posts;
        _loading = false;
        _error = null;
      });
    } catch (e) {
      if (!mounted) return;
      if (!silent) {
        setState(() {
          _loading = false;
          _error = _cleanError(e);
        });
      }
    } finally {
      _refreshing = false;
    }
  }

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

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

  bool _bool(dynamic value) {
    if (value is bool) return value;
    final text = '${value ?? ''}'.toLowerCase();
    return text == 'true' || text == '1' || text == 't';
  }

  String _formatTime(dynamic raw) {
    final value = raw?.toString().trim() ?? '';
    if (value.isEmpty) return 'Just now';
    final date = DateTime.tryParse(value)?.toLocal();
    if (date == null) return 'Recently';
    final now = DateTime.now();
    final diff = now.difference(date);
    if (diff.inMinutes < 1) return 'Just now';
    if (diff.inMinutes < 60) 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}';
  }

  Future<void> _loadNotificationCount() async {
    try {
      final count = await ConnectSocialService.getUnreadNotificationCount();
      if (!mounted) return;
      setState(() => _unreadNotifications = count);
    } catch (_) {
      // Social notifications must not block the feed when the backend is briefly unavailable.
    }
  }

  Future<void> _openNotifications() async {
    if (!mounted) return;
    setState(() {
      _showNotifications = true;
      _notificationsLoading = true;
      _notificationsError = null;
    });

    try {
      final items = await ConnectSocialService.getNotifications(limit: 80);
      if (!mounted) return;
      setState(() {
        _notifications = items;
        _notificationsLoading = false;
        _unreadNotifications = 0;
      });
      try {
        await ConnectSocialService.markAllNotificationsRead();
      } catch (_) {}
    } catch (e) {
      if (!mounted) return;
      setState(() {
        _notificationsLoading = false;
        _notificationsError = _cleanError(e);
      });
    }
  }

  void _closeNotifications() {
    setState(() => _showNotifications = false);
    _loadNotificationCount();
  }

  Future<void> _openNotificationTarget(Map<String, dynamic> notification) async {
    final id = _int(notification['id']);
    if (id > 0) {
      try {
        await ConnectSocialService.markNotificationRead(id);
      } catch (_) {}
    }
    final postId = _int(notification['post_id']);
    setState(() => _showNotifications = false);
    if (postId <= 0) return;
    Map<String, dynamic>? target;
    for (final post in _posts) {
      if (_int(post['id']) == postId) {
        target = post;
        break;
      }
    }
    if (target != null && mounted) {
      final type = (notification['type'] ?? '').toString();
      if (type == 'comment' || type == 'reply') {
        _openComments(target);
      } else {
        if (_scrollController.hasClients) {
          _scrollController.animateTo(0, duration: const Duration(milliseconds: 250), curve: Curves.easeOut);
        }
      }
    } else {
      await _loadPosts();
    }
  }

  Future<void> _toggleLike(Map<String, dynamic> post) async {
    final postId = _int(post['id']);
    if (postId <= 0 || _processingLikes.contains(postId)) return;

    final previousLiked = _bool(post['liked_by_me']);
    final previousCount = _int(post['likes_count']);
    setState(() {
      _processingLikes.add(postId);
      post['liked_by_me'] = !previousLiked;
      post['likes_count'] = previousLiked
          ? (previousCount > 0 ? previousCount - 1 : 0)
          : previousCount + 1;
    });

    try {
      final result = await ConnectSocialService.toggleLike(postId);
      if (!mounted) return;
      setState(() {
        post['liked_by_me'] = _bool(result['liked']);
        post['likes_count'] = _int(result['likes_count']);
      });

      // The PHP like endpoint creates/removes the recipient notification.
      await _loadNotificationCount();
    } catch (e) {
      if (!mounted) return;
      setState(() {
        post['liked_by_me'] = previousLiked;
        post['likes_count'] = previousCount;
      });
      _snack(_cleanError(e), error: true);
    } finally {
      if (mounted) setState(() => _processingLikes.remove(postId));
    }
  }

  void _openComments(Map<String, dynamic> post) {
    final postId = _int(post['id']);
    if (postId <= 0) return;
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      useSafeArea: true,
      backgroundColor: Colors.transparent,
      builder: (_) => FirebaseCommentsSheet(
        postId: postId,
        currentUserName: _currentUserName,
        currentUserEmail: _currentUserEmail,
        currentUserPic: _currentUserPic,
        postAuthorEmail: post['author_email']?.toString(),
        registeredUsers: _allUsers,
        onCommentAdded: () {
          if (!mounted) return;
          setState(() => post['comments_count'] = _int(post['comments_count']) + 1);
        },
      ),
    );
  }

  Future<void> _sharePost(Map<String, dynamic> post) async {
    final text = (post['content'] ?? '').toString().trim();
    final author = (post['author_name'] ?? 'Rockview User').toString();
    final media = (post['media'] as List?)?.whereType<Map>().toList() ?? const <Map>[];
    final mediaLine = media.isNotEmpty ? '\n${(media.first['url'] ?? ConnectSocialService.mediaUrl(media.first['file_path']?.toString())).toString()}' : '';
    await Share.share('Rockview Connect — $author\n\n$text$mediaLine');
  }

  void _snack(String message, {bool error = false}) {
    if (!mounted) return;
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: error ? Colors.red.shade700 : const Color(0xFF118A5E),
        behavior: SnackBarBehavior.floating,
      ),
    );
  }

  Future<void> _openCreatePost() async {
    final created = await showDialog<bool>(
      context: context,
      barrierDismissible: false,
      builder: (_) => _CreatePostDialog(
        currentUserName: _currentUserName,
        currentUserPic: _currentUserPic,
        users: _allUsers,
        picker: _picker,
      ),
    );
    if (created == true) {
      await _loadPosts();
      if (_scrollController.hasClients) {
        _scrollController.animateTo(0, duration: const Duration(milliseconds: 280), curve: Curves.easeOut);
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        final compact = constraints.maxWidth < 620;
        return Scaffold(
          backgroundColor: const Color(0xFFF0F2F5),
          body: Column(
            children: [
              _buildHeader(compact),
              Expanded(
                child: _showNotifications
                    ? _buildNotificationsView(compact)
                    : RefreshIndicator(
                        color: FbFeedColors.blue,
                        onRefresh: () async {
                          await _loadPosts();
                          await _loadNotificationCount();
                        },
                        child: _buildBody(compact),
                      ),
              ),
            ],
          ),
          floatingActionButton: compact && !_showNotifications
              ? FloatingActionButton(
                  onPressed: _openCreatePost,
                  backgroundColor: FbFeedColors.blue,
                  foregroundColor: Colors.white,
                  child: const Icon(Icons.add_rounded),
                )
              : null,
        );
      },
    );
  }

  Widget _buildHeader(bool compact) {
    return SafeArea(
      bottom: false,
      child: Container(
        height: 68,
        padding: EdgeInsets.symmetric(horizontal: compact ? 8 : 18),
        decoration: BoxDecoration(
          color: Colors.white,
          border: Border(bottom: BorderSide(color: Colors.grey.shade200)),
        ),
        child: Row(
          children: [
            if (_showNotifications)
              IconButton(
                onPressed: _closeNotifications,
                icon: const Icon(Icons.arrow_back_rounded),
                tooltip: 'Back to posts',
              )
            else if (widget.onBack != null)
              IconButton(onPressed: widget.onBack, icon: const Icon(Icons.arrow_back_rounded)),
            Container(
              width: 40,
              height: 40,
              decoration: BoxDecoration(
                color: FbFeedColors.blue.withOpacity(.10),
                borderRadius: BorderRadius.circular(12),
              ),
              child: Icon(
                _showNotifications ? Icons.notifications_rounded : Icons.dynamic_feed_rounded,
                color: FbFeedColors.blue,
              ),
            ),
            const SizedBox(width: 10),
            Expanded(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    _showNotifications ? 'Notifications' : 'Rockview Connect',
                    style: const TextStyle(fontWeight: FontWeight.w800, fontSize: 18, color: FbFeedColors.textMain),
                  ),
                  Text(
                    _showNotifications
                        ? 'Likes, comments, replies and community activity'
                        : 'Campus posts, pictures and videos',
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: const TextStyle(fontSize: 11, color: FbFeedColors.textSecondary),
                  ),
                ],
              ),
            ),
            if (!_showNotifications && !compact)
              FilledButton.icon(
                onPressed: _openCreatePost,
                icon: const Icon(Icons.edit_rounded, size: 18),
                label: const Text('Create post'),
                style: FilledButton.styleFrom(backgroundColor: FbFeedColors.blue),
              ),
            const SizedBox(width: 2),
            _notificationButton(),
            IconButton(
              onPressed: _showNotifications ? _openNotifications : () => _loadPosts(),
              icon: const Icon(Icons.refresh_rounded),
              tooltip: 'Refresh',
            ),
          ],
        ),
      ),
    );
  }

  Widget _notificationButton() {
    return Tooltip(
      message: 'Notifications',
      child: InkWell(
        onTap: _openNotifications,
        borderRadius: BorderRadius.circular(22),
        child: Padding(
          padding: const EdgeInsets.all(8),
          child: Stack(
            clipBehavior: Clip.none,
            children: [
              Icon(
                _showNotifications ? Icons.notifications_rounded : Icons.notifications_none_rounded,
                color: _showNotifications ? FbFeedColors.blue : FbFeedColors.textSecondary,
                size: 24,
              ),
              if (_unreadNotifications > 0)
                Positioned(
                  right: -9,
                  top: -8,
                  child: Container(
                    constraints: const BoxConstraints(minWidth: 18, minHeight: 18),
                    padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 2),
                    decoration: const ShapeDecoration(color: Color(0xFFD93025), shape: StadiumBorder()),
                    alignment: Alignment.center,
                    child: Text(
                      _unreadNotifications > 99 ? '99+' : '$_unreadNotifications',
                      style: const TextStyle(color: Colors.white, fontSize: 9, fontWeight: FontWeight.w900),
                    ),
                  ),
                ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildNotificationsView(bool compact) {
    if (_notificationsLoading) {
      return const Center(child: CircularProgressIndicator(color: FbFeedColors.blue));
    }
    if (_notificationsError != null) {
      return Center(
        child: Padding(
          padding: const EdgeInsets.all(28),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              const Icon(Icons.notifications_off_outlined, size: 52, color: FbFeedColors.textSecondary),
              const SizedBox(height: 12),
              const Text('Notifications could not be loaded', style: TextStyle(fontSize: 17, fontWeight: FontWeight.w800)),
              const SizedBox(height: 6),
              Text(_notificationsError!, textAlign: TextAlign.center, style: const TextStyle(color: FbFeedColors.textSecondary)),
              const SizedBox(height: 14),
              FilledButton.icon(onPressed: _openNotifications, icon: const Icon(Icons.refresh_rounded), label: const Text('Try again')),
            ],
          ),
        ),
      );
    }

    if (_notifications.isEmpty) {
      return const Center(
        child: Padding(
          padding: EdgeInsets.all(28),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Icon(Icons.notifications_none_rounded, size: 58, color: Color(0xFF9AA0A6)),
              SizedBox(height: 12),
              Text('You are all caught up', style: TextStyle(fontSize: 18, fontWeight: FontWeight.w800)),
              SizedBox(height: 6),
              Text('New likes, comments, replies and community activity will appear here.', textAlign: TextAlign.center, style: TextStyle(color: FbFeedColors.textSecondary, height: 1.4)),
            ],
          ),
        ),
      );
    }

    return RefreshIndicator(
      color: FbFeedColors.blue,
      onRefresh: _openNotifications,
      child: ListView.separated(
        physics: const AlwaysScrollableScrollPhysics(parent: BouncingScrollPhysics()),
        padding: EdgeInsets.fromLTRB(compact ? 8 : 18, 14, compact ? 8 : 18, 28),
        itemCount: _notifications.length,
        separatorBuilder: (_, __) => const SizedBox(height: 8),
        itemBuilder: (_, index) {
          final notification = _notifications[index];
          final unread = !_bool(notification['is_read']);
          final type = (notification['type'] ?? '').toString();
          final actor = (notification['actor_name'] ?? 'Rockview user').toString();
          IconData icon = Icons.notifications_rounded;
          Color accent = FbFeedColors.blue;
          if (type == 'like') {
            icon = Icons.thumb_up_rounded;
            accent = const Color(0xFF1877F2);
          } else if (type == 'comment' || type == 'reply') {
            icon = Icons.chat_bubble_rounded;
            accent = const Color(0xFF118A5E);
          } else if (type == 'community_join') {
            icon = Icons.groups_rounded;
            accent = const Color(0xFFCC7504);
          }
          return Material(
            color: unread ? const Color(0xFFEAF4EF) : Colors.white,
            borderRadius: BorderRadius.circular(14),
            child: InkWell(
              borderRadius: BorderRadius.circular(14),
              onTap: () => _openNotificationTarget(notification),
              child: Container(
                constraints: const BoxConstraints(maxWidth: 760),
                padding: const EdgeInsets.all(13),
                decoration: BoxDecoration(
                  border: Border.all(color: unread ? FbFeedColors.blue.withOpacity(.20) : Colors.grey.shade200),
                  borderRadius: BorderRadius.circular(14),
                ),
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Container(
                      width: 42,
                      height: 42,
                      decoration: BoxDecoration(color: accent.withOpacity(.10), shape: BoxShape.circle),
                      child: Icon(icon, color: accent, size: 21),
                    ),
                    const SizedBox(width: 11),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            (notification['title'] ?? 'Notification').toString(),
                            style: TextStyle(fontWeight: unread ? FontWeight.w900 : FontWeight.w700, fontSize: 14, color: FbFeedColors.textMain),
                          ),
                          const SizedBox(height: 3),
                          Text(
                            (notification['body'] ?? actor).toString(),
                            style: const TextStyle(fontSize: 12.5, height: 1.35, color: FbFeedColors.textSecondary),
                          ),
                          const SizedBox(height: 5),
                          Text(_formatTime(notification['created_at']), style: TextStyle(fontSize: 11, color: unread ? FbFeedColors.blue : FbFeedColors.textSecondary, fontWeight: FontWeight.w700)),
                        ],
                      ),
                    ),
                    if (unread) const Padding(padding: EdgeInsets.only(top: 4), child: CircleAvatar(radius: 4, backgroundColor: Color(0xFF118A5E))),
                  ],
                ),
              ),
            ),
          );
        },
      ),
    );
  }

  Widget _buildBody(bool compact) {
    if (_loading) {
      return ListView(
        physics: const AlwaysScrollableScrollPhysics(),
        children: const [SizedBox(height: 180), Center(child: CircularProgressIndicator(color: FbFeedColors.blue))],
      );
    }
    if (_error != null) {
      return ListView(
        physics: const AlwaysScrollableScrollPhysics(),
        padding: const EdgeInsets.all(24),
        children: [
          const SizedBox(height: 80),
          Icon(Icons.cloud_off_rounded, size: 56, color: Colors.grey.shade400),
          const SizedBox(height: 14),
          const Text('Posts could not be loaded', textAlign: TextAlign.center, style: TextStyle(fontWeight: FontWeight.w800, fontSize: 18)),
          const SizedBox(height: 6),
          Text(_error!, textAlign: TextAlign.center, style: const TextStyle(color: FbFeedColors.textSecondary)),
          const SizedBox(height: 18),
          Center(child: FilledButton.icon(onPressed: () => _loadPosts(), icon: const Icon(Icons.refresh_rounded), label: const Text('Try again'))),
        ],
      );
    }

    final query = _searchController.text.trim().toLowerCase();
    final visible = query.isEmpty
        ? _posts
        : _posts.where((post) {
            final haystack = '${post['author_name']} ${post['content']} ${post['location']}'.toLowerCase();
            return haystack.contains(query);
          }).toList();

    return ListView(
      controller: _scrollController,
      physics: const AlwaysScrollableScrollPhysics(parent: BouncingScrollPhysics()),
      padding: EdgeInsets.fromLTRB(compact ? 0 : 14, 14, compact ? 0 : 14, 100),
      children: [
        Center(
          child: ConstrainedBox(
            constraints: const BoxConstraints(maxWidth: 720),
            child: Column(
              children: [
                _composerCard(),
                const SizedBox(height: 12),
                _searchBar(),
                const SizedBox(height: 12),
                if (visible.isEmpty) _emptyFeed() else ...visible.map(_buildPostCard),
              ],
            ),
          ),
        ),
      ],
    );
  }

  Widget _composerCard() {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 10),
      padding: const EdgeInsets.all(14),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(14),
        boxShadow: [BoxShadow(color: Colors.black.withOpacity(.04), blurRadius: 12)],
      ),
      child: Column(
        children: [
          Row(
            children: [
              buildSmartFbAvatar(_currentUserPic, _currentUserName, radius: 20),
              const SizedBox(width: 10),
              Expanded(
                child: InkWell(
                  borderRadius: BorderRadius.circular(24),
                  onTap: _openCreatePost,
                  child: Container(
                    height: 44,
                    padding: const EdgeInsets.symmetric(horizontal: 16),
                    alignment: Alignment.centerLeft,
                    decoration: BoxDecoration(color: FbFeedColors.bg, borderRadius: BorderRadius.circular(24)),
                    child: Text("What's on your mind, ${_currentUserName.split(' ').first}?", maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle(color: FbFeedColors.textSecondary)),
                  ),
                ),
              ),
            ],
          ),
          const SizedBox(height: 10),
          const Divider(height: 1),
          const SizedBox(height: 6),
          Row(
            children: [
              Expanded(child: _quickPostAction(Icons.photo_library_rounded, const Color(0xFF45BD62), 'Photo', _openCreatePost)),
              Expanded(child: _quickPostAction(Icons.video_library_rounded, Colors.redAccent, 'Video', _openCreatePost)),
              Expanded(child: _quickPostAction(Icons.people_alt_rounded, const Color(0xFF1877F2), 'Tag', _openCreatePost)),
            ],
          ),
        ],
      ),
    );
  }

  Widget _quickPostAction(IconData icon, Color color, String label, VoidCallback onTap) {
    return InkWell(
      onTap: onTap,
      borderRadius: BorderRadius.circular(9),
      child: Padding(
        padding: const EdgeInsets.symmetric(vertical: 9),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [Icon(icon, color: color, size: 20), const SizedBox(width: 6), Flexible(child: Text(label, overflow: TextOverflow.ellipsis, style: const TextStyle(fontWeight: FontWeight.w600, color: FbFeedColors.textSecondary)))],
        ),
      ),
    );
  }

  Widget _searchBar() {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 10),
      child: TextField(
        controller: _searchController,
        onChanged: (_) => setState(() {}),
        onSubmitted: (_) => _loadPosts(),
        decoration: InputDecoration(
          hintText: 'Search posts...',
          prefixIcon: const Icon(Icons.search_rounded),
          suffixIcon: _searchController.text.isEmpty
              ? null
              : IconButton(onPressed: () { _searchController.clear(); setState(() {}); _loadPosts(); }, icon: const Icon(Icons.close_rounded)),
          filled: true,
          fillColor: Colors.white,
          contentPadding: const EdgeInsets.symmetric(vertical: 10),
          border: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: BorderSide.none),
        ),
      ),
    );
  }

  Widget _emptyFeed() {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 10),
      padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 50),
      decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(14)),
      child: Column(
        children: [
          Icon(Icons.dynamic_feed_outlined, size: 54, color: Colors.grey.shade400),
          const SizedBox(height: 14),
          const Text('No posts yet', style: TextStyle(fontWeight: FontWeight.w800, fontSize: 18)),
          const SizedBox(height: 6),
          const Text('Start the conversation by sharing an update, picture or video.', textAlign: TextAlign.center, style: TextStyle(color: FbFeedColors.textSecondary)),
          const SizedBox(height: 18),
          FilledButton.icon(onPressed: _openCreatePost, icon: const Icon(Icons.add_rounded), label: const Text('Create first post')),
        ],
      ),
    );
  }

  Widget _buildPostCard(Map<String, dynamic> post) {
    final postId = _int(post['id']);
    final author = (post['author_name'] ?? 'Rockview User').toString();
    final authorPic = post['author_profile_picture']?.toString();
    final content = (post['content'] ?? '').toString();
    final location = (post['location'] ?? '').toString().trim();
    final campus = (post['campus'] ?? '').toString().trim();
    final tagged = (post['tagged_name'] ?? '').toString().trim();
    final media = (post['media'] as List?)?.whereType<Map>().toList() ?? const <Map>[];
    final liked = _bool(post['liked_by_me']);
    final likeCount = _int(post['likes_count']);
    final commentCount = _int(post['comments_count']);
    final isSaved = _savedPostIds.contains(postId);
    final isLiking = _processingLikes.contains(postId);

    return Container(
      margin: const EdgeInsets.fromLTRB(10, 0, 10, 12),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(14),
        boxShadow: [BoxShadow(color: Colors.black.withOpacity(.04), blurRadius: 12)],
      ),
      clipBehavior: Clip.antiAlias,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: const EdgeInsets.fromLTRB(14, 12, 8, 8),
            child: Row(
              children: [
                buildSmartFbAvatar(authorPic, author, radius: 20),
                const SizedBox(width: 10),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(author, maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle(fontWeight: FontWeight.w700, fontSize: 15)),
                      Row(
                        children: [
                          Flexible(child: Text(_formatTime(post['created_at']), style: const TextStyle(fontSize: 12, color: FbFeedColors.textSecondary))),
                          if (campus.isNotEmpty) ...[
                            const Text('  •  ', style: TextStyle(color: FbFeedColors.textSecondary)),
                            Flexible(child: Text(campus, overflow: TextOverflow.ellipsis, style: const TextStyle(fontSize: 12, color: FbFeedColors.textSecondary))),
                          ],
                          const SizedBox(width: 4),
                          const Icon(Icons.public_rounded, size: 12, color: FbFeedColors.textSecondary),
                        ],
                      ),
                    ],
                  ),
                ),
                IconButton(onPressed: () => _toggleSavePost(postId), icon: Icon(isSaved ? Icons.bookmark_rounded : Icons.bookmark_border_rounded, color: isSaved ? FbFeedColors.blue : FbFeedColors.textSecondary), tooltip: 'Save post'),
              ],
            ),
          ),
          if (tagged.isNotEmpty || location.isNotEmpty)
            Padding(
              padding: const EdgeInsets.fromLTRB(14, 0, 14, 7),
              child: Wrap(
                spacing: 8,
                runSpacing: 5,
                children: [
                  if (tagged.isNotEmpty) _metaChip(Icons.person_rounded, 'with $tagged'),
                  if (location.isNotEmpty) _metaChip(Icons.location_on_rounded, location),
                ],
              ),
            ),
          if (content.isNotEmpty)
            Padding(
              padding: const EdgeInsets.fromLTRB(14, 4, 14, 12),
              child: Text(content, style: const TextStyle(fontSize: 15, height: 1.42, color: FbFeedColors.textMain)),
            ),
          if (media.isNotEmpty) _PostMediaGrid(media: media),
          Padding(
            padding: const EdgeInsets.fromLTRB(14, 10, 14, 8),
            child: Row(
              children: [
                if (likeCount > 0) ...[
                  Container(padding: const EdgeInsets.all(4), decoration: const BoxDecoration(color: Color(0xFF1877F2), shape: BoxShape.circle), child: const Icon(Icons.thumb_up_rounded, color: Colors.white, size: 11)),
                  const SizedBox(width: 6),
                  Text('$likeCount', style: const TextStyle(color: FbFeedColors.textSecondary, fontSize: 13)),
                ],
                const Spacer(),
                if (commentCount > 0) Text('$commentCount comment${commentCount == 1 ? '' : 's'}', style: const TextStyle(color: FbFeedColors.textSecondary, fontSize: 13)),
              ],
            ),
          ),
          const Divider(height: 1),
          Row(
            children: [
              Expanded(
                child: _postAction(
                  icon: liked ? Icons.thumb_up_rounded : Icons.thumb_up_alt_outlined,
                  label: 'Like',
                  active: liked,
                  busy: isLiking,
                  onTap: () => _toggleLike(post),
                ),
              ),
              Expanded(child: _postAction(icon: Icons.mode_comment_outlined, label: 'Comment', onTap: () => _openComments(post))),
              Expanded(child: _postAction(icon: Icons.share_outlined, label: 'Share', onTap: () => _sharePost(post))),
            ],
          ),
        ],
      ),
    );
  }

  Widget _metaChip(IconData icon, String text) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 9, vertical: 5),
      decoration: BoxDecoration(color: FbFeedColors.bg, borderRadius: BorderRadius.circular(20)),
      child: Row(mainAxisSize: MainAxisSize.min, children: [Icon(icon, size: 14, color: FbFeedColors.blue), const SizedBox(width: 4), Text(text, style: const TextStyle(fontSize: 12, color: FbFeedColors.textSecondary))]),
    );
  }

  Widget _postAction({required IconData icon, required String label, required VoidCallback onTap, bool active = false, bool busy = false}) {
    return HoverScaleButton(
      onTap: busy ? () {} : onTap,
      padding: const EdgeInsets.symmetric(vertical: 11, horizontal: 5),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          if (busy)
            const SizedBox(width: 18, height: 18, child: CircularProgressIndicator(strokeWidth: 2, color: FbFeedColors.blue))
          else
            Icon(icon, size: 20, color: active ? FbFeedColors.blue : FbFeedColors.textSecondary),
          const SizedBox(width: 6),
          Flexible(child: Text(label, maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(fontWeight: FontWeight.w600, color: active ? FbFeedColors.blue : FbFeedColors.textSecondary))),
        ],
      ),
    );
  }
}

class _CreatePostDialog extends StatefulWidget {
  final String currentUserName;
  final String? currentUserPic;
  final List<dynamic> users;
  final ImagePicker picker;

  const _CreatePostDialog({required this.currentUserName, required this.currentUserPic, required this.users, required this.picker});

  @override
  State<_CreatePostDialog> createState() => _CreatePostDialogState();
}

class _CreatePostDialogState extends State<_CreatePostDialog> {
  final _textController = TextEditingController();
  final List<File> _images = [];
  File? _video;
  Map<String, dynamic>? _taggedUser;
  String? _location;
  bool _posting = false;

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

  Future<void> _addImage() async {
    if (_images.length >= 6) return;
    final picked = await widget.picker.pickImage(source: ImageSource.gallery, imageQuality: 82);
    if (picked == null) return;
    setState(() {
      _video = null;
      _images.add(File(picked.path));
    });
  }

  Future<void> _pickVideo() async {
    try {
      final PlatformFile? picked = await FilePicker.pickFile(type: FileType.video);
      final path = picked?.path?.trim() ?? '';
      if (path.isEmpty) return;
      final file = File(path);
      if (!await file.exists()) {
        throw Exception('The selected video could not be read.');
      }
      final length = await file.length();
      if (length > 50 * 1024 * 1024) {
        throw Exception('Video must not exceed 50 MB.');
      }
      setState(() {
        _images.clear();
        _video = file;
      });
    } catch (e) {
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text(e.toString().replaceFirst(RegExp(r'^Exception:\s*'), '')), backgroundColor: Colors.redAccent),
      );
    }
  }

  Future<void> _pickTag() async {
    final result = await showModalBottomSheet<Map<String, dynamic>>(
      context: context,
      isScrollControlled: true,
      useSafeArea: true,
      builder: (_) => _UserPickerSheet(users: widget.users),
    );
    if (result != null) setState(() => _taggedUser = result);
  }

  Future<void> _pickLocation() async {
    const campuses = ['Ndola Campus', 'Lusaka Campus', 'Chipata Campus', '10 Miles Campus', 'Livingstone Campus', 'Kasama Campus'];
    final selected = await showModalBottomSheet<String>(
      context: context,
      builder: (_) => SafeArea(
        child: ListView(
          shrinkWrap: true,
          children: [
            const ListTile(title: Text('Add campus location', style: TextStyle(fontWeight: FontWeight.w800))),
            ...campuses.map((campus) => ListTile(leading: const Icon(Icons.location_on_rounded, color: Colors.redAccent), title: Text(campus), onTap: () => Navigator.pop(context, campus))),
          ],
        ),
      ),
    );
    if (selected != null) setState(() => _location = selected);
  }

  Future<void> _submit() async {
    if (_posting) return;
    setState(() => _posting = true);
    try {
      await ConnectSocialService.createPost(
        content: _textController.text,
        images: _images,
        video: _video,
        taggedName: _taggedUser == null ? null : (_taggedUser!['full_name'] ?? _taggedUser!['name'])?.toString(),
        location: _location,
      );
      if (!mounted) return;
      Navigator.pop(context, true);
    } catch (e) {
      if (!mounted) return;
      setState(() => _posting = false);
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(e.toString().replaceFirst(RegExp(r'^Exception:\s*'), '')), backgroundColor: Colors.red.shade700));
    }
  }

  @override
  Widget build(BuildContext context) {
    final screen = MediaQuery.sizeOf(context);
    return Dialog(
      insetPadding: EdgeInsets.symmetric(horizontal: screen.width < 560 ? 10 : 24, vertical: screen.height < 700 ? 10 : 32),
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(18)),
      child: ConstrainedBox(
        constraints: BoxConstraints(maxWidth: 560, maxHeight: screen.height * .92),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Padding(
              padding: const EdgeInsets.fromLTRB(16, 10, 8, 10),
              child: Row(
                children: [
                  const SizedBox(width: 40),
                  const Expanded(child: Text('Create post', textAlign: TextAlign.center, style: TextStyle(fontSize: 19, fontWeight: FontWeight.w800))),
                  IconButton(onPressed: _posting ? null : () => Navigator.pop(context), icon: const Icon(Icons.close_rounded)),
                ],
              ),
            ),
            const Divider(height: 1),
            Flexible(
              child: SingleChildScrollView(
                padding: const EdgeInsets.all(16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(children: [buildSmartFbAvatar(widget.currentUserPic, widget.currentUserName, radius: 20), const SizedBox(width: 10), Expanded(child: Text(widget.currentUserName, style: const TextStyle(fontWeight: FontWeight.w800, fontSize: 15))), const Icon(Icons.public_rounded, size: 16, color: FbFeedColors.textSecondary)]),
                    const SizedBox(height: 14),
                    TextField(
                      controller: _textController,
                      minLines: 3,
                      maxLines: 8,
                      autofocus: true,
                      decoration: const InputDecoration(hintText: "What's on your mind?", hintStyle: TextStyle(fontSize: 19, color: Color(0xFF8C939D)), border: InputBorder.none),
                      style: const TextStyle(fontSize: 18, height: 1.35),
                    ),
                    if (_taggedUser != null || _location != null)
                      Wrap(
                        spacing: 8,
                        runSpacing: 6,
                        children: [
                          if (_taggedUser != null) Chip(label: Text('with ${_taggedUser!['full_name'] ?? _taggedUser!['name']}'), avatar: const Icon(Icons.person_rounded, size: 16), onDeleted: () => setState(() => _taggedUser = null)),
                          if (_location != null) Chip(label: Text(_location!), avatar: const Icon(Icons.location_on_rounded, size: 16), onDeleted: () => setState(() => _location = null)),
                        ],
                      ),
                    if (_images.isNotEmpty) ...[
                      const SizedBox(height: 12),
                      _SelectedImageGrid(images: _images, onRemove: (index) => setState(() => _images.removeAt(index))),
                    ],
                    if (_video != null) ...[
                      const SizedBox(height: 12),
                      Container(
                        height: 180,
                        width: double.infinity,
                        decoration: BoxDecoration(color: const Color(0xFF111B21), borderRadius: BorderRadius.circular(12)),
                        child: Stack(
                          children: [
                            const Center(child: Column(mainAxisSize: MainAxisSize.min, children: [Icon(Icons.play_circle_fill_rounded, color: Colors.white, size: 56), SizedBox(height: 8), Text('Video selected', style: TextStyle(color: Colors.white, fontWeight: FontWeight.w700))])),
                            Positioned(top: 8, right: 8, child: CircleAvatar(backgroundColor: Colors.white, child: IconButton(onPressed: () => setState(() => _video = null), icon: const Icon(Icons.close_rounded, color: Colors.black)))),
                          ],
                        ),
                      ),
                    ],
                    const SizedBox(height: 14),
                    Container(
                      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                      decoration: BoxDecoration(border: Border.all(color: FbFeedColors.divider), borderRadius: BorderRadius.circular(12)),
                      child: Row(
                        children: [
                          const Expanded(child: Text('Add to your post', style: TextStyle(fontWeight: FontWeight.w700))),
                          IconButton(onPressed: _images.length < 6 ? _addImage : null, icon: const Icon(Icons.photo_library_rounded, color: Color(0xFF45BD62)), tooltip: 'Add picture'),
                          IconButton(onPressed: _pickVideo, icon: const Icon(Icons.video_library_rounded, color: Colors.redAccent), tooltip: 'Add video'),
                          IconButton(onPressed: _pickTag, icon: const Icon(Icons.person_add_alt_1_rounded, color: Color(0xFF1877F2)), tooltip: 'Tag person'),
                          IconButton(onPressed: _pickLocation, icon: const Icon(Icons.location_on_rounded, color: Color(0xFFF5533D)), tooltip: 'Add location'),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
            Padding(
              padding: const EdgeInsets.fromLTRB(16, 8, 16, 16),
              child: SizedBox(
                width: double.infinity,
                child: FilledButton(
                  onPressed: _posting ? null : _submit,
                  style: FilledButton.styleFrom(backgroundColor: FbFeedColors.blue, padding: const EdgeInsets.symmetric(vertical: 14)),
                  child: _posting
                      ? const SizedBox(width: 20, height: 20, child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white))
                      : const Text('POST', style: TextStyle(fontWeight: FontWeight.w800)),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class _UserPickerSheet extends StatefulWidget {
  final List<dynamic> users;
  const _UserPickerSheet({required this.users});

  @override
  State<_UserPickerSheet> createState() => _UserPickerSheetState();
}

class _UserPickerSheetState extends State<_UserPickerSheet> {
  String _query = '';
  @override
  Widget build(BuildContext context) {
    final items = widget.users.where((u) {
      final name = (u['full_name'] ?? u['name'] ?? '').toString().toLowerCase();
      return name.contains(_query.toLowerCase());
    }).toList();
    return FractionallySizedBox(
      heightFactor: .72,
      child: Column(
        children: [
          const ListTile(title: Text('Tag someone', style: TextStyle(fontWeight: FontWeight.w800, fontSize: 18))),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16),
            child: TextField(onChanged: (v) => setState(() => _query = v), decoration: InputDecoration(hintText: 'Search staff or administrator', prefixIcon: const Icon(Icons.search_rounded), filled: true, fillColor: FbFeedColors.bg, border: OutlineInputBorder(borderRadius: BorderRadius.circular(24), borderSide: BorderSide.none))),
          ),
          const SizedBox(height: 8),
          Expanded(
            child: ListView.builder(
              itemCount: items.length,
              itemBuilder: (_, index) {
                final user = items[index];
                final name = (user['full_name'] ?? user['name'] ?? 'User').toString();
                return ListTile(leading: buildSmartFbAvatar(user['profile_picture']?.toString(), name, radius: 18), title: Text(name, style: const TextStyle(fontWeight: FontWeight.w600)), subtitle: Text((user['role'] ?? '').toString()), onTap: () => Navigator.pop(context, Map<String, dynamic>.from(user)));
              },
            ),
          ),
        ],
      ),
    );
  }
}

class _SelectedImageGrid extends StatelessWidget {
  final List<File> images;
  final ValueChanged<int> onRemove;
  const _SelectedImageGrid({required this.images, required this.onRemove});

  @override
  Widget build(BuildContext context) {
    return GridView.builder(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      itemCount: images.length,
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: images.length == 1 ? 1 : 2, crossAxisSpacing: 6, mainAxisSpacing: 6, mainAxisExtent: images.length == 1 ? 220 : 150),
      itemBuilder: (_, index) => Stack(
        fit: StackFit.expand,
        children: [
          ClipRRect(borderRadius: BorderRadius.circular(10), child: Image.file(images[index], fit: BoxFit.cover)),
          Positioned(top: 6, right: 6, child: CircleAvatar(radius: 16, backgroundColor: Colors.white, child: IconButton(padding: EdgeInsets.zero, iconSize: 18, onPressed: () => onRemove(index), icon: const Icon(Icons.close_rounded, color: Colors.black)))),
        ],
      ),
    );
  }
}

class _PostMediaGrid extends StatelessWidget {
  final List<Map> media;
  const _PostMediaGrid({required this.media});

  @override
  Widget build(BuildContext context) {
    final videos = media.where((m) => (m['media_type'] ?? '').toString() == 'video').toList();
    if (videos.isNotEmpty) {
      final url = (videos.first['url'] ?? ConnectSocialService.mediaUrl(videos.first['file_path']?.toString())).toString();
      return _VideoCard(url: url, fileName: videos.first['original_name']?.toString() ?? 'Rockview video');
    }
    final images = media.where((m) => (m['media_type'] ?? '').toString() == 'image').toList();
    if (images.isEmpty) return const SizedBox.shrink();
    if (images.length == 1) {
      final url = (images.first['url'] ?? ConnectSocialService.mediaUrl(images.first['file_path']?.toString())).toString();
      return GestureDetector(onTap: () => showZoomableImage(context, url), child: buildSmartFbImage(url, width: double.infinity, height: 360, fit: BoxFit.cover));
    }
    final shown = images.take(4).toList();
    return SizedBox(
      height: images.length == 2 ? 260 : 360,
      child: GridView.builder(
        physics: const NeverScrollableScrollPhysics(),
        itemCount: shown.length,
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2, crossAxisSpacing: 2, mainAxisSpacing: 2),
        itemBuilder: (_, index) {
          final url = (shown[index]['url'] ?? ConnectSocialService.mediaUrl(shown[index]['file_path']?.toString())).toString();
          return GestureDetector(
            onTap: () => showZoomableImage(context, url),
            child: Stack(
              fit: StackFit.expand,
              children: [
                buildSmartFbImage(url, fit: BoxFit.cover),
                if (index == 3 && images.length > 4)
                  Container(color: Colors.black54, alignment: Alignment.center, child: Text('+${images.length - 4}', style: const TextStyle(color: Colors.white, fontSize: 28, fontWeight: FontWeight.w800))),
              ],
            ),
          );
        },
      ),
    );
  }
}

class _VideoCard extends StatefulWidget {
  final String url;
  final String fileName;
  const _VideoCard({required this.url, required this.fileName});

  @override
  State<_VideoCard> createState() => _VideoCardState();
}

class _VideoCardState extends State<_VideoCard> {
  bool _opening = false;

  Future<void> _openVideo() async {
    if (_opening) return;
    setState(() => _opening = true);
    try {
      Directory? dir;
      try {
        dir = await getTemporaryDirectory();
      } catch (_) {}
      if (dir == null) throw Exception('Temporary storage is not available.');
      final safe = widget.fileName.replaceAll(RegExp(r'[^A-Za-z0-9._-]+'), '_');
      final path = '${dir.path}${Platform.pathSeparator}${DateTime.now().millisecondsSinceEpoch}_$safe';
      await Dio().download(widget.url, path);
      await OpenFilex.open(path);
    } catch (e) {
      if (mounted) ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Unable to open video: $e'), backgroundColor: Colors.redAccent));
    } finally {
      if (mounted) setState(() => _opening = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: _openVideo,
      child: Container(
        height: 330,
        width: double.infinity,
        color: const Color(0xFF111B21),
        child: Stack(
          alignment: Alignment.center,
          children: [
            const Positioned.fill(child: DecoratedBox(decoration: BoxDecoration(gradient: LinearGradient(begin: Alignment.topLeft, end: Alignment.bottomRight, colors: [Color(0xFF1B2B24), Color(0xFF07110D)])))),
            Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                if (_opening)
                  const CircularProgressIndicator(color: Colors.white)
                else
                  Container(width: 72, height: 72, decoration: BoxDecoration(color: Colors.white.withOpacity(.15), shape: BoxShape.circle), child: const Icon(Icons.play_arrow_rounded, color: Colors.white, size: 48)),
                const SizedBox(height: 12),
                const Text('Play video', style: TextStyle(color: Colors.white, fontWeight: FontWeight.w800, fontSize: 16)),
                const SizedBox(height: 5),
                Padding(padding: const EdgeInsets.symmetric(horizontal: 20), child: Text(widget.fileName, maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(color: Colors.white.withOpacity(.70), fontSize: 12))),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
