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

class AddDeviceTypeBloc extends Bloc<AddDeviceTypeEvent, AddDeviceState> {
  AddDeviceTypeBloc() : super(AddDeviceInitial()) {
    on<InitializeDevice>(_onInitializeTagModels);
    on<UpdateProductCountEvent>(_onUpdateProductCount);
  }

  void _onInitializeTagModels(
      InitializeDevice event, Emitter<AddDeviceState> emit) {
    emit(AddDeviceLoaded(
      selectedProducts: event.addedProducts,
      initialTag: event.initialTags,
    ));
  }

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

    if (currentState is AddDeviceLoaded) {
      final existingProduct = currentState.selectedProducts.firstWhere(
        (p) => p.productId == event.productId,
        orElse: () => SelectedProduct(
          productId: event.productId,
          count: 0,
          productName: event.productName,
          product: event.product,
        ),
      );

      List<SelectedProduct> updatedProducts;

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

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