import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:unit2/model/location/barangay.dart';
import 'package:unit2/model/rbac/assigned_role.dart';
import 'package:unit2/model/rbac/rbac.dart';
import 'package:unit2/sevices/roles/rbac_operations/assigned_area_services.dart';
import '../../../../model/location/barangay2.dart';
import '../../../../model/profile/assigned_area.dart';
import '../../../../model/profile/basic_information/primary-information.dart';
import '../../../../sevices/roles/rbac_operations/role_assignment_services.dart';
part 'assign_area_event.dart';
part 'assign_area_state.dart';

class AssignAreaBloc extends Bloc<AssignAreaEvent, AssignAreaState> {
  AssignAreaBloc() : super(AssignAreaInitial()) {
    String? fname;
    String? lname;
    String? fullname;
    Profile? profile;
    int id;
    List<UserAssignedArea> userAssignedAreas = [];
    List<AssignedRole> assignedRoles = [];
    List<RBAC> roles = [];
    on<GetAssignArea>((event, emit) async {
      emit(AssignAreaLoadingState());
      try {
        profile = await RbacRoleAssignmentServices.instance.searchUser(
            page: 1, name: event.firstname, lastname: event.lastname);
        if (profile != null && profile!.id != null) {
          fname = profile!.firstName;
          lname = profile!.lastName;
          fullname = profile!.lastName;
          fullname = "${fname!} ${lname!}";
          id = profile!.webuserId!;
          userAssignedAreas = await RbacAssignedAreaServices.instance
              .getAssignedArea(id: profile!.webuserId!);

          assignedRoles = await RbacRoleAssignmentServices.instance
              .getAssignedRoles(
                  firstname: event.firstname, lastname: event.lastname);

          for (var role in assignedRoles) {
            roles.add(role.role!);
          }
          emit(AssignedAreaLoadedState(
              userAssignedAreas: userAssignedAreas,
              fullname: fullname!,
              roles: roles,
              userId: id));
        } else {
          id = 0;
          emit(UserNotExistError());
        }
      } catch (e) {
        emit(AssignAreaErorState(message: e.toString()));
      }
    });
    on<AddAssignArea>((event, emit) async {
      // try {
      emit(AssignAreaLoadingState());
      Map<dynamic, dynamic> response = await RbacAssignedAreaServices.instance
          .add(
              userId: event.userId,
              roleId: event.roleId,
              areaTypeId: event.areaTypeId,
              areaId: event.areaId);
      if (response["success"]) {
        UserAssignedArea newAssignArea = userAssignedAreas.firstWhere(
            (element) =>
                element.assignedRole!.role!.id == event.roleId &&
                element.assignedRole!.user!.id == event.userId);
        userAssignedAreas.removeWhere((element) =>
            element.assignedRole!.role!.id == event.roleId &&
            element.assignedRole!.user!.id == event.userId);
        ////barangay
        if (event.areaTypeId == 1) {
          List<dynamic> newAreas = [];
          for (var area in response['data']) {
            for (var assignedArea in area['assigned_area']) {
              var newArea = {};
              newArea.addAll({"id": assignedArea['id']});
              newArea.addAll({'isactive': assignedArea['isactive']});

              Barangay2 newBarangay = Barangay2.fromJson(assignedArea['area']);

              newArea.addAll({
                'area': {
                  "brgycode": newBarangay.brgycode,
                  "brgydesc": newBarangay.brgydesc,
                  "citymuncode": newBarangay.citymuncode
                }
              });

              newAreas.add(newArea);
            }
          }
          newAssignArea.assignedArea = newAreas;
          userAssignedAreas.add(newAssignArea);
          //// purok
        }
        if (event.areaTypeId == 2) {
          //// station
        }
        if (event.areaTypeId == 4) {
          ////agency
        }
        if (event.areaTypeId == 3) {}
        emit(AssignAreaAddedState(response: response));
      } else {
        emit(AssignAreaAddedState(response: response));
      }
      // } catch (e) {
      //   emit(AssignAreaErorState(message: e.toString()));
      // }
    });
    on<LoadAssignedAreas>((event, emit) async {
      emit(AssignedAreaLoadedState(
          userAssignedAreas: userAssignedAreas,
          fullname: fullname!,
          roles: roles,
          userId: event.userId));
    });
    on<DeleteAssignedArea>((event, emit) async {
      emit(AssignAreaLoadingState());
      try {
        bool success = await RbacAssignedAreaServices.instance
            .deleteAssignedArea(areaId: event.areaId);
        if (success) {
          for (var area in userAssignedAreas) {
            area.assignedArea.removeWhere((var a) {
              return a['id'] == event.areaId;
            });
          }
          emit(AssignedAreaDeletedState(success: success));
        } else {
          emit(AssignedAreaDeletedState(success: success));
        }
      } catch (e) {
        emit(AssignAreaErorState(message: e.toString()));
      }
    });
    on<CallErrorState>((event, emit) {
      emit(AssignAreaErorState(message: event.message));
    });
  }
}
