import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/selected_product_model.dart';
import 'package:syncrow_web/pages/spaces_management/tag_model/bloc/add_device_model_state.dart';
import 'package:syncrow_web/pages/spaces_management/tag_model/bloc/add_device_type_model_event.dart';

class AddDeviceTypeModelBloc
    extends Bloc<AddDeviceTypeModelEvent, AddDeviceModelState> {
  AddDeviceTypeModelBloc() : super(AddDeviceModelInitial()) {
    on<InitializeDeviceTypeModel>(_onInitializeTagModels);
    on<UpdateProductCountEvent>(_onUpdateProductCount);
  }

  void _onInitializeTagModels(
      InitializeDeviceTypeModel event, Emitter<AddDeviceModelState> emit) {
    emit(AddDeviceModelLoaded(
      selectedProducts: event.addedProducts,
      initialTag: event.initialTags,
    ));
  }

  void _onUpdateProductCount(
      UpdateProductCountEvent event, Emitter<AddDeviceModelState> emit) {
    final currentState = state;

    if (currentState is AddDeviceModelLoaded) {
      final existingProduct = currentState.selectedProducts.firstWhere(
        (p) => p.productId == event.selectedProduct.productId,
        orElse: () => event.selectedProduct,
      );

      List<SelectedProduct> updatedProducts;

      if (event.selectedProduct.count > 0) {
        if (!currentState.selectedProducts.contains(existingProduct)) {
          updatedProducts = [
            ...currentState.selectedProducts,
            event.selectedProduct,
          ];
        } else {
          updatedProducts = currentState.selectedProducts.map((p) {
            if (p.productId == event.selectedProduct.productId) {
              return event.selectedProduct;
            }
            return p;
          }).toList();
        }
      } else {
        // Remove the product if the count is 0
        updatedProducts = currentState.selectedProducts
            .where((p) => p.productId != event.selectedProduct.productId)
            .toList();
      }

      // Emit the updated state
      emit(AddDeviceModelLoaded(
          selectedProducts: updatedProducts,
          initialTag: currentState.initialTag));
    }
  }
}
