import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_modular/flutter_modular.dart';
import 'package:staff_main/src/presentation/blocs/staff_main_state.dart';
import 'package:staff_main/src/presentation/constants/staff_main_routes.dart';
import 'package:staff_main/src/presentation/navigation/staff_main_navigator.dart';

class StaffMainCubit extends Cubit<StaffMainState> implements Disposable {
  StaffMainCubit() : super(const StaffMainState()) {
    Modular.to.addListener(_onRouteChanged);
    _onRouteChanged();
  }

  void _onRouteChanged() {
    if (isClosed) return;
    final String path = Modular.to.path;
    int newIndex = state.currentIndex;

    // Detect which tab is active based on the route path
    // Using contains() to handle child routes and trailing slashes
    if (path.contains(StaffMainRoutes.shiftsFull)) {
      newIndex = 0;
    } else if (path.contains(StaffMainRoutes.paymentsFull)) {
      newIndex = 1;
    } else if (path.contains(StaffMainRoutes.homeFull)) {
      newIndex = 2;
    } else if (path.contains(StaffMainRoutes.clockInFull)) {
      newIndex = 3;
    } else if (path.contains(StaffMainRoutes.profileFull)) {
      newIndex = 4;
    }

    if (newIndex != state.currentIndex) {
      emit(state.copyWith(currentIndex: newIndex));
    }
  }

  void navigateToTab(int index) {
    if (index == state.currentIndex) return;

    switch (index) {
      case 0:
        Modular.to.navigateToShifts();
        break;
      case 1:
        Modular.to.navigateToPayments();
        break;
      case 2:
        Modular.to.navigateToHome();
        break;
      case 3:
        Modular.to.navigateToClockIn();
        break;
      case 4:
        Modular.to.navigateToProfile();
        break;
    }
    // State update will happen via _onRouteChanged
  }

  @override
  void dispose() {
    Modular.to.removeListener(_onRouteChanged);
    close();
  }
}
