import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:go_router/go_router.dart';
import 'package:real_estate_mobile/core/constants/app_colors.dart';
import 'package:real_estate_mobile/features/auth/presentation/providers/auth_provider.dart';

/// Determines which tab is active based on the current route.
int _currentTabIndex(BuildContext context) {
  final location = GoRouterState.of(context).matchedLocation;
  if (location.startsWith('/messages')) return 2;
  if (location.startsWith('/agents/search') ||
      location.startsWith('/agent/network')) {
    return 1;
  }
  if (location.startsWith('/profile')) return 3;
  return 0; // home and everything else
}

class AppBottomNavBar extends ConsumerWidget {
  const AppBottomNavBar({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final selectedIndex = _currentTabIndex(context);

    return Container(
      decoration: const BoxDecoration(
        color: Colors.white,
        border: Border(
          top: BorderSide(color: Color(0xFFE8E8E8), width: 1),
        ),
      ),
      child: SafeArea(
        top: false,
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              _NavItem(
                svgPath: 'assets/icons/nav_home_icon.svg',
                fallbackIcon: Icons.home,
                isSelected: selectedIndex == 0,
                onTap: () => context.go('/home'),
              ),
              _NavItem(
                svgPath: 'assets/icons/nav_list_icon.svg',
                fallbackIcon: Icons.list,
                isSelected: selectedIndex == 1,
                onTap: () {
                  final authState = ref.read(authProvider);
                  // Agents see their network, users see agent search
                  if (authState.status == AuthStatus.authenticated &&
                      authState.user?.role == 'AGENT') {
                    context.go('/agent/network');
                  } else {
                    context.go('/agents/search');
                  }
                },
              ),
              _NavItem(
                svgPath: 'assets/icons/nav_messages_icon.svg',
                fallbackIcon: Icons.chat_bubble,
                isSelected: selectedIndex == 2,
                onTap: () {
                  final authState = ref.read(authProvider);
                  if (authState.status != AuthStatus.authenticated) {
                    context.push('/login');
                    return;
                  }
                  context.go('/messages');
                },
              ),
              _NavItem(
                svgPath: 'assets/icons/nav_profile_icon.svg',
                fallbackIcon: Icons.person_outline,
                isSelected: selectedIndex == 3,
                onTap: () {
                  final authState = ref.read(authProvider);
                  if (authState.status != AuthStatus.authenticated) {
                    context.push('/login');
                    return;
                  }
                  context.go('/profile');
                },
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class _NavItem extends StatelessWidget {
  final String svgPath;
  final IconData fallbackIcon;
  final bool isSelected;
  final VoidCallback onTap;

  const _NavItem({
    required this.svgPath,
    required this.fallbackIcon,
    required this.isSelected,
    required this.onTap,
  });

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onTap,
      behavior: HitTestBehavior.opaque,
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
        child: SvgPicture.asset(
          svgPath,
          width: 24,
          height: 24,
          colorFilter: isSelected
              ? const ColorFilter.mode(
                  AppColors.primaryDark, BlendMode.srcIn)
              : const ColorFilter.mode(
                  AppColors.accentOrange, BlendMode.srcIn),
          placeholderBuilder: (_) => Icon(
            fallbackIcon,
            size: 24,
            color: isSelected ? AppColors.primaryDark : AppColors.accentOrange,
          ),
        ),
      ),
    );
  }
}
