import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/subspace_model.dart';
import 'package:syncrow_web/utils/constants/action_enum.dart';

import 'subspace_event.dart';
import 'subspace_state.dart';

class SubSpaceBloc extends Bloc<SubSpaceEvent, SubSpaceState> {
  SubSpaceBloc() : super(SubSpaceState([], [], '', {})) {
    on<AddSubSpace>((event, emit) {
      final existingNames = state.subSpaces.map((e) => e.subspaceName).toSet();

      if (existingNames.contains(event.subSpace.subspaceName.toLowerCase())) {
        final updatedDuplicates = Set<String>.from(state.duplicates)
          ..add(event.subSpace.subspaceName.toLowerCase());
        final updatedSubSpaces = List<SubspaceModel>.from(state.subSpaces)
          ..add(event.subSpace);
        emit(SubSpaceState(
          updatedSubSpaces,
          state.updatedSubSpaceModels,
          '*Duplicated sub-space name',
          updatedDuplicates,
        ));
      } else {
        // Add subspace if no duplicate exists
        final updatedSubSpaces = List<SubspaceModel>.from(state.subSpaces)
          ..add(event.subSpace);

        if (state.duplicates.isNotEmpty) {
          emit(SubSpaceState(
            updatedSubSpaces,
            state.updatedSubSpaceModels,
            '*Duplicated sub-space name',
            state.duplicates,
          ));
        } else {
          emit(SubSpaceState(
            updatedSubSpaces,
            state.updatedSubSpaceModels,
            '',
            state.duplicates,
// Clear error message
          ));
        }
      }
    });

    // Handle RemoveSubSpace Event
    on<RemoveSubSpace>((event, emit) {
      final updatedSubSpaces = List<SubspaceModel>.from(state.subSpaces)
        ..remove(event.subSpace);

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

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

      final nameOccurrences = <String, int>{};
      for (final subSpace in updatedSubSpaces) {
        final lowerName = subSpace.subspaceName.toLowerCase();
        nameOccurrences[lowerName] = (nameOccurrences[lowerName] ?? 0) + 1;
      }

      final updatedDuplicates = nameOccurrences.entries
          .where((entry) => entry.value > 1)
          .map((entry) => entry.key)
          .toSet();
      final errorMessage =
          updatedDuplicates.isNotEmpty ? '*Duplicated sub-space name' : '';

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

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

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

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

      emit(SubSpaceState(
        updatedSubSpaces,
        updatedSubspaceModels,
        '',
        state.duplicates,
      ));
    });
  }
}
