import 'dart:async';

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/benefits/domain/benefits_repository.dart';
import 'package:krow/features/profile/benefits/domain/entities/benefit_entity.dart';

part 'benefits_event.dart';

part 'benefits_state.dart';

class BenefitsBloc extends Bloc<BenefitsEvent, BenefitsState> {
  BenefitsBloc() : super(const BenefitsState()) {
    on<InitializeBenefits>((event, emit) async {
      emit(state.copyWith(status: StateStatus.loading));

      final benefits = await _repository.getStaffBenefits();

      emit(state.copyWith(status: StateStatus.idle, benefits: benefits));
    });

    on<SendBenefitRequest>((event, emit) async {
      emit(state.copyWith(status: StateStatus.loading));
      final result = await _repository.requestBenefit(benefit: event.benefit);

      int index = -1;
      List<BenefitEntity>? updatedBenefits;
      if (result != null) {
        index = state.benefits.indexWhere(
          (benefit) => benefit.name == result.name,
        );

        if (index >= 0) {
          updatedBenefits = List.from(state.benefits)..[index] = result;
        }
      }

      emit(
        state.copyWith(
          benefits: updatedBenefits,
          status: StateStatus.idle,
        ),
      );
      event.requestCompleter.complete(result ?? event.benefit);
    });
  }

  final BenefitsRepository _repository = getIt<BenefitsRepository>();
}
