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/mobility/data/models/mobility_model.dart';
import 'package:krow/features/profile/mobility/data/staff_mobility_repository.dart';

part 'mobility_event.dart';
part 'mobility_state.dart';

class MobilityBloc extends Bloc<MobilityEvent, MobilityState> {
  MobilityBloc() : super(const MobilityState()) {
    on<InitializeMobilityEvent>((event, emit) async {
      emit(
        state.copyWith(
          isInEditMode: event.isInEditMode,
          status: event.isInEditMode ? StateStatus.loading : StateStatus.idle,
        ),
      );
      if (!state.isInEditMode) {
        emit(
          state.copyWith(
            hasACar: true,
            canRelocate: true,
          ),
        );
        return;
      }

      try {
        await for (final mobilityData
            in getIt<StaffMobilityRepository>().getStaffMobility()) {
          emit(
            state.copyWith(
              hasACar: mobilityData.hasACar,
              canRelocate: mobilityData.canRelocate,
              status: StateStatus.idle,
            ),
          );
        }
      } catch (except) {
        log(except.toString());
      }

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

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

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

    on<SaveMobilityChanges>((event, emit) async {
      emit(state.copyWith(status: StateStatus.loading));
      try {
        await getIt<StaffMobilityRepository>().updateStaffMobilityInfo(
          MobilityModel(
            hasACar: state.hasACar ?? false,
            canRelocate: state.canRelocate ?? false,
          ),
        );

        //resave cached data
        getIt<StaffMobilityRepository>().getStaffMobility();
      } catch (except) {
        emit(state.copyWith(status: StateStatus.idle));
        log(except.toString());
      }

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