import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/analytics/modules/analytics/strategies/analytics_data_loading_strategy.dart';
import 'package:syncrow_web/pages/analytics/modules/energy_management/helpers/fetch_energy_management_data_helper.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';

class EnergyManagementDataLoadingStrategy implements AnalyticsDataLoadingStrategy {
  @override
  void onCommunitySelected(
    BuildContext context,
    CommunityModel community,
    List<SpaceModel> spaces,
  ) {
    // Add to space tree bloc first
    context.read<SpaceTreeBloc>().add(
          OnCommunitySelected(
            community.uuid,
            spaces,
          ),
        );

    final spaceTreeState = context.read<SpaceTreeBloc>().state;
    if (spaceTreeState.selectedCommunities.contains(community.uuid)) {
      clearData(context);
      return;
    }

    FetchEnergyManagementDataHelper.loadEnergyManagementData(
      context,
      communityId: community.uuid,
      spaceId: spaces.isNotEmpty ? spaces.first.uuid ?? '' : '',
    );
  }

  @override
  void onSpaceSelected(
    BuildContext context,
    CommunityModel community,
    SpaceModel space,
  ) {
    context.read<SpaceTreeBloc>().add(
          OnSpaceSelected(
            community,
            space.uuid ?? '',
            space.children,
          ),
        );

    final spaceTreeState = context.read<SpaceTreeBloc>().state;
    if (spaceTreeState.selectedCommunities.contains(community.uuid) ||
        spaceTreeState.selectedSpaces.contains(space.uuid)) {
      clearData(context);
      return;
    }

    FetchEnergyManagementDataHelper.loadEnergyManagementData(
      context,
      communityId: community.uuid,
      spaceId: space.uuid ?? '',
    );
  }

  @override
  void onChildSpaceSelected(
    BuildContext context,
    CommunityModel community,
    SpaceModel child,
  ) {
    // Do nothing else as per original implementation
  }

  @override
  void clearData(BuildContext context) {
    context.read<SpaceTreeBloc>().add(const SpaceTreeClearSelectionEvent());
    FetchEnergyManagementDataHelper.clearAllData(context);
  }
}
