import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:krow_core/core.dart';
import 'package:flutter_modular/flutter_modular.dart';
import 'package:staff_main/src/presentation/blocs/staff_main_state.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
    if (path.contains('/clock-in')) {
      newIndex = 3;
    } else if (path.contains('/payments')) {
      newIndex = 1;
    } else if (path.contains('/home')) {
      newIndex = 2;
    } else if (path.contains('/shifts')) {
      newIndex = 0;
    } else if (path.contains('/profile')) {
      newIndex = 4;
    }

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

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

    // Optimistically update the tab index for instant feedback
    emit(state.copyWith(currentIndex: index));

    switch (index) {
      case 0:
        Modular.to.toShifts();
        break;
      case 1:
        Modular.to.toPayments();
        break;
      case 2:
        Modular.to.toStaffHome();
        break;
      case 3:
        Modular.to.toClockIn();
        break;
      case 4:
        Modular.to.toProfile();
        break;
    }
  }

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