import 'package:flutter/material.dart';
import 'package:inventory_system/services/session_manager.dart';

class BottomNavBar extends StatelessWidget {
  final int selectedIndex;
  final Function(int) onItemTapped;

  const BottomNavBar({
    super.key,
    required this.selectedIndex,
    required this.onItemTapped,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.1),
            blurRadius: 8,
            offset: const Offset(0, -2),
          ),
        ],
      ),
      child: BottomNavigationBar(
        currentIndex: selectedIndex,
        onTap: (index) {
          final currentUser = SessionManager.instance.currentUser;
          final bool isAdmin = currentUser?['isAdmin'] ?? false;
          final String homeRoute = isAdmin ? '/home' : '/user-home';

          if (index == 0) {
            final currentRoute = ModalRoute.of(context)?.settings.name;
            if (currentRoute != homeRoute) {
              Navigator.pushNamedAndRemoveUntil(context, homeRoute, (route) => false);
            }
            return;
          }

          if (index == 1) {
            final currentRoute = ModalRoute.of(context)?.settings.name;
            final scanRoute = isAdmin ? '/scan' : '/scan-user';
            
            if (currentRoute != homeRoute) {
              Navigator.pushNamed(context, homeRoute);
            }
            if (currentRoute != scanRoute) {
              Navigator.pushNamed(context, scanRoute);
            }
            return;
          }

          if (index == 2) {
            final currentRoute = ModalRoute.of(context)?.settings.name;
            const profileRoute = '/profile';

            if (currentRoute != profileRoute) {
              Navigator.pushNamed(context, profileRoute);
            }
            return;
          }

          onItemTapped(index);
        },
        backgroundColor: Colors.blue[800],
        elevation: 0,
        selectedItemColor: Colors.black87,
        unselectedItemColor: Colors.white,
        selectedFontSize: 11,
        unselectedFontSize: 11,
        type: BottomNavigationBarType.fixed,
        items: const [
          BottomNavigationBarItem(
            icon: Icon(Icons.home_rounded, size: 26),
            label: 'Home',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.qr_code_scanner_rounded, size: 26),
            label: 'Scan item',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.person_rounded, size: 26),
            label: 'Profile',
          ),
        ],
      ),
    );
  }
}
