import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/spaces_management/create_subspace_model/bloc/subspace_model_event.dart';
import 'package:syncrow_web/pages/spaces_management/create_subspace_model/bloc/subspace_model_state.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/models/space_template_model.dart';
import 'package:syncrow_web/pages/spaces_management/space_model/models/subspace_template_model.dart';
import 'package:syncrow_web/utils/constants/action_enum.dart';

class SubSpaceModelBloc extends Bloc<SubSpaceModelEvent, SubSpaceModelState> {
  SubSpaceModelBloc() : super(SubSpaceModelState([], [], '', {})) {
    // Handle AddSubSpaceModel Event
    on<AddSubSpaceModel>((event, emit) {
      final existingNames =
          state.subSpaces.map((e) => e.subspaceName.toLowerCase()).toSet();

      if (existingNames.contains(event.subSpace.subspaceName.toLowerCase())) {
        final updatedDuplicates = Set<String>.from(state.duplicates)
          ..add(event.subSpace.subspaceName.toLowerCase());
        final updatedSubSpaces =
            List<SubspaceTemplateModel>.from(state.subSpaces)
              ..add(event.subSpace);
        emit(SubSpaceModelState(
          updatedSubSpaces,
          state.updatedSubSpaceModels,
          '*Duplicated sub-space name',
          updatedDuplicates,
        ));
      } else {
        final updatedSubSpaces =
            List<SubspaceTemplateModel>.from(state.subSpaces)
              ..add(event.subSpace);

        if (state.duplicates.isNotEmpty) {
          emit(SubSpaceModelState(
            updatedSubSpaces,
            state.updatedSubSpaceModels,
            '*Duplicated sub-space name',
            state.duplicates,
          ));
        } else {
          emit(SubSpaceModelState(
            updatedSubSpaces,
            state.updatedSubSpaceModels,
            '',
            state.duplicates,
          ));
        }
      }
    });

    // Handle RemoveSubSpaceModel Event

    on<RemoveSubSpaceModel>((event, emit) {
      final updatedSubSpaces = List<SubspaceTemplateModel>.from(state.subSpaces)
        ..remove(event.subSpace);

      final updatedSubspaceModels = List<UpdateSubspaceTemplateModel>.from(
        state.updatedSubSpaceModels,
      );

      if (event.subSpace.uuid?.isNotEmpty ?? false) {
        updatedSubspaceModels.add(UpdateSubspaceTemplateModel(
          action: Action.delete,
          uuid: event.subSpace.uuid!,
        ));
      }

      // Count occurrences of sub-space names to identify duplicates
      final nameOccurrences = <String, int>{};
      for (final subSpace in updatedSubSpaces) {
        final lowerName = subSpace.subspaceName.toLowerCase();
        nameOccurrences[lowerName] = (nameOccurrences[lowerName] ?? 0) + 1;
      }

      // Identify duplicate names
      final updatedDuplicates = nameOccurrences.entries
          .where((entry) => entry.value > 1)
          .map((entry) => entry.key)
          .toSet();

      // Determine the error message
      final errorMessage =
          updatedDuplicates.isNotEmpty ? '*Duplicated sub-space name' : '';

      emit(SubSpaceModelState(
        updatedSubSpaces,
        updatedSubspaceModels,
        errorMessage,
        updatedDuplicates,
      ));
    });

    // Handle UpdateSubSpaceModel Event
    on<UpdateSubSpaceModel>((event, emit) {
      final updatedSubSpaces = state.subSpaces.map((subSpace) {
        if (subSpace.uuid == event.updatedSubSpace.uuid) {
          return event.updatedSubSpace;
        }
        return subSpace;
      }).toList();

      final updatedSubspaceModels = List<UpdateSubspaceTemplateModel>.from(
        state.updatedSubSpaceModels,
      );

      updatedSubspaceModels.add(UpdateSubspaceTemplateModel(
        action: Action.update,
        uuid: event.updatedSubSpace.uuid!,
      ));

      emit(SubSpaceModelState(
        updatedSubSpaces,
        updatedSubspaceModels,
        '',
        state.duplicates,
// Clear error message
      ));
    });
  }
}
