import 'dart:async';

import 'package:flutter/material.dart';

import '../../../../core/services/campus_clubs_service.dart';
import 'club_directory_sub_tab.dart' show ClubDetailsDialog;

const Color _green = Color.fromARGB(255, 2, 105, 48);
const Color _gold = Color.fromARGB(255, 204, 117, 4);
const Color _bg = Color(0xFFF4F7F5);
const Color _border = Color(0xFFE0E7E3);
const Color _ink = Color(0xFF1D2D25);
const Color _muted = Color(0xFF69766F);

class PendingClubsSubTab extends StatefulWidget {
  final ClubCurrentUser currentUser;

  const PendingClubsSubTab({
    super.key,
    required this.currentUser,
  });

  @override
  State<PendingClubsSubTab> createState() => _PendingClubsSubTabState();
}

class _PendingClubsSubTabState extends State<PendingClubsSubTab> {
  final TextEditingController _search = TextEditingController();
  final List<CampusClub> _clubs = <CampusClub>[];
  Timer? _timer;
  bool _loading = true;
  bool _busy = false;
  String? _error;
  String _status = '';
  String _campus = '';
  List<String> _campuses = <String>[];

  @override
  void initState() {
    super.initState();
    _load();
    _timer = Timer.periodic(const Duration(seconds: 20), (_) => _silentRefresh());
  }

  @override
  void dispose() {
    _timer?.cancel();
    _search.dispose();
    super.dispose();
  }

  Future<void> _load() async {
    if (!mounted) return;
    setState(() {
      _loading = true;
      _error = null;
    });
    try {
      final futures = <Future<dynamic>>[
        CampusClubsService.getClubs(
          status: widget.currentUser.isAdmin ? (_status.isEmpty ? 'pending' : _status) : (_status.isEmpty ? 'all' : _status),
          scope: widget.currentUser.isAdmin ? 'directory' : 'my_submissions',
          campus: widget.currentUser.isAdmin ? _campus : '',
          search: _search.text,
        ),
      ];
      if (widget.currentUser.isAdmin && _campuses.isEmpty) {
        futures.add(CampusClubsService.getCampuses());
      }
      final results = await Future.wait<dynamic>(futures);
      if (!mounted) return;
      final page = results.first as ClubPage;
      setState(() {
        _clubs
          ..clear()
          ..addAll(page.clubs);
        if (results.length > 1) _campuses = List<String>.from(results[1] as List);
        _loading = false;
      });
    } catch (e) {
      if (!mounted) return;
      setState(() {
        _loading = false;
        _error = e.toString().replaceFirst('Exception: ', '');
      });
    }
  }

  Future<void> _silentRefresh() async {
    if (!mounted || _loading || _busy) return;
    try {
      final page = await CampusClubsService.getClubs(
        status: widget.currentUser.isAdmin ? (_status.isEmpty ? 'pending' : _status) : (_status.isEmpty ? 'all' : _status),
        scope: widget.currentUser.isAdmin ? 'directory' : 'my_submissions',
        campus: widget.currentUser.isAdmin ? _campus : '',
        search: _search.text,
      );
      if (!mounted) return;
      setState(() {
        _clubs
          ..clear()
          ..addAll(page.clubs);
      });
    } catch (_) {}
  }

  Future<void> _openClub(CampusClub club) async {
    await showDialog<bool>(
      context: context,
      builder: (_) => ClubDetailsDialog(
        clubId: club.id,
        currentUser: widget.currentUser,
        campuses: _campuses,
      ),
    );
    if (mounted) await _load();
  }

  Future<void> _approve(CampusClub club) async {
    final yes = await showDialog<bool>(
      context: context,
      builder: (_) => AlertDialog(
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(18)),
        title: const Text('Approve club registration?'),
        content: Text('Publish "${club.name}" as an active club for ${club.campus}?'),
        actions: [
          TextButton(onPressed: () => Navigator.pop(context, false), child: const Text('Cancel')),
          FilledButton(
            style: FilledButton.styleFrom(backgroundColor: _green),
            onPressed: () => Navigator.pop(context, true),
            child: const Text('Approve'),
          ),
        ],
      ),
    );
    if (yes != true) return;
    setState(() => _busy = true);
    try {
      await CampusClubsService.moderateClub(club.id, 'approve');
      await _load();
      _snack('${club.name} approved.');
    } catch (e) {
      _snack(e.toString().replaceFirst('Exception: ', ''), error: true);
    } finally {
      if (mounted) setState(() => _busy = false);
    }
  }

  Future<void> _reject(CampusClub club) async {
    final controller = TextEditingController();
    final reason = await showDialog<String>(
      context: context,
      builder: (_) => AlertDialog(
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(18)),
        title: const Text('Reject club registration'),
        content: SizedBox(
          width: 480,
          child: TextField(
            controller: controller,
            minLines: 4,
            maxLines: 7,
            decoration: InputDecoration(
              labelText: 'Reason for rejection',
              hintText: 'Explain what the staff member needs to correct.',
              border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
            ),
          ),
        ),
        actions: [
          TextButton(onPressed: () => Navigator.pop(context), child: const Text('Cancel')),
          FilledButton(
            style: FilledButton.styleFrom(backgroundColor: Colors.red.shade700),
            onPressed: () {
              final text = controller.text.trim();
              if (text.isNotEmpty) Navigator.pop(context, text);
            },
            child: const Text('Reject'),
          ),
        ],
      ),
    );
    controller.dispose();
    if (reason == null || reason.isEmpty) return;
    setState(() => _busy = true);
    try {
      await CampusClubsService.moderateClub(club.id, 'reject', reason: reason);
      await _load();
      _snack('${club.name} rejected.');
    } catch (e) {
      _snack(e.toString().replaceFirst('Exception: ', ''), error: true);
    } finally {
      if (mounted) setState(() => _busy = false);
    }
  }

  void _snack(String text, {bool error = false}) {
    if (!mounted) return;
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(backgroundColor: error ? Colors.red.shade700 : _green, content: Text(text)),
    );
  }

  Map<String, List<CampusClub>> get _grouped {
    if (!widget.currentUser.isAdmin) return <String, List<CampusClub>>{'My Registrations': _clubs};
    final map = <String, List<CampusClub>>{};
    for (final club in _clubs) {
      final key = club.campus.trim().isEmpty ? 'Campus not assigned' : club.campus;
      map.putIfAbsent(key, () => <CampusClub>[]).add(club);
    }
    final keys = map.keys.toList()..sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase()));
    return <String, List<CampusClub>>{for (final key in keys) key: map[key]!};
  }

  @override
  Widget build(BuildContext context) {
    return ColoredBox(
      color: _bg,
      child: LayoutBuilder(
        builder: (context, constraints) {
          final compact = constraints.maxWidth < 700;
          return Column(
            children: [
              _header(compact),
              Expanded(
                child: RefreshIndicator(
                  color: _green,
                  onRefresh: _load,
                  child: ListView(
                    physics: const AlwaysScrollableScrollPhysics(),
                    padding: EdgeInsets.fromLTRB(compact ? 10 : 24, 16, compact ? 10 : 24, 80),
                    children: [
                      if (_loading)
                        const Padding(
                          padding: EdgeInsets.symmetric(vertical: 150),
                          child: Center(child: CircularProgressIndicator(color: _green)),
                        )
                      else if (_error != null)
                        _errorCard()
                      else if (_clubs.isEmpty)
                        _emptyCard()
                      else
                        ..._grouped.entries.map((entry) => _group(entry.key, entry.value, compact)),
                    ],
                  ),
                ),
              ),
            ],
          );
        },
      ),
    );
  }

  Widget _header(bool compact) {
    final pending = _clubs.where((c) => c.status == 'pending').length;
    final active = _clubs.where((c) => c.status == 'active').length;
    final rejected = _clubs.where((c) => c.status == 'rejected').length;
    return Container(
      width: double.infinity,
      padding: EdgeInsets.fromLTRB(compact ? 14 : 28, compact ? 16 : 23, compact ? 14 : 28, compact ? 14 : 19),
      decoration: const BoxDecoration(color: Colors.white, border: Border(bottom: BorderSide(color: _border))),
      child: Center(
        child: ConstrainedBox(
          constraints: const BoxConstraints(maxWidth: 1220),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Container(
                    width: 44,
                    height: 44,
                    decoration: BoxDecoration(color: _green.withOpacity(.08), borderRadius: BorderRadius.circular(14)),
                    child: Icon(widget.currentUser.isAdmin ? Icons.fact_check_outlined : Icons.assignment_outlined, color: _green),
                  ),
                  const SizedBox(width: 12),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          widget.currentUser.isAdmin ? 'Club Registration Approvals' : 'My Club Registrations',
                          style: const TextStyle(color: _ink, fontSize: 22, fontWeight: FontWeight.w900),
                        ),
                        const SizedBox(height: 4),
                        Text(
                          widget.currentUser.isAdmin
                              ? 'Review registrations from every campus, inspect membership and documents, then approve or reject.'
                              : 'Track your submitted clubs. You can open a registration to add members and official documents before approval.',
                          style: const TextStyle(color: _muted, fontSize: 12.2, height: 1.4),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 15),
              if (compact)
                Column(
                  children: [
                    _searchBox(),
                    const SizedBox(height: 9),
                    Row(
                      children: [
                        Expanded(child: _statusFilter()),
                        if (widget.currentUser.isAdmin) ...[
                          const SizedBox(width: 8),
                          Expanded(child: _campusFilter()),
                        ],
                      ],
                    ),
                    const SizedBox(height: 9),
                    Row(
                      children: [
                        Expanded(child: _metric(Icons.hourglass_top_rounded, '$pending', 'Pending')),
                        const SizedBox(width: 7),
                        Expanded(child: _metric(Icons.verified_outlined, '$active', 'Active')),
                        const SizedBox(width: 7),
                        Expanded(child: _metric(Icons.cancel_outlined, '$rejected', 'Rejected')),
                      ],
                    ),
                  ],
                )
              else
                Row(
                  children: [
                    Expanded(child: _searchBox()),
                    const SizedBox(width: 10),
                    SizedBox(width: 175, child: _statusFilter()),
                    if (widget.currentUser.isAdmin) ...[
                      const SizedBox(width: 10),
                      SizedBox(width: 190, child: _campusFilter()),
                    ],
                    const SizedBox(width: 12),
                    _metric(Icons.hourglass_top_rounded, '$pending', 'Pending'),
                    const SizedBox(width: 7),
                    _metric(Icons.verified_outlined, '$active', 'Active'),
                    if (!widget.currentUser.isAdmin) ...[
                      const SizedBox(width: 7),
                      _metric(Icons.cancel_outlined, '$rejected', 'Rejected'),
                    ],
                  ],
                ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _searchBox() {
    return TextField(
      controller: _search,
      onSubmitted: (_) => _load(),
      decoration: _inputDecoration('Search club registrations...', Icons.search_rounded).copyWith(
        suffixIcon: IconButton(onPressed: _load, icon: const Icon(Icons.arrow_forward_rounded, color: _green)),
      ),
    );
  }

  Widget _statusFilter() {
    final items = widget.currentUser.isAdmin
        ? const <MapEntry<String, String>>[
            MapEntry('', 'Pending only'),
            MapEntry('all', 'All statuses'),
            MapEntry('active', 'Active'),
            MapEntry('rejected', 'Rejected'),
            MapEntry('inactive', 'Inactive'),
          ]
        : const <MapEntry<String, String>>[
            MapEntry('', 'All statuses'),
            MapEntry('pending', 'Pending'),
            MapEntry('active', 'Active'),
            MapEntry('rejected', 'Rejected'),
            MapEntry('inactive', 'Inactive'),
          ];
    return DropdownButtonFormField<String>(
      value: _status,
      isExpanded: true,
      decoration: _inputDecoration('Status', Icons.filter_alt_outlined),
      items: items.map((entry) => DropdownMenuItem(value: entry.key, child: Text(entry.value))).toList(),
      onChanged: (value) {
        setState(() => _status = value ?? '');
        _load();
      },
    );
  }

  Widget _campusFilter() {
    return DropdownButtonFormField<String>(
      value: _campus,
      isExpanded: true,
      decoration: _inputDecoration('Campus', Icons.location_city_outlined),
      items: <DropdownMenuItem<String>>[
        const DropdownMenuItem(value: '', child: Text('All campuses')),
        ..._campuses.map((campus) => DropdownMenuItem(value: campus, child: Text(campus, overflow: TextOverflow.ellipsis))),
      ],
      onChanged: (value) {
        setState(() => _campus = value ?? '');
        _load();
      },
    );
  }

  Widget _metric(IconData icon, String value, String label) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 9),
      decoration: BoxDecoration(color: const Color(0xFFF8FAF9), borderRadius: BorderRadius.circular(12), border: Border.all(color: _border)),
      child: Row(mainAxisSize: MainAxisSize.min, children: [Icon(icon, size: 16, color: _green), const SizedBox(width: 6), Text(value, style: const TextStyle(color: _ink, fontWeight: FontWeight.w900)), const SizedBox(width: 4), Flexible(child: Text(label, overflow: TextOverflow.ellipsis, style: const TextStyle(color: _muted, fontSize: 9.8)))]),
    );
  }

  Widget _group(String title, List<CampusClub> clubs, bool compact) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 23),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(children: [const Icon(Icons.location_city_outlined, color: _green, size: 20), const SizedBox(width: 8), Expanded(child: Text(title, style: const TextStyle(color: _ink, fontSize: 16, fontWeight: FontWeight.w900))), Text('${clubs.length}', style: const TextStyle(color: _muted, fontWeight: FontWeight.w800))]),
          const SizedBox(height: 10),
          ...clubs.map((club) => Padding(padding: const EdgeInsets.only(bottom: 10), child: _registrationCard(club, compact))),
        ],
      ),
    );
  }

  Widget _registrationCard(CampusClub club, bool compact) {
    final statusColor = club.status == 'active'
        ? _green
        : club.status == 'rejected'
            ? Colors.red.shade700
            : club.status == 'inactive'
                ? Colors.grey.shade700
                : _gold;
    return Material(
      color: Colors.white,
      borderRadius: BorderRadius.circular(18),
      child: InkWell(
        borderRadius: BorderRadius.circular(18),
        onTap: () => _openClub(club),
        child: Container(
          padding: const EdgeInsets.all(15),
          decoration: BoxDecoration(borderRadius: BorderRadius.circular(18), border: Border.all(color: _border)),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Container(
                    width: 45,
                    height: 45,
                    alignment: Alignment.center,
                    decoration: BoxDecoration(color: _green.withOpacity(.09), borderRadius: BorderRadius.circular(13)),
                    child: Text(_initials(club.name), style: const TextStyle(color: _green, fontWeight: FontWeight.w900, fontSize: 12)),
                  ),
                  const SizedBox(width: 11),
                  Expanded(
                    child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [Text(club.name, maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle(color: _ink, fontWeight: FontWeight.w900, fontSize: 14.5)), const SizedBox(height: 3), Text('${club.category} • ${club.campus}', maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle(color: _muted, fontSize: 10.2))]),
                  ),
                  Container(
                    padding: const EdgeInsets.symmetric(horizontal: 9, vertical: 5),
                    decoration: BoxDecoration(color: statusColor.withOpacity(.09), borderRadius: BorderRadius.circular(20), border: Border.all(color: statusColor.withOpacity(.25))),
                    child: Text(club.status.toUpperCase(), style: TextStyle(color: statusColor, fontWeight: FontWeight.w900, fontSize: 9.2)),
                  ),
                ],
              ),
              const SizedBox(height: 10),
              Text(club.purpose, maxLines: 2, overflow: TextOverflow.ellipsis, style: const TextStyle(color: _muted, fontSize: 11.3, height: 1.4)),
              if (club.status == 'rejected' && club.rejectionReason.trim().isNotEmpty) ...[
                const SizedBox(height: 10),
                Container(
                  width: double.infinity,
                  padding: const EdgeInsets.all(10),
                  decoration: BoxDecoration(color: Colors.red.shade50, borderRadius: BorderRadius.circular(10), border: Border.all(color: Colors.red.shade100)),
                  child: Text('Administration feedback: ${club.rejectionReason}', style: TextStyle(color: Colors.red.shade800, fontSize: 10.5, height: 1.4)),
                ),
              ],
              const SizedBox(height: 10),
              Wrap(
                spacing: 8,
                runSpacing: 6,
                children: [
                  _meta(Icons.person_outline_rounded, 'By ${club.creatorName}'),
                  _meta(Icons.people_alt_outlined, '${club.memberCount} members'),
                  _meta(Icons.description_outlined, '${club.documentCount} documents'),
                  _meta(Icons.schedule_outlined, _date(club.createdAt)),
                ],
              ),
              const SizedBox(height: 11),
              if (widget.currentUser.isAdmin && club.status == 'pending')
                if (compact)
                  Column(
                    children: [
                      SizedBox(width: double.infinity, child: OutlinedButton.icon(onPressed: _busy ? null : () => _openClub(club), icon: const Icon(Icons.visibility_outlined), label: const Text('Review Details'))),
                      const SizedBox(height: 7),
                      Row(children: [Expanded(child: OutlinedButton(onPressed: _busy ? null : () => _reject(club), style: OutlinedButton.styleFrom(foregroundColor: Colors.red.shade700), child: const Text('Reject'))), const SizedBox(width: 7), Expanded(child: FilledButton(onPressed: _busy ? null : () => _approve(club), style: FilledButton.styleFrom(backgroundColor: _green), child: const Text('Approve')))]),
                    ],
                  )
                else
                  Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      OutlinedButton.icon(onPressed: _busy ? null : () => _openClub(club), icon: const Icon(Icons.visibility_outlined, size: 17), label: const Text('Review')),
                      const SizedBox(width: 8),
                      OutlinedButton(onPressed: _busy ? null : () => _reject(club), style: OutlinedButton.styleFrom(foregroundColor: Colors.red.shade700), child: const Text('Reject')),
                      const SizedBox(width: 8),
                      FilledButton.icon(onPressed: _busy ? null : () => _approve(club), style: FilledButton.styleFrom(backgroundColor: _green), icon: const Icon(Icons.check_rounded, size: 17), label: const Text('Approve')),
                    ],
                  )
              else
                Align(
                  alignment: Alignment.centerRight,
                  child: OutlinedButton.icon(
                    onPressed: () => _openClub(club),
                    icon: const Icon(Icons.open_in_new_rounded, size: 16),
                    label: Text(widget.currentUser.isAdmin ? 'Open Club' : 'Manage Registration'),
                  ),
                ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _errorCard() {
    return _centerCard(Icons.cloud_off_rounded, Colors.red.shade300, 'Registrations could not be loaded', _error ?? 'Unknown error.');
  }

  Widget _emptyCard() {
    return _centerCard(
      widget.currentUser.isAdmin ? Icons.fact_check_outlined : Icons.assignment_turned_in_outlined,
      Colors.grey.shade300,
      widget.currentUser.isAdmin ? 'No club registrations in this queue' : 'No club registrations yet',
      widget.currentUser.isAdmin
          ? 'There are no club registrations matching the selected filters.'
          : 'Clubs that you register will appear here with their approval status.',
    );
  }

  Widget _centerCard(IconData icon, Color color, String title, String message) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 22, vertical: 80),
      decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(20), border: Border.all(color: _border)),
      child: Column(children: [Icon(icon, size: 62, color: color), const SizedBox(height: 14), Text(title, textAlign: TextAlign.center, style: const TextStyle(color: _ink, fontWeight: FontWeight.w900, fontSize: 18)), const SizedBox(height: 7), Text(message, textAlign: TextAlign.center, style: const TextStyle(color: _muted, height: 1.5)), const SizedBox(height: 15), FilledButton.icon(onPressed: _load, style: FilledButton.styleFrom(backgroundColor: _green), icon: const Icon(Icons.refresh_rounded), label: const Text('Refresh'))]),
    );
  }

  InputDecoration _inputDecoration(String hint, IconData icon) {
    return InputDecoration(
      hintText: hint,
      prefixIcon: Icon(icon, color: _green, size: 18),
      filled: true,
      fillColor: const Color(0xFFF8FAF9),
      isDense: true,
      contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 13),
      border: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: const BorderSide(color: _border)),
      enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: const BorderSide(color: _border)),
      focusedBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: const BorderSide(color: _green, width: 1.3)),
    );
  }
}

Widget _meta(IconData icon, String text) {
  return Row(mainAxisSize: MainAxisSize.min, children: [Icon(icon, size: 13, color: _muted), const SizedBox(width: 4), Text(text, style: const TextStyle(color: _muted, fontSize: 9.8, fontWeight: FontWeight.w600))]);
}

String _initials(String value) {
  final parts = value.trim().split(RegExp(r'\s+')).where((e) => e.isNotEmpty).toList();
  if (parts.isEmpty) return 'CL';
  if (parts.length == 1) return parts.first.substring(0, parts.first.length > 1 ? 2 : 1).toUpperCase();
  return '${parts.first[0]}${parts.last[0]}'.toUpperCase();
}

String _date(DateTime value) {
  const months = <String>['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
  final local = value.toLocal();
  return '${local.day} ${months[local.month - 1]} ${local.year}';
}
