import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/common/bloc/project_manager.dart';
import 'package:syncrow_web/pages/space_tree/bloc/space_tree_bloc.dart';
import 'package:syncrow_web/pages/spaces_management/link_space_model/bloc/link_space_to_model_event.dart';
import 'package:syncrow_web/pages/spaces_management/link_space_model/bloc/link_space_to_model_state.dart';
import 'package:syncrow_web/services/space_model_mang_api.dart';
import 'package:syncrow_web/utils/navigation_service.dart';

class LinkSpaceToModelBloc
    extends Bloc<LinkSpaceToModelEvent, LinkSpaceToModelState> {
  LinkSpaceToModelBloc() : super(SpaceModelInitial()) {
    on<LinkSpaceModelSelectedIdsEvent>(_getSpaceIds);
    on<LinkSpaceModelEvent>(_handleLinkSpaceModel);
    on<ValidateSpaceModelEvent>(_validateLinkSpaceModel);
    on<LinkSpaceModelSelectedEvent>((event, emit) {
      emit(SpaceModelSelectedState(event.selectedIndex));
    });
  }

  List<String> spacesListIds = [];
  bool hasSelectedSpaces = false;
  String validate = '';

  Future<void> _getSpaceIds(LinkSpaceModelSelectedIdsEvent event,
      Emitter<LinkSpaceToModelState> emit) async {
    try {
      BuildContext context = NavigationService.navigatorKey.currentContext!;
      var spaceBloc = context.read<SpaceTreeBloc>();
      spacesListIds.clear(); 
      for (var communityId in spaceBloc.state.selectedCommunities) {
        List<String> spacesList =
            spaceBloc.state.selectedCommunityAndSpaces[communityId] ?? [];
        spacesListIds.addAll(spacesList); 
      }
      hasSelectedSpaces =
          spaceBloc.state.selectedCommunities.any((communityId) {
        List<String> spacesList =
            spaceBloc.state.selectedCommunityAndSpaces[communityId] ?? [];
        return spacesList.isNotEmpty;
      });
      if (hasSelectedSpaces) {
        debugPrint("At least one space is selected.");
      } else {
        debugPrint("No spaces selected.");
      }
    } catch (e) {
      debugPrint("Error in _getSpaceIds: $e");
    }
  }

  Future<void> _handleLinkSpaceModel(
    LinkSpaceModelEvent event,
    Emitter<LinkSpaceToModelState> emit,
  ) async {
    emit(SpaceModelLoading());
    try {
      final projectUuid = await ProjectManager.getProjectUUID() ?? '';
      await SpaceModelManagementApi().linkSpaceModel(
          spaceModelUuid: event.selectedSpaceMode!,
          projectId: projectUuid,
          spaceUuids: spacesListIds,
          isOverWrite: event.isOverWrite);
      emit(SpaceModelLinkSuccess());
    } on DioException catch (e) {
      final errorMessage = _parseDioError(e);
      emit(SpaceModelOperationFailure(errorMessage));
    } catch (e) {
      emit(SpaceModelOperationFailure('Unexpected error: $e'));
    }
  }

  Future<void> _validateLinkSpaceModel(
    ValidateSpaceModelEvent event,
    Emitter<LinkSpaceToModelState> emit,
  ) async {
    emit(SpaceModelLoading());
    try {
      final projectUuid = await ProjectManager.getProjectUUID() ?? '';
      await SpaceModelManagementApi().validateSpaceModel(
        projectUuid,
        spacesListIds,
      );
      emit(SpaceValidationSuccess());
    } on DioException catch (e) {
      final errorMessage = _parseDioError(e);
      if (errorMessage ==
          'Selected spaces already have linked space model / sub-spaces and devices') {
        emit(const AlreadyHaveLinkedState());
      } else {
        emit(SpaceModelOperationFailure(errorMessage));
      }
    } catch (e) {
      emit(SpaceModelOperationFailure('Unexpected error: $e'));
    }
  }

  String _parseDioError(DioException e) {
    if (e.response?.data is Map<String, dynamic>) {
      return e.response!.data['error']['message'] ?? 'Unknown error occurred';
    }
    return e.message ?? 'Network request failed';
  }
}
