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,
  ) {
    final spaceTreeBloc = context.read<SpaceTreeBloc>();
    final isCommunitySelected =
        spaceTreeBloc.state.selectedCommunities.contains(community.uuid);

    if (isCommunitySelected) {
      clearData(context);
      return;
    }
  }

  @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 (isSpaceSelected) {
      final firstSelectedSpace = spaceTreeBloc.state.selectedSpaces.first;
      final isTheFirstSelectedSpace = firstSelectedSpace == space.uuid;
      if (isTheFirstSelectedSpace) {
        clearData(context);
      }
      return;
    }

    if (hasSelectedSpaces) {
      clearData(context);
    }

    spaceTreeBloc.add(
      OnSpaceSelected(
        community,
        space.uuid ?? '',
        space.children,
      ),
    );

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

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