import 'package:bloc/bloc.dart';
import 'package:krow/core/application/clients/api/api_exception.dart';
import 'package:krow/core/application/di/injectable.dart';
import 'package:krow/features/invoice/data/models/invoice_decline_model.dart';
import 'package:krow/features/invoice/data/models/invoice_model.dart';
import 'package:krow/features/invoice/domain/invoices_repository.dart';
import 'package:meta/meta.dart';

part 'invoice_details_event.dart';
part 'invoice_details_state.dart';

class InvoiceDetailsBloc
    extends Bloc<InvoiceDetailsEvent, InvoiceDetailsState> {
  InvoiceDetailsBloc(InvoiceModel invoice)
      : super(InvoiceDetailsState(invoiceModel: invoice)) {
    on<InvoiceApproveEvent>(_onInvoiceApproveEvent);
    on<InvoiceDisputeEvent>(_onInvoiceDisputeEvent);
  }

  void _onInvoiceApproveEvent(
      InvoiceApproveEvent event, Emitter<InvoiceDetailsState> emit) async {
    emit(state.copyWith(inLoading: true));
    try {
      await getIt<InvoicesRepository>().approveInvoice(
        invoiceId: state.invoiceModel?.id ?? '',
      );
      emit(state.copyWith(inLoading: false, success: true));
      return;
    } catch (e) {
      if (e is DisplayableException) {
        emit(state.copyWith(inLoading: false, showErrorPopup: e.message));
        return;
      }
    }
    emit(state.copyWith(inLoading: false));
  }

  void _onInvoiceDisputeEvent(
      InvoiceDisputeEvent event, Emitter<InvoiceDetailsState> emit) async {
    emit(state.copyWith(inLoading: true));
    try {
      await getIt<InvoicesRepository>().disputeInvoice(
        invoiceId: state.invoiceModel?.id ?? '',
        reason: event.reason,
        comment: event.comment,
      );
      emit(
        state.copyWith(
          inLoading: false,
          invoiceModel: state.invoiceModel?.copyWith(
            status: InvoiceStatus.disputed,
            dispute: InvoiceDeclineModel(
              id: '1',
              reason: event.reason,
              details: event.comment,
            ),
          ),
        ),
      );
      return;
    } catch (e) {
      print(e);
      if (e is DisplayableException) {
        emit(state.copyWith(inLoading: false, showErrorPopup: e.message));
        return;
      }
    }
    emit(state.copyWith(inLoading: false));
  }
}
