import 'dart:convert';

import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:unit2/model/passo/land_value_adjustment.dart';
import 'package:http/http.dart' as http;
import 'package:unit2/sevices/passo/land/land_value_adjustment.dart';
part 'land_value_adjustments_event.dart';
part 'land_value_adjustments_state.dart';

class LandValueAdjustmentsBloc
    extends Bloc<LandValueAdjustmentsEvent, LandValueAdjustmentsState> {
  LandValueAdjustmentsBloc() : super(LandValueAdjustmentsLoading()) {
    List<ValueAdjustments> globalLandValueAdjustments = [];
    on<LoadLandValueAdjustments>((event, emit) async {
      emit(LandValueAdjustmentsLoading());
      try {
        // final tempID = await SharedPreferences.getInstance();
        // print(tempID.getInt('tempid'));
        // final additionalItem = await GetLandValueAdjustments.getLandValueAdjustments(
        //     tempID.getInt('tempid'));

        emit(LandValueAdjustmentsLoaded(globalLandValueAdjustments));
      } catch (e) {
        emit(LandValueAdjustmentsErrorState(e.toString()));
      }
    });
    on<LoadLandValueAdjustmentsEdit>((event, emit) async {
      emit(LandValueAdjustmentsLoading());
      try {
        final additionalItems =
            await ValueAdjustmentsServices.instance.fetch(event.id);
        globalLandValueAdjustments.clear();
        globalLandValueAdjustments
            .addAll(additionalItems); // Append all items to the list
        emit(LandValueAdjustmentsLoaded(globalLandValueAdjustments));
      } catch (e) {
        emit(LandValueAdjustmentsErrorState(e.toString()));
      }
    });
    on<AddLandValueAdjustments>((event, emit) async {
      http.Response response =
          (await ValueAdjustmentsServices.instance.add(event.val_adj))!;
      print(response.body);

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

        emit(LandValueAdjustmentsLoaded(globalLandValueAdjustments));
      }
    });
    on<DeleteLandValueAdjustments>((event, emit) async {
      print(event.id);
      http.Response response =
          (await ValueAdjustmentsServices.instance.remove(event.id));
      print(response.statusCode);
      if (response.statusCode == 200) {
        globalLandValueAdjustments.removeWhere(
            ((ValueAdjustments element) => element.id == event.id));
        emit(LandValueAdjustmentsDeletedState(success: true));
      }
    });

    on<ShowLandValueAdjustments>((event, emit) async {
      emit(ShowAddLandValueAdjustmentsScreen());
    });
  }
}
