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/wages_forms/domain/entities/wage_form_entity.dart';
import 'package:krow/features/profile/wages_forms/domain/utils/validator_wage_from_visitor.dart';
import 'package:krow/features/profile/wages_forms/domain/wages_forms_repository.dart';

part 'wages_form_event.dart';

part 'wages_form_state.dart';

part 'wages_form_fields.dart';

class WagesFormBloc extends Bloc<WagesFormEvent, WagesFormState> {
  WagesFormBloc() : super(const WagesFormState()) {
    on<InitializeWagesFormBloc>(_onInitial);

    on<SetActiveForm>(_onSetActiveForm);

    on<AddUserSignImage>(_onAddUserSign);

    on<UpdateCurrentForm>(_onUpdateCurrentForm);

    on<ValidateCurrentForm>(_onValidateCurrentForm);

    on<SubmitCurrentForm>(_onSubmitCurrentForm);
  }

  final _repository = getIt<WagesFormsRepository>();
  final _validatorVisitor = const ValidatorWageFromVisitor();

  Future<void> _onInitial(
    InitializeWagesFormBloc event,
    Emitter<WagesFormState> emit,
  ) async {
    final forms = await _repository.getActualForms();

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

  void _onSetActiveForm(SetActiveForm event, Emitter<WagesFormState> emit) {
    emit(state.copyWith(activeForm: event.form));
  }

  void _onAddUserSign(AddUserSignImage event, Emitter<WagesFormState> emit) {
    emit(state.copyWith(signImageData: event.imageData));
  }

  void _onUpdateCurrentForm(
    UpdateCurrentForm event,
    Emitter<WagesFormState> emit,
  ) {
    emit(state.copyWith(activeForm: event.form));

    final index = state.actualForms.indexWhere(
      (item) => item.runtimeType == event.form.runtimeType,
    );
    if (index < 0) return;

    emit(
      state.copyWith(
        actualForms: List.from(state.actualForms)..[index] = event.form,
      ),
    );
  }

  void _onValidateCurrentForm(
    ValidateCurrentForm event,
    Emitter<WagesFormState> emit,
  ) {
    final formErrors = state.activeForm?.visit(_validatorVisitor) ?? {};

    final isSignAdded = state.signImageData != null;

    emit(
      state.copyWith(
        status: formErrors.isEmpty && isSignAdded
            ? StateStatus.success
            : StateStatus.error,
        formErrors: formErrors,
      ),
    );

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

  void _onSubmitCurrentForm(
    SubmitCurrentForm event,
    Emitter<WagesFormState> emit,
  ) async {
    final form = state.activeForm;
    if (form == null) return;

    emit(state.copyWith(status: StateStatus.loading));

    await _repository.submitWageForm(form: form);

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