import 'dart:developer';

import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:krow/core/application/di/injectable.dart';
import 'package:krow/core/data/enums/state_status.dart';
import 'package:krow/features/profile/inclusive/data/models/inclusive_info_model.dart';
import 'package:krow/features/profile/inclusive/data/staff_inclusivity_repository.dart';

part 'inclusive_info_event.dart';

part 'inclusive_info_state.dart';

class InclusiveInfoBloc extends Bloc<InclusiveInfoEvent, InclusiveInfoState> {
  InclusiveInfoBloc() : super(const InclusiveInfoState()) {
    on<InitializeInclusiveInfoEvent>((event, emit) async {
      emit(
        state.copyWith(
          isInEditMode: event.isInEditMode,
          status: event.isInEditMode ? StateStatus.loading : StateStatus.idle,
        ),
      );
      if (!state.isInEditMode) {
        emit(
          state.copyWith(
            areAccommodationsRequired: true,
          ),
        );
        return;
      }

      try {
        await for (final inclusivityData
            in getIt<StaffInclusivityRepository>().getStaffInclusivityInfo()) {
          emit(
            state.copyWith(
              areAccommodationsRequired:
                  inclusivityData.areAccommodationsRequired,
              accommodationsDetails: inclusivityData.accommodationsDetails,
              status: StateStatus.idle,
            ),
          );
        }
      } catch (except) {
        log(except.toString());
      }

      emit(
        state.copyWith(
          areAccommodationsRequired: state.areAccommodationsRequired ?? true,
          status: state.status == StateStatus.loading
              ? StateStatus.idle
              : state.status,
        ),
      );
    });

    on<ToggleRequiresAccommodations>((event, emit) {
      emit(state.copyWith(areAccommodationsRequired: event.index == 0));
    });

    on<ChangeAccommodationsDetails>((event, emit) {
      emit(state.copyWith(accommodationsDetails: event.details));
    });

    on<SaveInclusiveInfoChanges>((event, emit) async {
      emit(state.copyWith(status: StateStatus.loading));

      try {
        await getIt<StaffInclusivityRepository>().updateStaffMobilityInfo(
          InclusiveInfoModel(
            areAccommodationsRequired: state.areAccommodationsRequired ?? false,
            accommodationsDetails: state.accommodationsDetails,
          ),
        );
      } catch (except) {
        emit(state.copyWith(status: StateStatus.idle));

        log(except.toString());
      }

      emit(state.copyWith(status: StateStatus.success));
    });
  }
}
