import 'package:flutter/material.dart';

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

const Color _clubsGreen = Color.fromARGB(255, 2, 105, 48);
const Color _clubsGold = Color.fromARGB(255, 204, 117, 4);
const Color _clubsBg = Color(0xFFF4F7F5);
const Color _clubsInk = Color(0xFF1E2D26);
const Color _clubsMuted = Color(0xFF6A756F);

class StaffClubsMainTab extends StatefulWidget {
  const StaffClubsMainTab({super.key});

  @override
  State<StaffClubsMainTab> createState() => _StaffClubsMainTabState();
}

class _StaffClubsMainTabState extends State<StaffClubsMainTab> {
  ClubCurrentUser? _user;
  bool _loading = true;
  String? _error;
  int _selected = 0;

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

  Future<void> _loadUser() async {
    if (!mounted) return;
    setState(() {
      _loading = true;
      _error = null;
    });
    try {
      final user = await CampusClubsService.getCurrentUser();
      if (!mounted) return;
      setState(() {
        _user = user;
        _loading = false;
      });
    } catch (e) {
      if (!mounted) return;
      setState(() {
        _loading = false;
        _error = _cleanError(e);
      });
    }
  }

  String _cleanError(Object error) {
    return error.toString().replaceFirst('Exception: ', '').trim();
  }

  List<_ClubNavItem> _items(ClubCurrentUser user) => <_ClubNavItem>[
        const _ClubNavItem(
          label: 'Club Directory',
          icon: Icons.hub_rounded,
          description: 'Campus clubs, membership and official documents',
        ),
        _ClubNavItem(
          label: user.isAdmin ? 'Pending Approvals' : 'My Registrations',
          icon: user.isAdmin
              ? Icons.fact_check_outlined
              : Icons.assignment_outlined,
          description: user.isAdmin
              ? 'Review club registrations from every campus'
              : 'Track clubs that you have submitted',
        ),
      ];

  Widget _currentPage(ClubCurrentUser user) {
    if (_selected == 1) {
      return PendingClubsSubTab(
        key: ValueKey('pending-${user.id}-${user.isAdmin}'),
        currentUser: user,
      );
    }
    return ClubDirectorySubTab(
      key: ValueKey('directory-${user.id}-${user.isAdmin}'),
      currentUser: user,
    );
  }

  @override
  Widget build(BuildContext context) {
    if (_loading) {
      return const ColoredBox(
        color: _clubsBg,
        child: Center(child: CircularProgressIndicator(color: _clubsGreen)),
      );
    }
    if (_error != null || _user == null) {
      return ColoredBox(
        color: _clubsBg,
        child: Center(
          child: Padding(
            padding: const EdgeInsets.all(24),
            child: ConstrainedBox(
              constraints: const BoxConstraints(maxWidth: 520),
              child: Container(
                padding: const EdgeInsets.all(28),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(22),
                  border: Border.all(color: const Color(0xFFE1E7E3)),
                ),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Icon(Icons.cloud_off_rounded,
                        size: 54, color: Colors.red.shade300),
                    const SizedBox(height: 14),
                    const Text(
                      'Clubs & Societies could not be opened',
                      textAlign: TextAlign.center,
                      style: TextStyle(
                        color: _clubsInk,
                        fontSize: 18,
                        fontWeight: FontWeight.w900,
                      ),
                    ),
                    const SizedBox(height: 8),
                    Text(
                      _error ?? 'The signed-in account could not be loaded.',
                      textAlign: TextAlign.center,
                      style: const TextStyle(color: _clubsMuted, height: 1.5),
                    ),
                    const SizedBox(height: 18),
                    FilledButton.icon(
                      onPressed: _loadUser,
                      style: FilledButton.styleFrom(backgroundColor: _clubsGreen),
                      icon: const Icon(Icons.refresh_rounded),
                      label: const Text('Try again'),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
      );
    }

    final user = _user!;
    final items = _items(user);

    return LayoutBuilder(
      builder: (context, constraints) {
        final desktop = constraints.maxWidth >= 980;
        if (desktop) {
          return ColoredBox(
            color: _clubsBg,
            child: Row(
              children: [
                SizedBox(width: 286, child: _desktopSidebar(user, items)),
                Expanded(child: _currentPage(user)),
              ],
            ),
          );
        }

        return Scaffold(
          backgroundColor: _clubsBg,
          body: Column(
            children: [
              _mobileHeader(user),
              Expanded(child: _currentPage(user)),
            ],
          ),
          bottomNavigationBar: NavigationBar(
            selectedIndex: _selected,
            height: 68,
            backgroundColor: Colors.white,
            indicatorColor: _clubsGreen.withOpacity(.10),
            onDestinationSelected: (index) => setState(() => _selected = index),
            destinations: items
                .map(
                  (item) => NavigationDestination(
                    icon: Icon(item.icon, color: _clubsMuted),
                    selectedIcon: Icon(item.icon, color: _clubsGreen),
                    label: item.label,
                  ),
                )
                .toList(),
          ),
        );
      },
    );
  }

  Widget _desktopSidebar(ClubCurrentUser user, List<_ClubNavItem> items) {
    return Container(
      color: Colors.white,
      child: Column(
        children: [
          Container(
            width: double.infinity,
            padding: const EdgeInsets.fromLTRB(24, 30, 24, 25),
            decoration: const BoxDecoration(
              color: _clubsGreen,
              border: Border(bottom: BorderSide(color: _clubsGold, width: 4)),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  width: 48,
                  height: 48,
                  decoration: BoxDecoration(
                    color: Colors.white.withOpacity(.12),
                    borderRadius: BorderRadius.circular(15),
                  ),
                  child: const Icon(Icons.groups_2_rounded,
                      color: Colors.white, size: 27),
                ),
                const SizedBox(height: 17),
                const Text(
                  'CLUBS & SOCIETIES',
                  style: TextStyle(
                    color: Colors.white,
                    fontWeight: FontWeight.w900,
                    fontSize: 17,
                    letterSpacing: 1.1,
                  ),
                ),
                const SizedBox(height: 5),
                const Text(
                  'Campus Registry',
                  style: TextStyle(
                    color: _clubsGold,
                    fontWeight: FontWeight.w700,
                    fontSize: 12,
                  ),
                ),
              ],
            ),
          ),
          Padding(
            padding: const EdgeInsets.fromLTRB(18, 18, 18, 10),
            child: Container(
              width: double.infinity,
              padding: const EdgeInsets.all(13),
              decoration: BoxDecoration(
                color: _clubsBg,
                borderRadius: BorderRadius.circular(14),
                border: Border.all(color: const Color(0xFFE1E7E3)),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    user.fullName,
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: const TextStyle(
                      fontWeight: FontWeight.w900,
                      color: _clubsInk,
                    ),
                  ),
                  const SizedBox(height: 4),
                  Row(
                    children: [
                      const Icon(Icons.location_on_outlined,
                          size: 15, color: _clubsGreen),
                      const SizedBox(width: 4),
                      Expanded(
                        child: Text(
                          user.isAdmin
                              ? 'All campuses access'
                              : (user.campus.isEmpty
                                  ? 'Campus not assigned'
                                  : user.campus),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: const TextStyle(
                            color: _clubsMuted,
                            fontSize: 11.5,
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
          const SizedBox(height: 4),
          ...List<Widget>.generate(items.length, (index) {
            final item = items[index];
            final active = _selected == index;
            return Padding(
              padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
              child: Material(
                color: active ? _clubsGreen.withOpacity(.08) : Colors.transparent,
                borderRadius: BorderRadius.circular(14),
                child: InkWell(
                  borderRadius: BorderRadius.circular(14),
                  onTap: () => setState(() => _selected = index),
                  child: Container(
                    padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 14),
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(14),
                      border: active
                          ? Border.all(color: _clubsGreen.withOpacity(.18))
                          : null,
                    ),
                    child: Row(
                      children: [
                        Icon(item.icon,
                            color: active ? _clubsGreen : _clubsMuted, size: 22),
                        const SizedBox(width: 12),
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                item.label,
                                style: TextStyle(
                                  color: active ? _clubsGreen : _clubsInk,
                                  fontWeight: FontWeight.w900,
                                  fontSize: 13,
                                ),
                              ),
                              const SizedBox(height: 3),
                              Text(
                                item.description,
                                style: const TextStyle(
                                  color: _clubsMuted,
                                  fontSize: 9.7,
                                  height: 1.35,
                                ),
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            );
          }),
          const Spacer(),
          const Padding(
            padding: EdgeInsets.all(20),
            child: Text(
              'Rockview University\nCampus Club Registry',
              textAlign: TextAlign.center,
              style: TextStyle(color: _clubsMuted, fontSize: 10.5, height: 1.5),
            ),
          ),
        ],
      ),
    );
  }

  Widget _mobileHeader(ClubCurrentUser user) {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.fromLTRB(15, 13, 15, 12),
      decoration: const BoxDecoration(
        color: _clubsGreen,
        border: Border(bottom: BorderSide(color: _clubsGold, width: 3)),
      ),
      child: SafeArea(
        bottom: false,
        child: Row(
          children: [
            Container(
              width: 39,
              height: 39,
              decoration: BoxDecoration(
                color: Colors.white.withOpacity(.12),
                borderRadius: BorderRadius.circular(12),
              ),
              child: const Icon(Icons.groups_2_rounded,
                  color: Colors.white, size: 22),
            ),
            const SizedBox(width: 11),
            const Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    'CLUBS & SOCIETIES',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 14,
                      fontWeight: FontWeight.w900,
                      letterSpacing: .8,
                    ),
                  ),
                  Text(
                    'Campus Registry',
                    style: TextStyle(
                      color: _clubsGold,
                      fontSize: 10.5,
                      fontWeight: FontWeight.w700,
                    ),
                  ),
                ],
              ),
            ),
            Container(
              constraints: const BoxConstraints(maxWidth: 150),
              padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 7),
              decoration: BoxDecoration(
                color: Colors.white.withOpacity(.10),
                borderRadius: BorderRadius.circular(20),
                border: Border.all(color: Colors.white24),
              ),
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  const Icon(Icons.location_on_outlined,
                      size: 14, color: _clubsGold),
                  const SizedBox(width: 4),
                  Flexible(
                    child: Text(
                      user.isAdmin
                          ? 'All campuses'
                          : (user.campus.isEmpty ? 'No campus' : user.campus),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: const TextStyle(
                        color: Colors.white,
                        fontSize: 10.5,
                        fontWeight: FontWeight.w700,
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class _ClubNavItem {
  final String label;
  final IconData icon;
  final String description;

  const _ClubNavItem({
    required this.label,
    required this.icon,
    required this.description,
  });
}
