import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:kasy_kit/core/data/api/analytics_api.dart';
import 'package:kasy_kit/core/theme/theme.dart';
import 'package:kasy_kit/features/subscription/providers/models/premium_state.dart';
import 'package:kasy_kit/features/subscription/providers/premium_page_provider.dart';
import 'package:kasy_kit/features/subscription/ui/component/active_premium_content.dart';
import 'package:kasy_kit/features/subscription/ui/component/premium_page_factory.dart';
import 'package:kasy_kit/features/subscription/ui/widgets/paywall_empty_state.dart';
import 'package:kasy_kit/i18n/translations.g.dart';

class PremiumPageArgs {
  // The redirect route to navigate to after the purchase
  final String? redirect;
  // The delay to show the close button
  final int? delayCloseMs;
  // Whether to show the trial bottom sheet when the user skip the purchase
  final bool? showTrialBottomSheet;

  const PremiumPageArgs({
    this.redirect,
    this.delayCloseMs,
    this.showTrialBottomSheet = false,
  });
}

/// The premium page is the page where the user can subscribe to the premium offer
/// It's also named as Paywall
///
/// - This page is responsible for displaying the offers or the active subscription
/// - It also handles the purchase and restore of the subscription
/// - It also handles the redirection after the purchase see [PremiumPageArgs]
class PremiumPage extends ConsumerWidget {
  final PremiumPageArgs? args;
  final PaywallFactory? paywall;

  const PremiumPage({super.key, this.args, this.paywall});

  bool get hasRedirect => args?.redirect != null;

  void _handleRedirection(BuildContext context) {
    if (hasRedirect) {
      context.go(args!.redirect!);
    }
  }

  PremiumStateNotifier getNotifier(WidgetRef ref) =>
      ref.read(premiumStateProvider.notifier);

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final premiumState = ref.watch(premiumStateProvider);

    /// ===============================================
    /// This is an example of how to get the paywall from the remote config
    /// You can use this to test different paywalls
    /// ===============================================
    // final configuredPaywall = ref
    //     .read(remoteConfigApiProvider) //
    //     .subscription
    //     .paywall;

    // final paywallFactory = switch (configuredPaywall) {
    //   'withSwitch' => PaywallFactory.withSwitch,
    //   _ => PaywallFactory.basic,
    // };

    final paywallFactory = paywall ?? PaywallFactory.minimal;

    return switch (premiumState) {
      AsyncError() => Center(child: Text(t.premium.error_loading)),
      AsyncLoading() => Center(
        child: CircularProgressIndicator.adaptive(
          valueColor: AlwaysStoppedAnimation<Color>(context.colors.onPrimary),
        ),
      ),
      AsyncData(:final value) => switch (value) {
        final PremiumStateActive _ => ActivePremiumContent(
          onTap: (String reason) async {
            await getNotifier(ref).saveUnsubscribeReason(reason);
            await getNotifier(ref).unsubscribe();
          },
          onExit: () {
            if (hasRedirect) {
              _handleRedirection(context);
            } else if (context.canPop()) {
              context.pop();
            } else {
              context.go('/');
            }
          },
        ),
        final PremiumStateSending data => paywallFactory.buildSending(
          offers: data.offers,
          selectedOffer: data.selectedOffer,
          onSelectItem: (offer) => getNotifier(ref).selectOffer(offer),
        ),
        PremiumStateData(offers: final offers) when offers.isEmpty =>
          PaywallEmptyState(
            onSkip: () {
              ref.read(analyticsApiProvider).logEvent('premium_empty_exit', {});
              if (hasRedirect) {
                _handleRedirection(context);
              } else if (context.canPop()) {
                context.pop();
              } else {
                context.go('/');
              }
            },
            onTapRestore: () =>
                getNotifier(ref).restore(redirectRoute: args?.redirect),
          ),
        final PremiumStateData data => paywallFactory.build(
          offers: data.offers,
          selectedOffer: data.selectedOffer,
          onSelectItem: (offer) => getNotifier(ref).selectOffer(offer),
          onSkip: () {
            final analyticsApi = ref.read(analyticsApiProvider);
            analyticsApi.logEvent('premium_exit', {});
            if (hasRedirect) {
              _handleRedirection(context);
            } else if (context.canPop()) {
              context.pop();
            } else {
              context.go('/');
            }
          },
          onTapRestore: () =>
              getNotifier(ref).restore(redirectRoute: args?.redirect),
          onTap: () => getNotifier(ref).purchase(
            paywall: paywallFactory.name,
            redirectRoute: args?.redirect,
          ),
        ),
      },
    };
  }
}
