import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/common/bloc/project_manager.dart';
import 'package:syncrow_web/pages/routines/bloc/create_routine_bloc/create_routine_event.dart';
import 'package:syncrow_web/pages/routines/bloc/create_routine_bloc/create_routine_state.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';
import 'package:syncrow_web/services/space_mana_api.dart';

class CreateRoutineBloc extends Bloc<CreateRoutineEvent, CreateRoutineState> {
  CreateRoutineBloc() : super(const CreateRoutineInitial()) {
    on<SpaceOnlyWithDevicesEvent>(_fetchSpaceOnlyWithDevices);
    on<SaveCommunityIdAndSpaceIdEvent>(saveSpaceIdCommunityId);
    on<ResetSelectedEvent>(resetSelected);
  }

  String selectedSpaceId = '';
  String selectedCommunityId = '';
  List<CommunityModel> communities = [];
  List<SpaceModel> spacesOnlyWithDevices = [];

  Future<void> _fetchSpaceOnlyWithDevices(
      SpaceOnlyWithDevicesEvent event, Emitter<CreateRoutineState> emit) async {
    emit(const SpaceWithDeviceLoadingState());

    try {
      final projectUuid = await ProjectManager.getProjectUUID() ?? '';

      spacesOnlyWithDevices = await CommunitySpaceManagementApi()
          .getSpaceOnlyWithDevices(
              communityId: event.communityID, projectId: projectUuid);

      emit(SpaceWithDeviceLoadedState(spacesOnlyWithDevices));
    } catch (e) {
      emit(SpaceTreeErrorState('Error loading spaces: $e'));
    }
  }

  saveSpaceIdCommunityId(
      SaveCommunityIdAndSpaceIdEvent event, Emitter<CreateRoutineState> emit) {
    emit(const SpaceWithDeviceLoadingState());
    selectedSpaceId = event.spaceID!;
    selectedCommunityId = event.communityID!;
    emit(const SelectedState());
  }

  resetSelected(ResetSelectedEvent event, Emitter<CreateRoutineState> emit) {
    emit(const SpaceWithDeviceLoadingState());
    selectedSpaceId = '';
    selectedCommunityId = '';
    emit(const ResetSelectedState());
  }
}
