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

import 'dart:async';

import 'package:flutter/material.dart';

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

const Color _communityGreen = Color(0xFF118A5E);
const Color _communityDark = Color(0xFF111B21);
const Color _communityMuted = Color(0xFF667781);
const Color _communityBg = Color(0xFFF0F2F5);

class CommunitiesPanel extends StatefulWidget {
  final VoidCallback? onBack;

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

  @override
  State<CommunitiesPanel> createState() => _CommunitiesPanelState();
}

class _CommunitiesPanelState extends State<CommunitiesPanel> {
  final _searchController = TextEditingController();
  List<Map<String, dynamic>> _communities = [];
  bool _loading = true;
  bool _refreshing = false;
  String? _error;
  int? _processingCommunity;
  Timer? _refreshTimer;

  @override
  void initState() {
    super.initState();
    _loadCommunities();
    _refreshTimer = Timer.periodic(const Duration(seconds: 30), (_) => _loadCommunities(silent: true));
  }

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

  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 _cleanError(Object e) => e.toString().replaceFirst(RegExp(r'^Exception:\s*'), '').trim();

  Future<void> _loadCommunities({bool silent = false}) async {
    if (!mounted || (silent && _refreshing)) return;
    if (!silent) {
      setState(() {
        _loading = true;
        _error = null;
      });
    }
    _refreshing = true;
    try {
      final data = await ConnectSocialService.getCommunities(search: _searchController.text.trim());
      if (!mounted) return;
      setState(() {
        _communities = data;
        _loading = false;
        _error = null;
      });
    } catch (e) {
      if (!mounted) return;
      if (!silent) {
        setState(() {
          _loading = false;
          _error = _cleanError(e);
        });
      }
    } finally {
      _refreshing = false;
    }
  }

  Future<void> _openCreateCommunity() async {
    final result = await showDialog<bool>(
      context: context,
      barrierDismissible: false,
      builder: (_) => const _CreateCommunityDialog(),
    );
    if (result == true) await _loadCommunities();
  }

  Future<void> _toggleMembership(Map<String, dynamic> community) async {
    final id = _int(community['id']);
    if (id <= 0 || _processingCommunity != null) return;
    final isMember = _bool(community['is_member']);
    setState(() => _processingCommunity = id);
    try {
      final result = await ConnectSocialService.updateMembership(communityId: id, join: !isMember);
      if (!mounted) return;
      setState(() {
        community['is_member'] = result['is_member'];
        community['members_count'] = result['members_count'];
        if (!isMember) community['my_role'] = 'member';
        if (isMember) community['my_role'] = '';
      });
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(!isMember ? 'You joined ${community['name']}.' : 'You left ${community['name']}.'),
          backgroundColor: _communityGreen,
          behavior: SnackBarBehavior.floating,
        ),
      );
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(_cleanError(e)), backgroundColor: Colors.red.shade700, behavior: SnackBarBehavior.floating));
      }
    } finally {
      if (mounted) setState(() => _processingCommunity = null);
    }
  }

  Future<void> _openCommunity(Map<String, dynamic> community) async {
    await showModalBottomSheet<void>(
      context: context,
      isScrollControlled: true,
      useSafeArea: true,
      backgroundColor: Colors.transparent,
      builder: (_) => _CommunityDetailsSheet(community: community),
    );
    await _loadCommunities(silent: true);
  }

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        final compact = constraints.maxWidth < 620;
        final width = constraints.maxWidth;
        final columns = width >= 1200 ? 3 : width >= 760 ? 2 : 1;

        return Scaffold(
          backgroundColor: _communityBg,
          floatingActionButton: compact
              ? FloatingActionButton(onPressed: _openCreateCommunity, backgroundColor: _communityGreen, foregroundColor: Colors.white, child: const Icon(Icons.group_add_rounded))
              : null,
          body: Column(
            children: [
              _header(compact),
              Expanded(
                child: RefreshIndicator(
                  color: _communityGreen,
                  onRefresh: () => _loadCommunities(),
                  child: _body(columns: columns, compact: compact),
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  Widget _header(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 (widget.onBack != null) IconButton(onPressed: widget.onBack, icon: const Icon(Icons.arrow_back_rounded)),
            Container(width: 40, height: 40, decoration: BoxDecoration(color: _communityGreen.withOpacity(.10), borderRadius: BorderRadius.circular(12)), child: const Icon(Icons.groups_rounded, color: _communityGreen)),
            const SizedBox(width: 10),
            const Expanded(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text('Communities', style: TextStyle(fontWeight: FontWeight.w800, fontSize: 18, color: _communityDark)),
                  Text('Discover, join and build Rockview communities', style: TextStyle(fontSize: 11, color: _communityMuted)),
                ],
              ),
            ),
            if (!compact)
              FilledButton.icon(onPressed: _openCreateCommunity, icon: const Icon(Icons.add_rounded), label: const Text('New community'), style: FilledButton.styleFrom(backgroundColor: _communityGreen)),
            IconButton(onPressed: () => _loadCommunities(), icon: const Icon(Icons.refresh_rounded), tooltip: 'Refresh'),
          ],
        ),
      ),
    );
  }

  Widget _body({required int columns, required bool compact}) {
    if (_loading) {
      return ListView(physics: const AlwaysScrollableScrollPhysics(), children: const [SizedBox(height: 170), Center(child: CircularProgressIndicator(color: _communityGreen))]);
    }
    if (_error != null) {
      return ListView(
        physics: const AlwaysScrollableScrollPhysics(),
        padding: const EdgeInsets.all(24),
        children: [
          const SizedBox(height: 70),
          Icon(Icons.cloud_off_rounded, size: 56, color: Colors.grey.shade400),
          const SizedBox(height: 12),
          const Text('Communities 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: _communityMuted)),
          const SizedBox(height: 16),
          Center(child: FilledButton.icon(onPressed: () => _loadCommunities(), icon: const Icon(Icons.refresh_rounded), label: const Text('Try again'))),
        ],
      );
    }

    return CustomScrollView(
      physics: const AlwaysScrollableScrollPhysics(parent: BouncingScrollPhysics()),
      slivers: [
        SliverToBoxAdapter(
          child: Center(
            child: ConstrainedBox(
              constraints: const BoxConstraints(maxWidth: 1180),
              child: Padding(
                padding: EdgeInsets.fromLTRB(compact ? 12 : 20, 16, compact ? 12 : 20, 10),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    _summaryCard(),
                    const SizedBox(height: 12),
                    TextField(
                      controller: _searchController,
                      onSubmitted: (_) => _loadCommunities(),
                      decoration: InputDecoration(
                        hintText: 'Search communities...',
                        prefixIcon: const Icon(Icons.search_rounded),
                        suffixIcon: _searchController.text.isEmpty ? null : IconButton(onPressed: () { _searchController.clear(); setState(() {}); _loadCommunities(); }, icon: const Icon(Icons.close_rounded)),
                        filled: true,
                        fillColor: Colors.white,
                        border: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: BorderSide.none),
                      ),
                      onChanged: (_) => setState(() {}),
                    ),
                    const SizedBox(height: 16),
                    Text('${_communities.length} active communit${_communities.length == 1 ? 'y' : 'ies'}', style: const TextStyle(fontSize: 13, fontWeight: FontWeight.w700, color: _communityMuted)),
                  ],
                ),
              ),
            ),
          ),
        ),
        if (_communities.isEmpty)
          SliverFillRemaining(hasScrollBody: false, child: _emptyState())
        else
          SliverPadding(
            padding: EdgeInsets.fromLTRB(compact ? 12 : 20, 0, compact ? 12 : 20, 100),
            sliver: SliverLayoutBuilder(
              builder: (context, constraints) {
                final maxWidth = constraints.crossAxisExtent;
                final contentWidth = maxWidth > 1180 ? 1180.0 : maxWidth;
                return SliverToBoxAdapter(
                  child: Center(
                    child: SizedBox(
                      width: contentWidth,
                      child: GridView.builder(
                        shrinkWrap: true,
                        physics: const NeverScrollableScrollPhysics(),
                        itemCount: _communities.length,
                        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: columns, crossAxisSpacing: 14, mainAxisSpacing: 14, mainAxisExtent: columns == 1 ? 215 : 235),
                        itemBuilder: (_, index) => _communityCard(_communities[index]),
                      ),
                    ),
                  ),
                );
              },
            ),
          ),
      ],
    );
  }

  Widget _summaryCard() {
    final joined = _communities.where((c) => _bool(c['is_member'])).length;
    final members = _communities.fold<int>(0, (sum, c) => sum + _int(c['members_count']));
    return Container(
      padding: const EdgeInsets.all(18),
      decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(16), boxShadow: [BoxShadow(color: Colors.black.withOpacity(.04), blurRadius: 12)]),
      child: Row(
        children: [
          Container(width: 50, height: 50, decoration: BoxDecoration(color: _communityGreen.withOpacity(.10), borderRadius: BorderRadius.circular(14)), child: const Icon(Icons.hub_rounded, color: _communityGreen, size: 28)),
          const SizedBox(width: 12),
          const Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [Text('Rockview Communities', style: TextStyle(fontWeight: FontWeight.w800, fontSize: 17, color: _communityDark)), SizedBox(height: 3), Text('University-wide spaces visible to signed-in staff.', style: TextStyle(fontSize: 12, color: _communityMuted))])),
          _stat('${_communities.length}', 'Spaces'),
          const SizedBox(width: 16),
          _stat('$joined', 'Joined'),
          const SizedBox(width: 16),
          _stat('$members', 'Members'),
        ],
      ),
    );
  }

  Widget _stat(String value, String label) => Column(children: [Text(value, style: const TextStyle(fontWeight: FontWeight.w900, fontSize: 18, color: _communityDark)), Text(label, style: const TextStyle(fontSize: 10, color: _communityMuted))]);

  Widget _communityCard(Map<String, dynamic> community) {
    final id = _int(community['id']);
    final name = (community['name'] ?? 'Community').toString();
    final description = (community['description'] ?? '').toString();
    final campus = (community['campus'] ?? 'University-wide').toString();
    final creator = (community['creator_name'] ?? 'Rockview Staff').toString();
    final members = _int(community['members_count']);
    final isMember = _bool(community['is_member']);
    final role = (community['my_role'] ?? '').toString();
    final busy = _processingCommunity == id;

    return Material(
      color: Colors.white,
      borderRadius: BorderRadius.circular(16),
      child: InkWell(
        borderRadius: BorderRadius.circular(16),
        onTap: () => _openCommunity(community),
        child: Container(
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(borderRadius: BorderRadius.circular(16), boxShadow: [BoxShadow(color: Colors.black.withOpacity(.035), blurRadius: 10)]),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Container(width: 50, height: 50, decoration: BoxDecoration(color: _communityGreen.withOpacity(.11), borderRadius: BorderRadius.circular(14)), child: Center(child: Text(name.isNotEmpty ? name[0].toUpperCase() : 'C', style: const TextStyle(color: _communityGreen, fontWeight: FontWeight.w900, fontSize: 22)))),
                  const SizedBox(width: 11),
                  Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [Text(name, maxLines: 2, overflow: TextOverflow.ellipsis, style: const TextStyle(fontWeight: FontWeight.w800, fontSize: 16, color: _communityDark)), const SizedBox(height: 3), Text('$members member${members == 1 ? '' : 's'}', style: const TextStyle(fontSize: 12, color: _communityMuted))])),
                  if (role == 'admin') Container(padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), decoration: BoxDecoration(color: const Color(0xFFFFF4E3), borderRadius: BorderRadius.circular(20)), child: const Text('ADMIN', style: TextStyle(fontSize: 9, fontWeight: FontWeight.w900, color: Color(0xFFB56B00)))),
                ],
              ),
              const SizedBox(height: 12),
              Text(description.isEmpty ? 'No description provided.' : description, maxLines: 3, overflow: TextOverflow.ellipsis, style: const TextStyle(color: _communityMuted, height: 1.35, fontSize: 13)),
              const Spacer(),
              Row(children: [const Icon(Icons.location_on_outlined, size: 15, color: _communityMuted), const SizedBox(width: 4), Expanded(child: Text(campus, maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle(fontSize: 11, color: _communityMuted))), const Icon(Icons.person_outline_rounded, size: 15, color: _communityMuted), const SizedBox(width: 4), Flexible(child: Text(creator, maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle(fontSize: 11, color: _communityMuted)))]),
              const SizedBox(height: 12),
              SizedBox(
                width: double.infinity,
                child: OutlinedButton.icon(
                  onPressed: role == 'admin' || busy ? null : () => _toggleMembership(community),
                  icon: busy ? const SizedBox(width: 16, height: 16, child: CircularProgressIndicator(strokeWidth: 2)) : Icon(isMember ? Icons.logout_rounded : Icons.group_add_rounded, size: 18),
                  label: Text(role == 'admin' ? 'You manage this community' : isMember ? 'Leave community' : 'Join community'),
                  style: OutlinedButton.styleFrom(foregroundColor: isMember ? _communityMuted : _communityGreen, side: BorderSide(color: isMember ? Colors.grey.shade300 : _communityGreen.withOpacity(.55)), padding: const EdgeInsets.symmetric(vertical: 10)),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _emptyState() {
    return Center(
      child: SingleChildScrollView(
        padding: const EdgeInsets.all(28),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Container(width: 90, height: 90, decoration: BoxDecoration(color: _communityGreen.withOpacity(.10), borderRadius: BorderRadius.circular(26)), child: const Icon(Icons.groups_rounded, color: _communityGreen, size: 46)),
            const SizedBox(height: 18),
            const Text('Build the first community', textAlign: TextAlign.center, style: TextStyle(fontWeight: FontWeight.w900, fontSize: 21, color: _communityDark)),
            const SizedBox(height: 7),
            const Text('Communities created here are stored in the PHP/PostgreSQL backend, so all signed-in staff using the updated app can discover and join them.', textAlign: TextAlign.center, style: TextStyle(color: _communityMuted, height: 1.45)),
            const SizedBox(height: 18),
            FilledButton.icon(onPressed: _openCreateCommunity, icon: const Icon(Icons.add_rounded), label: const Text('Create community'), style: FilledButton.styleFrom(backgroundColor: _communityGreen)),
          ],
        ),
      ),
    );
  }
}

class _CreateCommunityDialog extends StatefulWidget {
  const _CreateCommunityDialog();

  @override
  State<_CreateCommunityDialog> createState() => _CreateCommunityDialogState();
}

class _CreateCommunityDialogState extends State<_CreateCommunityDialog> {
  final _name = TextEditingController();
  final _description = TextEditingController();
  bool _saving = false;

  @override
  void dispose() {
    _name.dispose();
    _description.dispose();
    super.dispose();
  }

  Future<void> _save() async {
    if (_saving || _name.text.trim().isEmpty) return;
    setState(() => _saving = true);
    try {
      await ConnectSocialService.createCommunity(name: _name.text, description: _description.text);
      if (mounted) Navigator.pop(context, true);
    } catch (e) {
      if (!mounted) return;
      setState(() => _saving = false);
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(e.toString().replaceFirst(RegExp(r'^Exception:\s*'), '')), backgroundColor: Colors.red.shade700));
    }
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(18)),
      title: const Text('Create community', style: TextStyle(fontWeight: FontWeight.w800)),
      content: ConstrainedBox(
        constraints: const BoxConstraints(maxWidth: 480),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            TextField(controller: _name, autofocus: true, maxLength: 160, decoration: InputDecoration(labelText: 'Community name', prefixIcon: const Icon(Icons.groups_rounded), filled: true, fillColor: const Color(0xFFF0F2F5), border: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: BorderSide.none))),
            const SizedBox(height: 12),
            TextField(controller: _description, minLines: 3, maxLines: 5, maxLength: 1200, decoration: InputDecoration(labelText: 'Description', alignLabelWithHint: true, filled: true, fillColor: const Color(0xFFF0F2F5), border: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: BorderSide.none))),
            const SizedBox(height: 6),
            const Row(crossAxisAlignment: CrossAxisAlignment.start, children: [Icon(Icons.info_outline_rounded, size: 17, color: _communityMuted), SizedBox(width: 6), Expanded(child: Text('The creator is automatically added as the community administrator. All signed-in Rockview staff can discover the community and request to join immediately.', style: TextStyle(fontSize: 11, color: _communityMuted, height: 1.35)))]),
          ],
        ),
      ),
      actions: [
        TextButton(onPressed: _saving ? null : () => Navigator.pop(context), child: const Text('Cancel')),
        FilledButton(onPressed: _saving ? null : _save, style: FilledButton.styleFrom(backgroundColor: _communityGreen), child: _saving ? const SizedBox(width: 18, height: 18, child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white)) : const Text('CREATE')),
      ],
    );
  }
}

class _CommunityDetailsSheet extends StatefulWidget {
  final Map<String, dynamic> community;
  const _CommunityDetailsSheet({required this.community});

  @override
  State<_CommunityDetailsSheet> createState() => _CommunityDetailsSheetState();
}

class _CommunityDetailsSheetState extends State<_CommunityDetailsSheet> {
  List<Map<String, dynamic>> _members = [];
  bool _loading = true;
  String? _error;

  int get _id => int.tryParse('${widget.community['id'] ?? 0}') ?? 0;

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

  Future<void> _load() async {
    try {
      final data = await ConnectSocialService.getCommunityMembers(_id);
      if (mounted) setState(() { _members = data; _loading = false; _error = null; });
    } catch (e) {
      if (mounted) setState(() { _loading = false; _error = e.toString().replaceFirst(RegExp(r'^Exception:\s*'), ''); });
    }
  }

  @override
  Widget build(BuildContext context) {
    final name = (widget.community['name'] ?? 'Community').toString();
    final description = (widget.community['description'] ?? '').toString();
    return FractionallySizedBox(
      heightFactor: .88,
      child: Container(
        decoration: const BoxDecoration(color: Colors.white, borderRadius: BorderRadius.vertical(top: Radius.circular(22))),
        child: Column(
          children: [
            Container(width: 42, height: 4, margin: const EdgeInsets.only(top: 9), decoration: BoxDecoration(color: Colors.grey.shade300, borderRadius: BorderRadius.circular(4))),
            Padding(
              padding: const EdgeInsets.fromLTRB(18, 14, 8, 12),
              child: Row(children: [Container(width: 48, height: 48, decoration: BoxDecoration(color: _communityGreen.withOpacity(.10), borderRadius: BorderRadius.circular(14)), child: const Icon(Icons.groups_rounded, color: _communityGreen)), const SizedBox(width: 11), Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [Text(name, style: const TextStyle(fontWeight: FontWeight.w900, fontSize: 19)), if (description.isNotEmpty) Text(description, maxLines: 2, overflow: TextOverflow.ellipsis, style: const TextStyle(color: _communityMuted, fontSize: 12))])), IconButton(onPressed: () => Navigator.pop(context), icon: const Icon(Icons.close_rounded))]),
            ),
            const Divider(height: 1),
            Padding(padding: const EdgeInsets.fromLTRB(18, 14, 18, 8), child: Row(children: [const Text('Members', style: TextStyle(fontWeight: FontWeight.w800, fontSize: 16)), const Spacer(), Text('${_members.length}', style: const TextStyle(color: _communityMuted, fontWeight: FontWeight.w700))])),
            Expanded(
              child: _loading
                  ? const Center(child: CircularProgressIndicator(color: _communityGreen))
                  : _error != null
                      ? Center(child: Padding(padding: const EdgeInsets.all(24), child: Column(mainAxisSize: MainAxisSize.min, children: [Text(_error!, textAlign: TextAlign.center), const SizedBox(height: 10), FilledButton.icon(onPressed: _load, icon: const Icon(Icons.refresh_rounded), label: const Text('Try again'))])))
                      : _members.isEmpty
                          ? const Center(child: Text('No members yet.', style: TextStyle(color: _communityMuted)))
                          : ListView.separated(
                              padding: const EdgeInsets.fromLTRB(12, 0, 12, 20),
                              itemCount: _members.length,
                              separatorBuilder: (_, __) => const Divider(height: 1),
                              itemBuilder: (_, index) {
                                final member = _members[index];
                                final name = (member['user_name'] ?? 'Rockview User').toString();
                                final role = (member['role'] ?? 'member').toString();
                                return ListTile(leading: CircleAvatar(backgroundColor: _communityGreen.withOpacity(.10), foregroundColor: _communityGreen, child: Text(name.isNotEmpty ? name[0].toUpperCase() : 'U')), title: Text(name, style: const TextStyle(fontWeight: FontWeight.w700)), subtitle: Text((member['user_email'] ?? '').toString()), trailing: role == 'admin' ? const Chip(label: Text('ADMIN', style: TextStyle(fontSize: 9, fontWeight: FontWeight.w900))) : const Text('Member', style: TextStyle(fontSize: 11, color: _communityMuted)));
                              },
                            ),
            ),
          ],
        ),
      ),
    );
  }
}
