import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:syncrow_web/pages/analytics/models/air_quality_data_model.dart';
import 'package:syncrow_web/pages/analytics/modules/air_quality/widgets/aqi_type_dropdown.dart';
import 'package:syncrow_web/pages/analytics/params/get_air_quality_distribution_param.dart';
import 'package:syncrow_web/pages/analytics/services/air_quality_distribution/air_quality_distribution_service.dart';

part 'air_quality_distribution_event.dart';
part 'air_quality_distribution_state.dart';

class AirQualityDistributionBloc
    extends Bloc<AirQualityDistributionEvent, AirQualityDistributionState> {
  final AirQualityDistributionService _aqiDistributionService;

  AirQualityDistributionBloc(
    this._aqiDistributionService,
  ) : super(const AirQualityDistributionState()) {
    on<LoadAirQualityDistribution>(_onLoadAirQualityDistribution);
    on<ClearAirQualityDistribution>(_onClearAirQualityDistribution);
    on<UpdateAqiTypeEvent>(_onUpdateAqiTypeEvent);
  }

  Future<void> _onLoadAirQualityDistribution(
    LoadAirQualityDistribution event,
    Emitter<AirQualityDistributionState> emit,
  ) async {
    try {
      emit(state.copyWith(status: AirQualityDistributionStatus.loading));
      final result = await _aqiDistributionService.getAirQualityDistribution(
        event.param,
      );
      emit(
        state.copyWith(
          status: AirQualityDistributionStatus.success,
          chartData: result,
        ),
      );
    } catch (e) {
      emit(
        AirQualityDistributionState(
          status: AirQualityDistributionStatus.failure,
          errorMessage: e.toString(),
          selectedAqiType: state.selectedAqiType,
        ),
      );
    }
  }

  void _onClearAirQualityDistribution(
    ClearAirQualityDistribution event,
    Emitter<AirQualityDistributionState> emit,
  ) {
    emit(AirQualityDistributionState(selectedAqiType: state.selectedAqiType));
  }

  void _onUpdateAqiTypeEvent(
    UpdateAqiTypeEvent event,
    Emitter<AirQualityDistributionState> emit,
  ) {
    emit(state.copyWith(selectedAqiType: event.aqiType));
  }
}
