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/occupancy/helpers/fetch_occupancy_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 OccupancyDataLoadingStrategy implements AnalyticsDataLoadingStrategy {
  @override
  void onCommunitySelected(
    BuildContext context,
    CommunityModel community,
    List<SpaceModel> spaces,
  ) {
    context.read<SpaceTreeBloc>().add(
          OnCommunitySelected(
            community.uuid,
            spaces.isNotEmpty ? [spaces.first] : [],
          ),
        );

    final spaceTreeState = context.read<SpaceTreeBloc>().state;
    if (spaceTreeState.selectedCommunities.contains(community.uuid)) {
      clearData(context);
      return;
    }
    FetchOccupancyDataHelper.loadOccupancyData(
      context,
      communityId: community.uuid,
      spaceId: spaces.isNotEmpty ? spaces.first.uuid ?? '' : '',
    );
  }

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

    if (selectedSpacesIds.isEmpty) {
      spaceTreeBloc.add(OnCommunitySelected(community.uuid, [space]));
    } else if (isSpaceSelected) {
      spaceTreeBloc.add(const SpaceTreeClearSelectionEvent());
    } else {
      spaceTreeBloc
        ..add(const SpaceTreeClearSelectionEvent())
        ..add(OnSpaceSelected(community, space.uuid ?? '', []));
    }

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

    FetchOccupancyDataHelper.loadOccupancyData(
      context,
      communityId: community.uuid,
      spaceId: space.uuid ?? '',
    );
  }

  @override
  void onChildSpaceSelected(
    BuildContext context,
    CommunityModel community,
    SpaceModel child,
  ) {
    // Do nothing
  }

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