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

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

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

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 ClubDirectorySubTab extends StatefulWidget {
  final ClubCurrentUser currentUser;

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

  @override
  State<ClubDirectorySubTab> createState() => _ClubDirectorySubTabState();
}

class _ClubDirectorySubTabState extends State<ClubDirectorySubTab> {
  final TextEditingController _search = TextEditingController();
  final List<CampusClub> _clubs = <CampusClub>[];
  Timer? _timer;
  bool _loading = true;
  bool _refreshing = false;
  String? _error;
  String _category = '';
  String _campus = '';
  List<String> _campuses = <String>[];

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

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

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

    try {
      final futures = <Future<dynamic>>[
        CampusClubsService.getClubs(
          status: 'active',
          campus: widget.currentUser.isAdmin ? _campus : '',
          category: _category,
          search: _search.text,
          scope: 'directory',
        ),
      ];
      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;
        _refreshing = false;
        _error = null;
      });
    } catch (e) {
      if (!mounted) return;
      setState(() {
        _loading = false;
        _refreshing = false;
        _error = _cleanError(e);
      });
    }
  }

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

  String _cleanError(Object e) =>
      e.toString().replaceFirst('Exception: ', '').trim();

  Future<void> _createClub() async {
    final changed = await showDialog<bool>(
      context: context,
      barrierDismissible: false,
      builder: (_) => _ClubEditorDialog(
        currentUser: widget.currentUser,
        campuses: _campuses,
      ),
    );
    if (changed == true) {
      await _load();
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          backgroundColor: _green,
          content: Text(
            widget.currentUser.isAdmin
                ? 'Club created successfully.'
                : 'Club registration submitted. Administration can now review it under approvals.',
          ),
        ),
      );
    }
  }

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

  Map<String, List<CampusClub>> get _grouped {
    final map = <String, List<CampusClub>>{};
    for (final club in _clubs) {
      final key = widget.currentUser.isAdmin
          ? (club.campus.trim().isEmpty ? 'Campus not assigned' : club.campus)
          : (club.category.trim().isEmpty ? 'Other' : club.category);
      map.putIfAbsent(key, () => <CampusClub>[]).add(club);
    }
    final sortedKeys = map.keys.toList()
      ..sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase()));
    return <String, List<CampusClub>>{
      for (final key in sortedKeys) 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,
                      90,
                    ),
                    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) => _ClubGroup(
                            title: entry.key,
                            clubs: entry.value,
                            adminGrouping: widget.currentUser.isAdmin,
                            onOpen: _openClub,
                          ),
                        ),
                    ],
                  ),
                ),
              ),
            ],
          );
        },
      ),
    );
  }

  Widget _header(bool compact) {
    final totalMembers = _clubs.fold<int>(0, (sum, club) => sum + club.memberCount);
    final totalDocs = _clubs.fold<int>(0, (sum, club) => sum + club.documentCount);
    final campusCount = _clubs.map((e) => e.campus.toLowerCase()).where((e) => e.isNotEmpty).toSet().length;

    return Container(
      width: double.infinity,
      padding: EdgeInsets.fromLTRB(
        compact ? 14 : 28,
        compact ? 15 : 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: [
              if (compact)
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    _titleBlock(),
                    const SizedBox(height: 13),
                    SizedBox(width: double.infinity, child: _createButton()),
                  ],
                )
              else
                Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Expanded(child: _titleBlock()),
                    const SizedBox(width: 20),
                    _createButton(),
                  ],
                ),
              const SizedBox(height: 16),
              if (compact)
                Column(
                  children: [
                    _searchBox(),
                    const SizedBox(height: 10),
                    Row(
                      children: [
                        Expanded(child: _categoryFilter()),
                        if (widget.currentUser.isAdmin) ...[
                          const SizedBox(width: 8),
                          Expanded(child: _campusFilter()),
                        ],
                      ],
                    ),
                    const SizedBox(height: 10),
                    Row(
                      children: [
                        Expanded(child: _metric(Icons.hub_rounded, '${_clubs.length}', 'Clubs')),
                        const SizedBox(width: 7),
                        Expanded(child: _metric(Icons.people_alt_outlined, '$totalMembers', 'Members')),
                      ],
                    ),
                    const SizedBox(height: 7),
                    Row(
                      children: [
                        Expanded(child: _metric(Icons.description_outlined, '$totalDocs', 'Documents')),
                        const SizedBox(width: 7),
                        Expanded(
                          child: _metric(
                            Icons.location_city_outlined,
                            widget.currentUser.isAdmin ? '$campusCount' : '1',
                            widget.currentUser.isAdmin ? 'Campuses' : 'Campus',
                          ),
                        ),
                      ],
                    ),
                  ],
                )
              else
                Row(
                  children: [
                    Expanded(child: _searchBox()),
                    const SizedBox(width: 10),
                    SizedBox(width: 210, child: _categoryFilter()),
                    if (widget.currentUser.isAdmin) ...[
                      const SizedBox(width: 10),
                      SizedBox(width: 190, child: _campusFilter()),
                    ],
                    const SizedBox(width: 12),
                    _metric(Icons.hub_rounded, '${_clubs.length}', 'Clubs'),
                    const SizedBox(width: 7),
                    _metric(Icons.people_alt_outlined, '$totalMembers', 'Members'),
                    const SizedBox(width: 7),
                    _metric(Icons.description_outlined, '$totalDocs', 'Docs'),
                  ],
                ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _titleBlock() {
    final campusLabel = widget.currentUser.isAdmin
        ? 'Management overview across all Rockview University campuses.'
        : widget.currentUser.campus.isEmpty
            ? 'Your account has no campus assignment. Club registration requires a campus.'
            : 'Showing approved clubs registered at ${widget.currentUser.campus} only.';
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Container(
              width: 44,
              height: 44,
              decoration: BoxDecoration(
                color: _green.withOpacity(.08),
                borderRadius: BorderRadius.circular(14),
              ),
              child: const Icon(Icons.groups_2_outlined, color: _green),
            ),
            const SizedBox(width: 12),
            const Expanded(
              child: Text(
                'Campus Club Directory',
                style: TextStyle(
                  color: _ink,
                  fontSize: 22,
                  fontWeight: FontWeight.w900,
                ),
              ),
            ),
          ],
        ),
        const SizedBox(height: 7),
        Text(
          campusLabel,
          style: const TextStyle(color: _muted, fontSize: 12.5, height: 1.45),
        ),
      ],
    );
  }

  Widget _createButton() {
    return FilledButton.icon(
      onPressed: widget.currentUser.isAdmin || widget.currentUser.campus.isNotEmpty
          ? _createClub
          : null,
      style: FilledButton.styleFrom(
        backgroundColor: _green,
        foregroundColor: Colors.white,
        padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 15),
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(13)),
      ),
      icon: const Icon(Icons.add_rounded, size: 19),
      label: const Text('Register Club', style: TextStyle(fontWeight: FontWeight.w900)),
    );
  }

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

  Widget _categoryFilter() {
    return DropdownButtonFormField<String>(
      value: _category,
      isExpanded: true,
      decoration: _inputDecoration('Category', Icons.category_outlined),
      items: <DropdownMenuItem<String>>[
        const DropdownMenuItem(value: '', child: Text('All categories')),
        ...CampusClubsService.categories.map(
          (item) => DropdownMenuItem(value: item, child: Text(item, overflow: TextOverflow.ellipsis)),
        ),
      ],
      onChanged: (value) {
        setState(() => _category = 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(
          (item) => DropdownMenuItem(value: item, child: Text(item, overflow: TextOverflow.ellipsis)),
        ),
      ],
      onChanged: (value) {
        setState(() => _campus = value ?? '');
        _load();
      },
    );
  }

  Widget _metric(IconData icon, String value, String label) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 11, 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, color: _green, size: 16),
          const SizedBox(width: 6),
          Text(value, style: const TextStyle(color: _ink, fontWeight: FontWeight.w900)),
          const SizedBox(width: 5),
          Flexible(
            child: Text(
              label,
              overflow: TextOverflow.ellipsis,
              style: const TextStyle(color: _muted, fontSize: 10.2),
            ),
          ),
        ],
      ),
    );
  }

  InputDecoration _inputDecoration(String hint, IconData icon) {
    return InputDecoration(
      hintText: hint,
      prefixIcon: Icon(icon, color: _green, size: 19),
      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 _errorCard() {
    return _centerCard(
      icon: Icons.cloud_off_rounded,
      iconColor: Colors.red.shade300,
      title: 'Club directory could not be loaded',
      message: _error ?? 'Unknown error.',
      action: FilledButton.icon(
        onPressed: () => _load(initial: true),
        style: FilledButton.styleFrom(backgroundColor: _green),
        icon: const Icon(Icons.refresh_rounded),
        label: const Text('Try again'),
      ),
    );
  }

  Widget _emptyCard() {
    return _centerCard(
      icon: Icons.groups_outlined,
      iconColor: Colors.grey.shade300,
      title: 'No approved clubs found',
      message: widget.currentUser.isAdmin
          ? 'No clubs match the selected campus, category or search.'
          : 'There are no approved clubs for your campus yet. You can register the first club.',
      action: FilledButton.icon(
        onPressed: widget.currentUser.isAdmin || widget.currentUser.campus.isNotEmpty
            ? _createClub
            : null,
        style: FilledButton.styleFrom(backgroundColor: _green),
        icon: const Icon(Icons.add_rounded),
        label: const Text('Register Club'),
      ),
    );
  }

  Widget _centerCard({
    required IconData icon,
    required Color iconColor,
    required String title,
    required String message,
    required Widget action,
  }) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 78),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(20),
        border: Border.all(color: _border),
      ),
      child: Column(
        children: [
          Icon(icon, size: 62, color: iconColor),
          const SizedBox(height: 14),
          Text(
            title,
            textAlign: TextAlign.center,
            style: const TextStyle(color: _ink, fontSize: 18, fontWeight: FontWeight.w900),
          ),
          const SizedBox(height: 7),
          Text(
            message,
            textAlign: TextAlign.center,
            style: const TextStyle(color: _muted, height: 1.5),
          ),
          const SizedBox(height: 18),
          action,
        ],
      ),
    );
  }
}

class _ClubGroup extends StatelessWidget {
  final String title;
  final List<CampusClub> clubs;
  final bool adminGrouping;
  final ValueChanged<CampusClub> onOpen;

  const _ClubGroup({
    required this.title,
    required this.clubs,
    required this.adminGrouping,
    required this.onOpen,
  });

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        final columns = constraints.maxWidth >= 1120
            ? 3
            : constraints.maxWidth >= 720
                ? 2
                : 1;
        final ratio = columns == 1 ? 1.95 : (columns == 2 ? 1.35 : 1.18);
        return Padding(
          padding: const EdgeInsets.only(bottom: 24),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Container(
                    width: 34,
                    height: 34,
                    decoration: BoxDecoration(
                      color: _green.withOpacity(.08),
                      borderRadius: BorderRadius.circular(10),
                    ),
                    child: Icon(
                      adminGrouping ? Icons.location_city_outlined : Icons.category_outlined,
                      color: _green,
                      size: 18,
                    ),
                  ),
                  const SizedBox(width: 10),
                  Expanded(
                    child: Text(
                      title,
                      style: const TextStyle(color: _ink, fontSize: 16, fontWeight: FontWeight.w900),
                    ),
                  ),
                  Container(
                    padding: const EdgeInsets.symmetric(horizontal: 9, vertical: 5),
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(20),
                      border: Border.all(color: _border),
                    ),
                    child: Text(
                      '${clubs.length} ${clubs.length == 1 ? 'club' : 'clubs'}',
                      style: const TextStyle(color: _muted, fontSize: 10.5, fontWeight: FontWeight.w700),
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 11),
              GridView.builder(
                shrinkWrap: true,
                physics: const NeverScrollableScrollPhysics(),
                itemCount: clubs.length,
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: columns,
                  crossAxisSpacing: 12,
                  mainAxisSpacing: 12,
                  childAspectRatio: ratio,
                ),
                itemBuilder: (context, index) => _ClubCard(
                  club: clubs[index],
                  onTap: () => onOpen(clubs[index]),
                ),
              ),
            ],
          ),
        );
      },
    );
  }
}

class _ClubCard extends StatelessWidget {
  final CampusClub club;
  final VoidCallback onTap;

  const _ClubCard({required this.club, required this.onTap});

  @override
  Widget build(BuildContext context) {
    final initials = _initials(club.name);
    return Material(
      color: Colors.white,
      borderRadius: BorderRadius.circular(18),
      child: InkWell(
        borderRadius: BorderRadius.circular(18),
        onTap: onTap,
        child: Container(
          padding: const EdgeInsets.all(15),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(18),
            border: Border.all(color: _border),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(.025),
                blurRadius: 12,
                offset: const Offset(0, 4),
              ),
            ],
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Container(
                    width: 48,
                    height: 48,
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      color: _green,
                      borderRadius: BorderRadius.circular(14),
                    ),
                    child: Text(
                      initials,
                      style: const TextStyle(
                        color: Colors.white,
                        fontWeight: FontWeight.w900,
                        fontSize: 15,
                      ),
                    ),
                  ),
                  const SizedBox(width: 11),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          club.name,
                          maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                          style: const TextStyle(
                            color: _ink,
                            fontSize: 14.5,
                            height: 1.2,
                            fontWeight: FontWeight.w900,
                          ),
                        ),
                        if (club.acronym.trim().isNotEmpty) ...[
                          const SizedBox(height: 3),
                          Text(
                            club.acronym.toUpperCase(),
                            style: const TextStyle(
                              color: _gold,
                              fontSize: 10.5,
                              fontWeight: FontWeight.w900,
                              letterSpacing: .7,
                            ),
                          ),
                        ],
                      ],
                    ),
                  ),
                  const Icon(Icons.chevron_right_rounded, color: _green),
                ],
              ),
              const SizedBox(height: 11),
              Text(
                club.purpose.trim().isEmpty ? club.description : club.purpose,
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
                style: const TextStyle(color: _muted, fontSize: 11.3, height: 1.4),
              ),
              const Spacer(),
              Wrap(
                spacing: 6,
                runSpacing: 5,
                children: [
                  _miniChip(Icons.category_outlined, club.category),
                  _miniChip(Icons.people_alt_outlined, '${club.memberCount} members'),
                  _miniChip(Icons.description_outlined, '${club.documentCount} docs'),
                ],
              ),
              const SizedBox(height: 9),
              Row(
                children: [
                  const Icon(Icons.location_on_outlined, size: 14, color: _green),
                  const SizedBox(width: 4),
                  Expanded(
                    child: Text(
                      club.campus,
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: const TextStyle(color: _muted, fontSize: 10.5, fontWeight: FontWeight.w700),
                    ),
                  ),
                  if (club.patronName.trim().isNotEmpty)
                    Flexible(
                      child: Text(
                        'Patron: ${club.patronName}',
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: const TextStyle(color: _muted, fontSize: 9.8),
                      ),
                    ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Widget _miniChip(IconData icon, String label) {
  return Container(
    padding: const EdgeInsets.symmetric(horizontal: 7, vertical: 5),
    decoration: BoxDecoration(
      color: const Color(0xFFF7F9F8),
      borderRadius: BorderRadius.circular(20),
      border: Border.all(color: _border),
    ),
    child: Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Icon(icon, size: 12, color: _green),
        const SizedBox(width: 4),
        ConstrainedBox(
          constraints: const BoxConstraints(maxWidth: 150),
          child: Text(
            label,
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: const TextStyle(color: _muted, fontSize: 9.7, fontWeight: FontWeight.w600),
          ),
        ),
      ],
    ),
  );
}

class _ClubEditorDialog extends StatefulWidget {
  final ClubCurrentUser currentUser;
  final CampusClub? club;
  final List<String> campuses;

  const _ClubEditorDialog({
    required this.currentUser,
    required this.campuses,
    this.club,
  });

  @override
  State<_ClubEditorDialog> createState() => _ClubEditorDialogState();
}

class _ClubEditorDialogState extends State<_ClubEditorDialog> {
  final _formKey = GlobalKey<FormState>();
  late final TextEditingController _name;
  late final TextEditingController _acronym;
  late final TextEditingController _purpose;
  late final TextEditingController _description;
  late final TextEditingController _patron;
  late final TextEditingController _email;
  late final TextEditingController _phone;
  late final TextEditingController _schedule;
  late final TextEditingController _venue;
  late String _category;
  late String _campus;
  bool _saving = false;

  @override
  void initState() {
    super.initState();
    final club = widget.club;
    _name = TextEditingController(text: club?.name ?? '');
    _acronym = TextEditingController(text: club?.acronym ?? '');
    _purpose = TextEditingController(text: club?.purpose ?? '');
    _description = TextEditingController(text: club?.description ?? '');
    _patron = TextEditingController(text: club?.patronName ?? '');
    _email = TextEditingController(text: club?.contactEmail ?? widget.currentUser.email);
    _phone = TextEditingController(text: club?.contactPhone ?? widget.currentUser.phone);
    _schedule = TextEditingController(text: club?.meetingSchedule ?? '');
    _venue = TextEditingController(text: club?.meetingVenue ?? '');
    _category = club?.category ?? CampusClubsService.categories.first;
    _campus = club?.campus ?? widget.currentUser.campus;
    if (widget.currentUser.isAdmin && _campus.isEmpty && widget.campuses.isNotEmpty) {
      _campus = widget.campuses.first;
    }
  }

  @override
  void dispose() {
    for (final controller in <TextEditingController>[
      _name,
      _acronym,
      _purpose,
      _description,
      _patron,
      _email,
      _phone,
      _schedule,
      _venue,
    ]) {
      controller.dispose();
    }
    super.dispose();
  }

  Future<void> _save() async {
    if (_saving || !(_formKey.currentState?.validate() ?? false)) return;
    setState(() => _saving = true);
    try {
      final data = <String, dynamic>{
        'name': _name.text.trim(),
        'acronym': _acronym.text.trim(),
        'category': _category,
        'purpose': _purpose.text.trim(),
        'description': _description.text.trim(),
        'patron_name': _patron.text.trim(),
        'contact_email': _email.text.trim(),
        'contact_phone': _phone.text.trim(),
        'meeting_schedule': _schedule.text.trim(),
        'meeting_venue': _venue.text.trim(),
        if (widget.currentUser.isAdmin) 'campus': _campus,
      };
      if (widget.club == null) {
        await CampusClubsService.createClub(data);
      } else {
        await CampusClubsService.updateClub(widget.club!.id, data);
      }
      if (!mounted) return;
      Navigator.pop(context, true);
    } catch (e) {
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          backgroundColor: Colors.red.shade700,
          content: Text(e.toString().replaceFirst('Exception: ', '')),
        ),
      );
    } finally {
      if (mounted) setState(() => _saving = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    final compact = MediaQuery.of(context).size.width < 700;
    return Dialog(
      insetPadding: EdgeInsets.symmetric(horizontal: compact ? 8 : 28, vertical: compact ? 12 : 24),
      backgroundColor: Colors.white,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(22)),
      child: ConstrainedBox(
        constraints: const BoxConstraints(maxWidth: 820, maxHeight: 820),
        child: Column(
          children: [
            _dialogHeader(
              icon: widget.club == null ? Icons.add_business_rounded : Icons.edit_rounded,
              title: widget.club == null ? 'Register a Club' : 'Edit Club Profile',
              subtitle: widget.currentUser.isAdmin
                  ? 'Create or update a club in the University-wide registry.'
                  : 'Your campus is attached automatically from your signed-in staff account.',
              onClose: _saving ? null : () => Navigator.pop(context),
            ),
            Expanded(
              child: SingleChildScrollView(
                padding: EdgeInsets.all(compact ? 15 : 24),
                child: Form(
                  key: _formKey,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      _campusBanner(),
                      const SizedBox(height: 18),
                      if (compact)
                        Column(
                          children: [
                            _textField(_name, 'Club name', 'E.g. Rockview Debate Society', Icons.groups_outlined, required: true),
                            const SizedBox(height: 12),
                            _textField(_acronym, 'Acronym', 'Optional, e.g. RDS', Icons.short_text_rounded),
                          ],
                        )
                      else
                        Row(
                          children: [
                            Expanded(flex: 2, child: _textField(_name, 'Club name', 'E.g. Rockview Debate Society', Icons.groups_outlined, required: true)),
                            const SizedBox(width: 12),
                            Expanded(child: _textField(_acronym, 'Acronym', 'Optional, e.g. RDS', Icons.short_text_rounded)),
                          ],
                        ),
                      const SizedBox(height: 12),
                      DropdownButtonFormField<String>(
                        value: _category,
                        isExpanded: true,
                        decoration: _fieldDecoration('Club category', null, Icons.category_outlined),
                        items: CampusClubsService.categories
                            .map((value) => DropdownMenuItem(value: value, child: Text(value)))
                            .toList(),
                        onChanged: (value) {
                          if (value != null) setState(() => _category = value);
                        },
                      ),
                      const SizedBox(height: 12),
                      _textField(_purpose, 'Purpose / mandate', 'State the main purpose of the club.', Icons.flag_outlined, required: true, minLines: 3, maxLines: 5),
                      const SizedBox(height: 12),
                      _textField(_description, 'Club profile', 'Describe activities, objectives and who the club serves.', Icons.notes_rounded, minLines: 4, maxLines: 7),
                      const SizedBox(height: 12),
                      if (compact)
                        Column(
                          children: [
                            _textField(_patron, 'Patron / adviser', 'Optional', Icons.person_outline_rounded),
                            const SizedBox(height: 12),
                            _textField(_venue, 'Meeting venue', 'E.g. Lecture Room 4', Icons.place_outlined),
                          ],
                        )
                      else
                        Row(
                          children: [
                            Expanded(child: _textField(_patron, 'Patron / adviser', 'Optional', Icons.person_outline_rounded)),
                            const SizedBox(width: 12),
                            Expanded(child: _textField(_venue, 'Meeting venue', 'E.g. Lecture Room 4', Icons.place_outlined)),
                          ],
                        ),
                      const SizedBox(height: 12),
                      _textField(_schedule, 'Meeting schedule', 'E.g. Fridays, 16:00 - 17:30', Icons.schedule_outlined),
                      const SizedBox(height: 12),
                      if (compact)
                        Column(
                          children: [
                            _textField(_email, 'Club contact email', 'Optional', Icons.email_outlined),
                            const SizedBox(height: 12),
                            _textField(_phone, 'Club contact phone', 'Optional', Icons.phone_outlined),
                          ],
                        )
                      else
                        Row(
                          children: [
                            Expanded(child: _textField(_email, 'Club contact email', 'Optional', Icons.email_outlined)),
                            const SizedBox(width: 12),
                            Expanded(child: _textField(_phone, 'Club contact phone', 'Optional', Icons.phone_outlined)),
                          ],
                        ),
                    ],
                  ),
                ),
              ),
            ),
            Container(
              padding: EdgeInsets.fromLTRB(compact ? 15 : 22, 12, compact ? 15 : 22, compact ? 15 : 20),
              decoration: const BoxDecoration(border: Border(top: BorderSide(color: _border))),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  TextButton(onPressed: _saving ? null : () => Navigator.pop(context), child: const Text('Cancel')),
                  const SizedBox(width: 9),
                  FilledButton.icon(
                    onPressed: _saving ? null : _save,
                    style: FilledButton.styleFrom(backgroundColor: _green, padding: const EdgeInsets.symmetric(horizontal: 19, vertical: 14)),
                    icon: _saving
                        ? const SizedBox(width: 17, height: 17, child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white))
                        : const Icon(Icons.save_outlined, size: 18),
                    label: Text(_saving ? 'Saving...' : (widget.club == null ? 'Submit Club' : 'Save Changes')),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _campusBanner() {
    if (widget.currentUser.isAdmin) {
      final values = <String>{...widget.campuses};
      if (_campus.isNotEmpty) values.add(_campus);
      final list = values.toList()..sort();
      return DropdownButtonFormField<String>(
        value: _campus.isEmpty ? null : _campus,
        isExpanded: true,
        decoration: _fieldDecoration('Campus', null, Icons.location_city_outlined),
        items: list.map((value) => DropdownMenuItem(value: value, child: Text(value))).toList(),
        validator: (value) => value == null || value.trim().isEmpty ? 'Select a campus.' : null,
        onChanged: (value) {
          if (value != null) setState(() => _campus = value);
        },
      );
    }

    return Container(
      padding: const EdgeInsets.all(13),
      decoration: BoxDecoration(
        color: _green.withOpacity(.05),
        borderRadius: BorderRadius.circular(13),
        border: Border.all(color: _green.withOpacity(.14)),
      ),
      child: Row(
        children: [
          const Icon(Icons.verified_user_outlined, color: _green),
          const SizedBox(width: 10),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text('Authenticated campus', style: TextStyle(color: _muted, fontSize: 10.5, fontWeight: FontWeight.w700)),
                const SizedBox(height: 2),
                Text(
                  widget.currentUser.campus.isEmpty ? 'Campus not assigned' : widget.currentUser.campus,
                  style: const TextStyle(color: _ink, fontWeight: FontWeight.w900),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

class ClubDetailsDialog extends StatefulWidget {
  final int clubId;
  final ClubCurrentUser currentUser;
  final List<String> campuses;

  const ClubDetailsDialog({
    required this.clubId,
    required this.currentUser,
    required this.campuses,
  });

  @override
  State<ClubDetailsDialog> createState() => _ClubDetailsDialogState();
}

class _ClubDetailsDialogState extends State<ClubDetailsDialog> {
  CampusClub? _club;
  List<ClubMember> _members = <ClubMember>[];
  List<ClubDocument> _documents = <ClubDocument>[];
  bool _loading = true;
  bool _busy = false;
  String? _error;

  bool get _canManage =>
      _club != null && (widget.currentUser.isAdmin || _club!.createdBy == widget.currentUser.id);

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

  Future<void> _load() async {
    if (!mounted) return;
    setState(() {
      _loading = true;
      _error = null;
    });
    try {
      final results = await Future.wait<dynamic>([
        CampusClubsService.getClub(widget.clubId),
        CampusClubsService.getMembers(widget.clubId),
        CampusClubsService.getDocuments(widget.clubId),
      ]);
      if (!mounted) return;
      setState(() {
        _club = results[0] as CampusClub;
        _members = List<ClubMember>.from(results[1] as List);
        _documents = List<ClubDocument>.from(results[2] as List);
        _loading = false;
      });
    } catch (e) {
      if (!mounted) return;
      setState(() {
        _loading = false;
        _error = e.toString().replaceFirst('Exception: ', '');
      });
    }
  }

  Future<void> _editClub() async {
    final club = _club;
    if (club == null) return;
    final changed = await showDialog<bool>(
      context: context,
      barrierDismissible: false,
      builder: (_) => _ClubEditorDialog(
        currentUser: widget.currentUser,
        campuses: widget.campuses,
        club: club,
      ),
    );
    if (changed == true) await _load();
  }

  Future<void> _deleteClub() async {
    final club = _club;
    if (club == null || _busy) return;
    final yes = await showDialog<bool>(
      context: context,
      builder: (_) => AlertDialog(
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(18)),
        title: const Text('Delete club permanently?'),
        content: Text('This will remove "${club.name}", its membership list and stored club documents.'),
        actions: [
          TextButton(onPressed: () => Navigator.pop(context, false), child: const Text('Cancel')),
          FilledButton(
            style: FilledButton.styleFrom(backgroundColor: Colors.red.shade700),
            onPressed: () => Navigator.pop(context, true),
            child: const Text('Delete permanently'),
          ),
        ],
      ),
    );
    if (yes != true) return;
    setState(() => _busy = true);
    try {
      await CampusClubsService.deleteClub(club.id);
      if (!mounted) return;
      Navigator.pop(context, true);
    } catch (e) {
      _snack(e.toString().replaceFirst('Exception: ', ''), error: true);
    } finally {
      if (mounted) setState(() => _busy = false);
    }
  }

  Future<void> _addOrEditMember({ClubMember? member}) async {
    final changed = await showDialog<bool>(
      context: context,
      barrierDismissible: false,
      builder: (_) => _MemberEditorDialog(clubId: widget.clubId, member: member),
    );
    if (changed == true) await _load();
  }

  Future<void> _removeMember(ClubMember member) async {
    final yes = await showDialog<bool>(
      context: context,
      builder: (_) => AlertDialog(
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(18)),
        title: const Text('Remove member?'),
        content: Text('Remove ${member.fullName} from this club?'),
        actions: [
          TextButton(onPressed: () => Navigator.pop(context, false), child: const Text('Cancel')),
          FilledButton(
            style: FilledButton.styleFrom(backgroundColor: Colors.red.shade700),
            onPressed: () => Navigator.pop(context, true),
            child: const Text('Remove'),
          ),
        ],
      ),
    );
    if (yes != true) return;
    try {
      await CampusClubsService.removeMember(member.id);
      await _load();
    } catch (e) {
      _snack(e.toString().replaceFirst('Exception: ', ''), error: true);
    }
  }

  Future<List<ClubLocalDocument>> _pickLocalDocuments() async {
    final List<PlatformFile> files;
    try {
      files = await FilePicker.pickFiles(
        type: FileType.custom,
        allowedExtensions: const ['pdf', 'txt', 'doc', 'docx', 'xls', 'xlsx'],
      );
    } catch (e) {
      _snack('Unable to open the document picker: $e', error: true);
      return const <ClubLocalDocument>[];
    }
    if (files.isEmpty || !mounted) return const <ClubLocalDocument>[];

    final selected = <ClubLocalDocument>[];
    for (final item in files) {
      final path = (item.path ?? '').trim();
      var name = item.name.trim();
      if (name.isEmpty && path.isNotEmpty) {
        name = path.split(Platform.pathSeparator).last;
      }
      if (path.isEmpty || name.isEmpty) continue;
      final local = File(path);
      if (!await local.exists()) continue;
      if (await local.length() > 10 * 1024 * 1024) {
        _snack('$name is larger than 10 MB.', error: true);
        continue;
      }
      selected.add(ClubLocalDocument(name: name, path: path));
      if (selected.length == 5) break;
    }
    return selected;
  }

  Future<void> _uploadDocuments() async {
    final local = await _pickLocalDocuments();
    if (local.isEmpty || !mounted) return;
    String documentType = CampusClubsService.documentTypes.first;
    final type = await showDialog<String>(
      context: context,
      builder: (dialogContext) => StatefulBuilder(
        builder: (context, setDialogState) => AlertDialog(
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(18)),
          title: const Text('Classify club documents'),
          content: SizedBox(
            width: 430,
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text('${local.length} file${local.length == 1 ? '' : 's'} selected.', style: const TextStyle(color: _muted)),
                const SizedBox(height: 14),
                DropdownButtonFormField<String>(
                  value: documentType,
                  isExpanded: true,
                  decoration: _fieldDecoration('Document type', null, Icons.description_outlined),
                  items: CampusClubsService.documentTypes
                      .map((value) => DropdownMenuItem(value: value, child: Text(value)))
                      .toList(),
                  onChanged: (value) {
                    if (value != null) setDialogState(() => documentType = value);
                  },
                ),
              ],
            ),
          ),
          actions: [
            TextButton(onPressed: () => Navigator.pop(dialogContext), child: const Text('Cancel')),
            FilledButton(
              style: FilledButton.styleFrom(backgroundColor: _green),
              onPressed: () => Navigator.pop(dialogContext, documentType),
              child: const Text('Upload'),
            ),
          ],
        ),
      ),
    );
    if (type == null) return;
    setState(() => _busy = true);
    try {
      await CampusClubsService.uploadDocuments(
        clubId: widget.clubId,
        documentType: type,
        documents: local,
      );
      await _load();
      _snack('Club documents uploaded successfully.');
    } catch (e) {
      _snack(e.toString().replaceFirst('Exception: ', ''), error: true);
    } finally {
      if (mounted) setState(() => _busy = false);
    }
  }

  Future<void> _downloadDocument(ClubDocument document) async {
    _snack('Downloading ${document.originalName}...');
    try {
      final path = await CampusClubsService.downloadDocument(document);
      if (!mounted) return;
      final open = await showDialog<bool>(
        context: context,
        builder: (_) => AlertDialog(
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(18)),
          title: const Text('Document downloaded'),
          content: SelectableText('Saved to:\n$path'),
          actions: [
            TextButton(onPressed: () => Navigator.pop(context, false), child: const Text('Close')),
            FilledButton.icon(
              style: FilledButton.styleFrom(backgroundColor: _green),
              onPressed: () => Navigator.pop(context, true),
              icon: const Icon(Icons.open_in_new_rounded, size: 17),
              label: const Text('Open file'),
            ),
          ],
        ),
      );
      if (open == true) await CampusClubsService.openDownloadedDocument(path);
    } catch (e) {
      _snack(e.toString().replaceFirst('Exception: ', ''), error: true);
    }
  }

  Future<void> _deleteDocument(ClubDocument document) async {
    final yes = await showDialog<bool>(
      context: context,
      builder: (_) => AlertDialog(
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(18)),
        title: const Text('Remove document?'),
        content: Text('Remove "${document.originalName}" from the club registry?'),
        actions: [
          TextButton(onPressed: () => Navigator.pop(context, false), child: const Text('Cancel')),
          FilledButton(
            style: FilledButton.styleFrom(backgroundColor: Colors.red.shade700),
            onPressed: () => Navigator.pop(context, true),
            child: const Text('Remove'),
          ),
        ],
      ),
    );
    if (yes != true) return;
    try {
      await CampusClubsService.deleteDocument(document.id);
      await _load();
    } catch (e) {
      _snack(e.toString().replaceFirst('Exception: ', ''), error: true);
    }
  }

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

  @override
  Widget build(BuildContext context) {
    final compact = MediaQuery.of(context).size.width < 760;
    return Dialog(
      insetPadding: EdgeInsets.symmetric(horizontal: compact ? 5 : 20, vertical: compact ? 8 : 20),
      backgroundColor: Colors.white,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(compact ? 16 : 22)),
      child: ConstrainedBox(
        constraints: const BoxConstraints(maxWidth: 1080, maxHeight: 850),
        child: _loading
            ? const Center(child: Padding(padding: EdgeInsets.all(80), child: CircularProgressIndicator(color: _green)))
            : _error != null || _club == null
                ? Center(
                    child: Padding(
                      padding: const EdgeInsets.all(28),
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Icon(Icons.error_outline_rounded, size: 50, color: Colors.red.shade300),
                          const SizedBox(height: 12),
                          Text(_error ?? 'Club could not be loaded.', textAlign: TextAlign.center),
                          const SizedBox(height: 14),
                          FilledButton.icon(onPressed: _load, style: FilledButton.styleFrom(backgroundColor: _green), icon: const Icon(Icons.refresh), label: const Text('Try again')),
                        ],
                      ),
                    ),
                  )
                : DefaultTabController(
                    length: 3,
                    child: Column(
                      children: [
                        _detailsHeader(compact),
                        const TabBar(
                          labelColor: _green,
                          unselectedLabelColor: _muted,
                          indicatorColor: _gold,
                          indicatorWeight: 3,
                          tabs: [
                            Tab(icon: Icon(Icons.info_outline_rounded, size: 18), text: 'Overview'),
                            Tab(icon: Icon(Icons.people_alt_outlined, size: 18), text: 'Members'),
                            Tab(icon: Icon(Icons.description_outlined, size: 18), text: 'Documents'),
                          ],
                        ),
                        Expanded(
                          child: TabBarView(
                            children: [
                              _overviewTab(compact),
                              _membersTab(compact),
                              _documentsTab(compact),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
      ),
    );
  }

  Widget _detailsHeader(bool compact) {
    final club = _club!;
    return Container(
      padding: EdgeInsets.fromLTRB(compact ? 14 : 22, compact ? 14 : 20, compact ? 9 : 14, compact ? 12 : 16),
      decoration: const BoxDecoration(color: _green, borderRadius: BorderRadius.vertical(top: Radius.circular(20))),
      child: Row(
        children: [
          Container(
            width: compact ? 43 : 52,
            height: compact ? 43 : 52,
            alignment: Alignment.center,
            decoration: BoxDecoration(color: Colors.white.withOpacity(.14), borderRadius: BorderRadius.circular(15)),
            child: Text(_initials(club.name), style: TextStyle(color: Colors.white, fontWeight: FontWeight.w900, fontSize: compact ? 13 : 16)),
          ),
          const SizedBox(width: 12),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(club.name, maxLines: 2, overflow: TextOverflow.ellipsis, style: TextStyle(color: Colors.white, fontWeight: FontWeight.w900, fontSize: compact ? 15 : 19)),
                const SizedBox(height: 3),
                Text('${club.campus} • ${club.category}', maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle(color: Color(0xFFE7F3EC), fontSize: 10.5)),
              ],
            ),
          ),
          if (_canManage)
            PopupMenuButton<String>(
              tooltip: 'Club management',
              color: Colors.white,
              icon: const Icon(Icons.more_vert_rounded, color: Colors.white),
              onSelected: (value) {
                if (value == 'edit') _editClub();
                if (value == 'delete') _deleteClub();
              },
              itemBuilder: (_) => [
                const PopupMenuItem(value: 'edit', child: ListTile(leading: Icon(Icons.edit_outlined), title: Text('Edit club'), dense: true)),
                const PopupMenuItem(value: 'delete', child: ListTile(leading: Icon(Icons.delete_outline, color: Colors.red), title: Text('Delete club', style: TextStyle(color: Colors.red)), dense: true)),
              ],
            ),
          IconButton(onPressed: () => Navigator.pop(context), icon: const Icon(Icons.close_rounded, color: Colors.white)),
        ],
      ),
    );
  }

  Widget _overviewTab(bool compact) {
    final club = _club!;
    return ListView(
      padding: EdgeInsets.all(compact ? 14 : 24),
      children: [
        if (compact)
          Column(
            children: [
              _overviewMetric(Icons.people_alt_outlined, '${_members.where((m) => m.status == 'active').length}', 'Registered members'),
              const SizedBox(height: 8),
              _overviewMetric(Icons.description_outlined, '${_documents.length}', 'Club documents'),
            ],
          )
        else
          Row(
            children: [
              Expanded(child: _overviewMetric(Icons.people_alt_outlined, '${_members.where((m) => m.status == 'active').length}', 'Registered members')),
              const SizedBox(width: 10),
              Expanded(child: _overviewMetric(Icons.description_outlined, '${_documents.length}', 'Club documents')),
              const SizedBox(width: 10),
              Expanded(child: _overviewMetric(Icons.verified_outlined, club.status.toUpperCase(), 'Registry status')),
            ],
          ),
        const SizedBox(height: 18),
        _section('Purpose / mandate', club.purpose, Icons.flag_outlined),
        if (club.description.trim().isNotEmpty) ...[
          const SizedBox(height: 12),
          _section('Club profile', club.description, Icons.notes_rounded),
        ],
        const SizedBox(height: 12),
        Wrap(
          spacing: 10,
          runSpacing: 10,
          children: [
            _infoTile(Icons.location_city_outlined, 'Campus', club.campus),
            _infoTile(Icons.category_outlined, 'Category', club.category),
            _infoTile(Icons.person_outline_rounded, 'Patron / adviser', club.patronName.isEmpty ? 'Not recorded' : club.patronName),
            _infoTile(Icons.schedule_outlined, 'Meeting schedule', club.meetingSchedule.isEmpty ? 'Not recorded' : club.meetingSchedule),
            _infoTile(Icons.place_outlined, 'Meeting venue', club.meetingVenue.isEmpty ? 'Not recorded' : club.meetingVenue),
            _infoTile(Icons.manage_accounts_outlined, 'Registered by', club.creatorName),
            _infoTile(Icons.email_outlined, 'Contact email', club.contactEmail.isEmpty ? 'Not recorded' : club.contactEmail),
            _infoTile(Icons.phone_outlined, 'Contact phone', club.contactPhone.isEmpty ? 'Not recorded' : club.contactPhone),
          ],
        ),
      ],
    );
  }

  Widget _membersTab(bool compact) {
    return Column(
      children: [
        Padding(
          padding: EdgeInsets.fromLTRB(compact ? 12 : 20, 14, compact ? 12 : 20, 10),
          child: Row(
            children: [
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text('Club Membership Register', style: TextStyle(color: _ink, fontWeight: FontWeight.w900, fontSize: 15)),
                    Text('${_members.length} recorded member${_members.length == 1 ? '' : 's'}', style: const TextStyle(color: _muted, fontSize: 10.5)),
                  ],
                ),
              ),
              if (_canManage)
                FilledButton.icon(
                  onPressed: () => _addOrEditMember(),
                  style: FilledButton.styleFrom(backgroundColor: _green),
                  icon: const Icon(Icons.person_add_alt_1_rounded, size: 17),
                  label: Text(compact ? 'Add' : 'Add Member'),
                ),
            ],
          ),
        ),
        const Divider(height: 1, color: _border),
        Expanded(
          child: _members.isEmpty
              ? _tabEmpty(Icons.group_add_outlined, 'No members recorded', _canManage ? 'Add the first member to this club register.' : 'The club creator has not added members yet.')
              : ListView.separated(
                  padding: EdgeInsets.all(compact ? 10 : 18),
                  itemCount: _members.length,
                  separatorBuilder: (_, __) => const SizedBox(height: 8),
                  itemBuilder: (context, index) {
                    final member = _members[index];
                    return Container(
                      padding: const EdgeInsets.all(12),
                      decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(14), border: Border.all(color: _border)),
                      child: Row(
                        children: [
                          CircleAvatar(
                            backgroundColor: _green.withOpacity(.09),
                            foregroundColor: _green,
                            child: Text(_initials(member.fullName), style: const TextStyle(fontWeight: FontWeight.w900, fontSize: 11)),
                          ),
                          const SizedBox(width: 11),
                          Expanded(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(member.fullName, style: const TextStyle(color: _ink, fontWeight: FontWeight.w900, fontSize: 13.5)),
                                const SizedBox(height: 4),
                                Wrap(
                                  spacing: 8,
                                  runSpacing: 4,
                                  children: [
                                    _inlineMeta(Icons.badge_outlined, member.clubRole),
                                    _inlineMeta(Icons.person_outline_rounded, member.memberType),
                                    if (member.memberNumber.isNotEmpty) _inlineMeta(Icons.numbers_rounded, member.memberNumber),
                                    if (member.phone.isNotEmpty) _inlineMeta(Icons.phone_outlined, member.phone),
                                  ],
                                ),
                              ],
                            ),
                          ),
                          if (_canManage)
                            PopupMenuButton<String>(
                              onSelected: (value) {
                                if (value == 'edit') _addOrEditMember(member: member);
                                if (value == 'remove') _removeMember(member);
                              },
                              itemBuilder: (_) => const [
                                PopupMenuItem(value: 'edit', child: Text('Edit member')),
                                PopupMenuItem(value: 'remove', child: Text('Remove member', style: TextStyle(color: Colors.red))),
                              ],
                            ),
                        ],
                      ),
                    );
                  },
                ),
        ),
      ],
    );
  }

  Widget _documentsTab(bool compact) {
    return Column(
      children: [
        Padding(
          padding: EdgeInsets.fromLTRB(compact ? 12 : 20, 14, compact ? 12 : 20, 10),
          child: Row(
            children: [
              const Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text('Official Club Documents', style: TextStyle(color: _ink, fontWeight: FontWeight.w900, fontSize: 15)),
                    Text('Constitutions, rules, registration papers and club records.', style: TextStyle(color: _muted, fontSize: 10.5)),
                  ],
                ),
              ),
              if (_canManage)
                FilledButton.icon(
                  onPressed: _busy ? null : _uploadDocuments,
                  style: FilledButton.styleFrom(backgroundColor: _green),
                  icon: const Icon(Icons.upload_file_rounded, size: 17),
                  label: Text(compact ? 'Upload' : 'Upload Documents'),
                ),
            ],
          ),
        ),
        const Divider(height: 1, color: _border),
        Expanded(
          child: _documents.isEmpty
              ? _tabEmpty(Icons.description_outlined, 'No club documents', _canManage ? 'Upload the club constitution, rules or another official document.' : 'No official club documents have been uploaded yet.')
              : ListView.separated(
                  padding: EdgeInsets.all(compact ? 10 : 18),
                  itemCount: _documents.length,
                  separatorBuilder: (_, __) => const SizedBox(height: 8),
                  itemBuilder: (context, index) {
                    final document = _documents[index];
                    return Container(
                      padding: const EdgeInsets.all(12),
                      decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(14), border: Border.all(color: _border)),
                      child: Row(
                        children: [
                          Container(
                            width: 43,
                            height: 43,
                            decoration: BoxDecoration(color: _green.withOpacity(.08), borderRadius: BorderRadius.circular(12)),
                            child: Icon(_documentIcon(document.originalName), color: _green),
                          ),
                          const SizedBox(width: 11),
                          Expanded(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(document.originalName, maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle(color: _ink, fontWeight: FontWeight.w900, fontSize: 12.8)),
                                const SizedBox(height: 3),
                                Text('${document.documentType} • ${_formatBytes(document.fileSize)} • ${_date(document.createdAt)}', maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle(color: _muted, fontSize: 9.8)),
                              ],
                            ),
                          ),
                          IconButton(
                            tooltip: 'Download',
                            onPressed: () => _downloadDocument(document),
                            icon: const Icon(Icons.download_rounded, color: _green),
                          ),
                          if (_canManage)
                            IconButton(
                              tooltip: 'Remove',
                              onPressed: () => _deleteDocument(document),
                              icon: Icon(Icons.delete_outline_rounded, color: Colors.red.shade400),
                            ),
                        ],
                      ),
                    );
                  },
                ),
        ),
      ],
    );
  }

  Widget _overviewMetric(IconData icon, String value, String label) {
    return Container(
      padding: const EdgeInsets.all(14),
      decoration: BoxDecoration(color: const Color(0xFFF8FAF9), borderRadius: BorderRadius.circular(14), border: Border.all(color: _border)),
      child: Row(
        children: [
          Icon(icon, color: _green),
          const SizedBox(width: 10),
          Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [Text(value, maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle(color: _ink, fontWeight: FontWeight.w900, fontSize: 16)), Text(label, style: const TextStyle(color: _muted, fontSize: 10))])),
        ],
      ),
    );
  }

  Widget _section(String title, String value, IconData icon) {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(15),
      decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(14), border: Border.all(color: _border)),
      child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [Row(children: [Icon(icon, size: 18, color: _green), const SizedBox(width: 7), Text(title, style: const TextStyle(color: _ink, fontWeight: FontWeight.w900))]), const SizedBox(height: 9), Text(value.trim().isEmpty ? 'Not recorded.' : value, style: const TextStyle(color: _muted, height: 1.55, fontSize: 12.2))]),
    );
  }

  Widget _infoTile(IconData icon, String label, String value) {
    return Container(
      constraints: const BoxConstraints(minWidth: 210, maxWidth: 320),
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(color: const Color(0xFFF8FAF9), borderRadius: BorderRadius.circular(12), border: Border.all(color: _border)),
      child: Row(children: [Icon(icon, color: _green, size: 18), const SizedBox(width: 9), Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [Text(label, style: const TextStyle(color: _muted, fontSize: 9.5, fontWeight: FontWeight.w700)), const SizedBox(height: 2), Text(value, maxLines: 2, overflow: TextOverflow.ellipsis, style: const TextStyle(color: _ink, fontSize: 11.5, fontWeight: FontWeight.w800))]))]),
    );
  }

  Widget _tabEmpty(IconData icon, String title, String message) {
    return Center(
      child: Padding(
        padding: const EdgeInsets.all(26),
        child: Column(mainAxisSize: MainAxisSize.min, children: [Icon(icon, size: 52, color: Colors.grey.shade300), const SizedBox(height: 12), Text(title, style: const TextStyle(color: _ink, fontWeight: FontWeight.w900, fontSize: 16)), const SizedBox(height: 6), Text(message, textAlign: TextAlign.center, style: const TextStyle(color: _muted, height: 1.45))]),
      ),
    );
  }
}

class _MemberEditorDialog extends StatefulWidget {
  final int clubId;
  final ClubMember? member;

  const _MemberEditorDialog({required this.clubId, this.member});

  @override
  State<_MemberEditorDialog> createState() => _MemberEditorDialogState();
}

class _MemberEditorDialogState extends State<_MemberEditorDialog> {
  final _formKey = GlobalKey<FormState>();
  late final TextEditingController _name;
  late final TextEditingController _number;
  late final TextEditingController _email;
  late final TextEditingController _phone;
  late String _type;
  late String _role;
  bool _saving = false;

  @override
  void initState() {
    super.initState();
    _name = TextEditingController(text: widget.member?.fullName ?? '');
    _number = TextEditingController(text: widget.member?.memberNumber ?? '');
    _email = TextEditingController(text: widget.member?.email ?? '');
    _phone = TextEditingController(text: widget.member?.phone ?? '');
    _type = widget.member?.memberType ?? CampusClubsService.memberTypes.first;
    _role = widget.member?.clubRole ?? CampusClubsService.memberRoles.first;
  }

  @override
  void dispose() {
    _name.dispose();
    _number.dispose();
    _email.dispose();
    _phone.dispose();
    super.dispose();
  }

  Future<void> _save() async {
    if (_saving || !(_formKey.currentState?.validate() ?? false)) return;
    setState(() => _saving = true);
    try {
      final values = <String, dynamic>{
        'full_name': _name.text.trim(),
        'member_number': _number.text.trim(),
        'member_type': _type,
        'club_role': _role,
        'email': _email.text.trim(),
        'phone': _phone.text.trim(),
      };
      if (widget.member == null) {
        await CampusClubsService.addMember(widget.clubId, values);
      } else {
        await CampusClubsService.updateMember(widget.member!.id, values);
      }
      if (!mounted) return;
      Navigator.pop(context, true);
    } catch (e) {
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(backgroundColor: Colors.red.shade700, content: Text(e.toString().replaceFirst('Exception: ', ''))));
    } finally {
      if (mounted) setState(() => _saving = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    final compact = MediaQuery.of(context).size.width < 580;
    return AlertDialog(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
      title: Text(widget.member == null ? 'Add Club Member' : 'Edit Club Member'),
      content: SizedBox(
        width: 560,
        child: SingleChildScrollView(
          child: Form(
            key: _formKey,
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                _textField(_name, 'Full name', 'Member full name', Icons.person_outline_rounded, required: true),
                const SizedBox(height: 12),
                _textField(_number, 'Student / staff number', 'Optional', Icons.badge_outlined),
                const SizedBox(height: 12),
                if (compact)
                  Column(children: [_memberTypeField(), const SizedBox(height: 12), _memberRoleField()])
                else
                  Row(children: [Expanded(child: _memberTypeField()), const SizedBox(width: 12), Expanded(child: _memberRoleField())]),
                const SizedBox(height: 12),
                if (compact)
                  Column(children: [_textField(_email, 'Email', 'Optional', Icons.email_outlined), const SizedBox(height: 12), _textField(_phone, 'Phone', 'Optional', Icons.phone_outlined)])
                else
                  Row(children: [Expanded(child: _textField(_email, 'Email', 'Optional', Icons.email_outlined)), const SizedBox(width: 12), Expanded(child: _textField(_phone, 'Phone', 'Optional', Icons.phone_outlined))]),
              ],
            ),
          ),
        ),
      ),
      actions: [
        TextButton(onPressed: _saving ? null : () => Navigator.pop(context), child: const Text('Cancel')),
        FilledButton.icon(
          onPressed: _saving ? null : _save,
          style: FilledButton.styleFrom(backgroundColor: _green),
          icon: _saving ? const SizedBox(width: 16, height: 16, child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white)) : const Icon(Icons.save_outlined, size: 17),
          label: Text(_saving ? 'Saving...' : 'Save Member'),
        ),
      ],
    );
  }

  Widget _memberTypeField() {
    return DropdownButtonFormField<String>(
      value: _type,
      isExpanded: true,
      decoration: _fieldDecoration('Member type', null, Icons.person_outline_rounded),
      items: CampusClubsService.memberTypes.map((value) => DropdownMenuItem(value: value, child: Text(value))).toList(),
      onChanged: (value) { if (value != null) setState(() => _type = value); },
    );
  }

  Widget _memberRoleField() {
    return DropdownButtonFormField<String>(
      value: _role,
      isExpanded: true,
      decoration: _fieldDecoration('Club position', null, Icons.workspace_premium_outlined),
      items: CampusClubsService.memberRoles.map((value) => DropdownMenuItem(value: value, child: Text(value))).toList(),
      onChanged: (value) { if (value != null) setState(() => _role = value); },
    );
  }
}

Widget _textField(
  TextEditingController controller,
  String label,
  String hint,
  IconData icon, {
  bool required = false,
  int minLines = 1,
  int maxLines = 1,
}) {
  return TextFormField(
    controller: controller,
    minLines: minLines,
    maxLines: maxLines,
    validator: required
        ? (value) => value == null || value.trim().isEmpty ? '$label is required.' : null
        : null,
    decoration: _fieldDecoration(label, hint, icon),
  );
}

InputDecoration _fieldDecoration(String label, String? hint, IconData icon) {
  return InputDecoration(
    labelText: label,
    hintText: hint,
    prefixIcon: Icon(icon, color: _green, size: 19),
    filled: true,
    fillColor: const Color(0xFFF8FAF9),
    contentPadding: const EdgeInsets.symmetric(horizontal: 13, 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 _dialogHeader({
  required IconData icon,
  required String title,
  required String subtitle,
  required VoidCallback? onClose,
}) {
  return Container(
    width: double.infinity,
    padding: const EdgeInsets.fromLTRB(20, 18, 12, 16),
    decoration: const BoxDecoration(color: _green, borderRadius: BorderRadius.vertical(top: Radius.circular(20))),
    child: Row(
      children: [
        Container(width: 42, height: 42, decoration: BoxDecoration(color: Colors.white.withOpacity(.12), borderRadius: BorderRadius.circular(13)), child: Icon(icon, color: Colors.white)),
        const SizedBox(width: 11),
        Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [Text(title, style: const TextStyle(color: Colors.white, fontWeight: FontWeight.w900, fontSize: 17)), const SizedBox(height: 2), Text(subtitle, style: const TextStyle(color: Color(0xFFE4F0E9), fontSize: 10.5, height: 1.35))])),
        IconButton(onPressed: onClose, icon: const Icon(Icons.close_rounded, color: Colors.white)),
      ],
    ),
  );
}

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

String _initials(String name) {
  final parts = name.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 >= 2 ? 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}';
}

String _formatBytes(int bytes) {
  if (bytes >= 1024 * 1024) return '${(bytes / (1024 * 1024)).toStringAsFixed(1)} MB';
  if (bytes >= 1024) return '${(bytes / 1024).toStringAsFixed(0)} KB';
  return '$bytes B';
}

IconData _documentIcon(String name) {
  final lower = name.toLowerCase();
  if (lower.endsWith('.pdf')) return Icons.picture_as_pdf_outlined;
  if (lower.endsWith('.doc') || lower.endsWith('.docx')) return Icons.article_outlined;
  if (lower.endsWith('.xls') || lower.endsWith('.xlsx')) return Icons.table_chart_outlined;
  return Icons.description_outlined;
}
