import 'dart:convert';

import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:unit2/model/passo/other_improvements.dart';
import 'package:unit2/sevices/passo/land/land_other_improvements.dart';
import 'package:http/http.dart' as http;
part 'other_improvements_event.dart';
part 'other_improvements_state.dart';

class OtherImprovementsBloc
    extends Bloc<OtherImprovementsEvent, OtherImprovementsState> {
  OtherImprovementsBloc() : super(OtherImprovementLoading()) {
    List<OtherImprovements> globalOtherImprovement = [];
    on<LoadOtherImprovement>((event, emit) async {
      emit(OtherImprovementLoading());
      try {
        // final tempID = await SharedPreferences.getInstance();
        // print(tempID.getInt('tempid'));
        // final additionalItem = await GetOtherImprovement.getOtherImprovement(
        //     tempID.getInt('tempid'));

        emit(OtherImprovementLoaded(globalOtherImprovement));
      } catch (e) {
        emit(OtherImprovementErrorState(e.toString()));
      }
    });
    on<LoadOtherImprovementEdit>((event, emit) async {
      emit(OtherImprovementLoading());
      try {
        final additionalItems =
            await OtherImprovementServices.instance.fetch(event.ids);
        print(additionalItems);
        globalOtherImprovement.clear();
        globalOtherImprovement
            .addAll(additionalItems); // Append all items to the list
        emit(OtherImprovementLoaded(globalOtherImprovement));
      } catch (e) {
        print(e.toString());
        emit(OtherImprovementErrorState(e.toString()));
      }
    });
    on<AddOtherImprovement>((event, emit) async {
      http.Response response =
          (await OtherImprovementServices.instance.add(event.other_imp))!;
      print(response.body);

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

        emit(OtherImprovementLoaded(globalOtherImprovement));
      }
    });
    on<DeleteOtherImprovement>((event, emit) async {
      print(event.id);
      http.Response response =
          (await OtherImprovementServices.instance.remove(event.id));
      print(response.statusCode);
      if (response.statusCode == 200) {
        globalOtherImprovement.removeWhere(
            ((OtherImprovements element) => element.id == event.id));
        emit(OtherImprovementDeletedState(success: true));
      }
    });

    on<ShowOtherImprovement>((event, emit) async {
      emit(ShowAddOtherImprovementScreen());
    });
  }
}
