import 'package:be_happy/domain/usecase/get_certificates_usecase.dart';
import 'package:be_happy/domain/usecase/get_payment_cards_usecase.dart';
import 'package:be_happy/domain/usecase/purchase_certificate_usecase.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import '../../core/result.dart';
import '../../domain/entities/certificate.dart';
import '../../domain/entities/payment_card.dart';
import '../event/top_up_event.dart';
import '../state/top_up_state.dart';

class TopUpBloc extends Bloc<TopUpEvent, TopUpState> {
  final GetCertificatesUsecase getCertificatesUsecase;
  final PurchaseCertificateUsecase purchaseCertificateUsecase;
  final GetPaymentCardsUsecase getUserCards;

  TopUpBloc({
    required this.getCertificatesUsecase,
    required this.purchaseCertificateUsecase,
    required this.getUserCards,
  }) : super(TopUpState(isLoading: true)) {
    on<LoadTopUpData>((event, emit) async {
      emit(state.copyWith(isLoading: true));

      // Запускаем оба запроса параллельно
      final results = await Future.wait([
        getCertificatesUsecase(),
        getUserCards(),
      ]);

      final certResult = results[0] as Result<List<Certificate>>;
      final cardResult = results[1] as Result<List<PaymentCard>>;

      switch ((certResult, cardResult)) {
        case (Success(data: final certs), Success(data: final cards)):
          emit(
            state.copyWith(
              certificates: certs,
              cards: cards,
              selectedTariff: certs!.length > 1
                  ? certs[1]
                  : (certs.isNotEmpty ? certs.first : null),

              selectedCard: cards!.isEmpty
                  ? null
                  : cards.firstWhere(
                      (c) => c.isMain,
                      orElse: () => cards.first,
                    ),
              isLoading: false,
            ),
          );

        case (
          Success<List<Certificate>>(data: null),
          Failure<List<PaymentCard>>(),
        ):
          // TODO: Handle this case.
          throw UnimplementedError();
        case (
          Success<List<Certificate>>(data: [...]),
          Failure<List<PaymentCard>>(),
        ):
          // TODO: Handle this case.
          throw UnimplementedError();
        case (Failure<List<Certificate>>(), _):
          // TODO: Handle this case.
          throw UnimplementedError();
      }
    });
    on<SelectCertificate>(
      (event, emit) => emit(state.copyWith(selectedTariff: event.certificate)),
    );
    on<SelectCard>(
      (event, emit) => emit(state.copyWith(selectedCard: event.card)),
    );
    on<ToggleAgreement>(
      (event, emit) => emit(state.copyWith(isAgreed: event.value)),
    );
  }
}
