import 'package:be_happy/core/result.dart';
import 'package:be_happy/domain/entities/subscription.dart';
import 'package:be_happy/domain/usecase/activate_subscription_usecase.dart';
import 'package:be_happy/domain/usecase/get_subscription_by_id_usecase.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import '../../domain/entities/client_subscription.dart';
import '../../domain/usecase/get_client_subscriptions_usecase.dart';
import '../event/subscription_details_event.dart';
import '../state/susbcription_details_state.dart';

class SubscriptionDetailsBloc
    extends Bloc<SubscriptionDetailsEvent, SubscriptionDetailsState> {
  final GetSubscriptionByIdUsecase getSubscriptionByIdUsecase;
  final ActivateSubscriptionUsecase activateSubscriptionUsecase;
  final GetClientSubscriptionsUsecase getClientSubscriptionsUsecase;

  SubscriptionDetailsBloc(
    this.getSubscriptionByIdUsecase,
    this.activateSubscriptionUsecase,
    this.getClientSubscriptionsUsecase,
  ) : super(DetailsLoading()) {
    on<LoadDetailsEvent>((event, emit) async {
      emit(DetailsLoading());
      try {
        final result = await getSubscriptionByIdUsecase(event.subscriptionId);

        final clientSubsResult = await getClientSubscriptionsUsecase();
        bool isPurchased = false;

        switch (clientSubsResult) {
          case Success<List<ClientSubscription>>():
            isPurchased = clientSubsResult.data?.any(
                  (element) => element.subscriptionId == event.subscriptionId,
            ) ?? false;
            break;

          case Failure<List<ClientSubscription>>():
            isPurchased = false;
            break;
        }

        switch (result) {
          case Success<Subscription>():
            final sub = result.data;
            if (sub == null) return;

            emit(
              DetailsContentState(
                subscription: sub,
                selectedPeriod: sub.options.first,
                isAlreadyPurchased: isPurchased,
              ),
            );
            break;
          case Failure<Subscription>():
            emit(DetailsError("Ошибка при запросе данных"));
            break;
        }
      } catch (e) {
        emit(DetailsError("Не удалось загрузить данные"));
      }
    });

    on<SelectPeriodEvent>((event, emit) {
      if (state is DetailsContentState) {
        emit(
          (state as DetailsContentState).copyWith(selectedPeriod: event.period),
        );
      }
    });

    on<ToggleAgreementEvent>((event, emit) {
      if (state is DetailsContentState) {
        emit((state as DetailsContentState).copyWith(isAgreed: event.value));
      }
    });

    on<ActivateSubscriptionPressed>((event, emit) async {
      switch (state) {
        case DetailsContentState contentState:
          if (!contentState.isAgreed) {
            return;
          }

          final result = await activateSubscriptionUsecase(contentState.selectedPeriod.id);

          if (result is Success) {
            emit(contentState.copyWith(isSuccess: true));
          } else {
          }
          break;
        default:
          break;
      }
    });
  }
}
