import 'dart:convert';

import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:unit2/model/passo/additional_items.dart';
import 'package:http/http.dart' as http;
import 'package:unit2/sevices/passo/building/additional_items_services.dart';
part 'additional_items_edit_event.dart';
part 'additional_items_edit_state.dart';

class AdditionalItemsEditBloc
    extends Bloc<AdditionalItemsEditEvent, AdditionalItemsEditState> {
  AdditionalItemsEditBloc() : super(AdditionalItemsEditInitial()) {
    List<AdditionalItems> globalAdditionalItemsEdit = [];
    on<LoadAdditionalItemsEdit>((event, emit) async {
      if (globalAdditionalItemsEdit.isEmpty) {
        emit(AdditionalItemsEditLoading());
        try {
          final additionalItems =
              await AdditionalItemsServices.instance.fetch(event.id);

          globalAdditionalItemsEdit
              .addAll(additionalItems); // Append fetched data
          emit(AdditionalItemsEditLoaded(globalAdditionalItemsEdit));
        } catch (e) {
          emit(AdditionalItemsEditErrorState(e.toString()));
        }
      } else {
        emit(AdditionalItemsEditLoaded(globalAdditionalItemsEdit));
      }
    });

    on<AddAdditionalItemsEdit>((event, emit) async {
      http.Response response =
          (await AdditionalItemsServices.instance.add(event.items))!;
      print(response.statusCode);

      if (response.statusCode == 201) {
        var jsonResponse = jsonDecode(response.body);
        AdditionalItems newAdditional =
            AdditionalItems.fromJson(jsonResponse['data']);
        print(jsonResponse['data']);
        globalAdditionalItemsEdit.add(newAdditional);

        emit(AdditionalItemsEditLoaded(globalAdditionalItemsEdit));
      }
    });
    on<ShowAdditionalItemsEdit>((event, emit) async {
      emit(ShowAddItemsScreenEdit());
    });
    on<DeleteAdditionalItemsEdit>((event, emit) async {
      print(event.id);
      http.Response response =
          (await AdditionalItemsServices.instance.remove(event.id));
      print(response.statusCode);
      if (response.statusCode == 200) {
        globalAdditionalItemsEdit
            .removeWhere(((AdditionalItems element) => element.id == event.id));
        emit(AdditionalItemsEditDeletedState(success: true));
      }
    });
  }
}
