import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/analytics/modules/air_quality/helpers/fetch_air_quality_data_helper.dart';
import 'package:syncrow_web/pages/analytics/modules/analytics/blocs/analytics_date_picker_bloc/analytics_date_picker_bloc.dart';
import 'package:syncrow_web/pages/analytics/modules/analytics/strategies/analytics_data_loading_strategy.dart';
import 'package:syncrow_web/pages/space_tree/bloc/space_tree_bloc.dart';
import 'package:syncrow_web/pages/space_tree/bloc/space_tree_event.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/community_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/space_model.dart';

final class AirQualityDataLoadingStrategy implements AnalyticsDataLoadingStrategy {
  @override
  void onCommunitySelected(
    BuildContext context,
    CommunityModel community,
    List<SpaceModel> spaces,
  ) {
    // Do nothing
  }

  @override
  void onSpaceSelected(
    BuildContext context,
    CommunityModel community,
    SpaceModel space,
  ) {
    final spaceTreeBloc = context.read<SpaceTreeBloc>();
    final isSpaceSelected = spaceTreeBloc.state.selectedSpaces.contains(space.uuid);

    final hasSelectedSpaces = spaceTreeBloc.state.selectedSpaces.isNotEmpty;
    if (hasSelectedSpaces) clearData(context);

    if (isSpaceSelected) return;

    spaceTreeBloc
      ..add(const SpaceTreeClearSelectionEvent())
      ..add(OnSpaceSelected(community, space.uuid ?? '', []));

    FetchAirQualityDataHelper.loadAirQualityData(
      context,
      communityUuid: community.uuid,
      spaceUuid: space.uuid ?? '',
      date: context.read<AnalyticsDatePickerBloc>().state.monthlyDate,
    );
  }

  @override
  void clearData(BuildContext context) {
    context.read<SpaceTreeBloc>().add(
          const AnalyticsClearAllSpaceTreeSelectionsEvent(),
        );
    FetchAirQualityDataHelper.clearAllData(context);
  }
}
