import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_modular/flutter_modular.dart';
import 'package:krow_core/core.dart';
import 'client_main_state.dart';

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

  void _onRouteChanged() {
    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(ClientPaths.coverage)) {
      newIndex = 0;
    } else if (path.contains(ClientPaths.billing)) {
      newIndex = 1;
    } else if (path.contains(ClientPaths.home)) {
      newIndex = 2;
    } else if (path.contains(ClientPaths.orders)) {
      newIndex = 3;
    } else if (path.contains(ClientPaths.reports)) {
      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.navigate(ClientPaths.coverage);
        break;
      case 1:
        Modular.to.navigate(ClientPaths.billing);
        break;
      case 2:
        Modular.to.navigate(ClientPaths.home);
        break;
      case 3:
        Modular.to.navigate(ClientPaths.orders);
        break;
      case 4:
        Modular.to.navigate(ClientPaths.reports);
        break;
    }
    // State update will happen via _onRouteChanged
  }

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