import 'dart:async';
import 'dart:math';

import 'package:applovin_max/applovin_max.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:wallpaperx/common/utils/log_print.dart';
import 'package:wallpaperx/common/utils/shared_util.dart';
import 'package:wallpaperx/firebase/firebase_analytics_manager.dart';

class ApplovinUtil {
  ApplovinUtil._();

  static final ApplovinUtil _instance = ApplovinUtil._();

  factory ApplovinUtil() => _instance;

  /// sdkKey
  final String applovinKey =
      'HXOh4UBLahW9KzBBrxqwniKOvfD_JEDJgE9y2rv8DlmJaJ6xPEXUmmJyeAg0xipqdH_EiHg5NsnvfmIHubSu1k';

  /// 广告单元Id
  final String adUnitId = 'f4d33bc86b44eb24';

  final List<String> adUnitIds = [
    'e0ac389b7746be38',
    'a8ecc9c457dee7bf',
    'f4231f22c0314229',
  ];

  /// 是否已初始化
  bool isInitialized = false;

  /// 是否是启动屏幕
  bool isSplashScreen = true;

  /// 重试计数
  final _maxExponentialRetryCount = 6;
  var _interstitialRetryAttempt = 0;

  /// 初始化
  Future<void> initApplovin() async {
    MaxConfiguration? configuration = await AppLovinMAX.initialize(applovinKey);
    if (configuration != null) {
      isInitialized = true;
    }
  }

  /// 初始化插页广告
  void initializeInterstitialAds({required Function() onGoHomeTap}) {
    if (isInitialized) {
      AppLovinMAX.setInterstitialListener(InterstitialListener(
        onAdLoadedCallback: (ad) async {
          LogPrint.d('AdLoadedSuccess:${ad.adUnitId}');
          if (ad.adUnitId == adUnitId && isSplashScreen) {
            await showAdIfReady(adUnitId: adUnitId);
            AppLovinMAX.loadInterstitial(adUnitId);
            isSplashScreen = false;
            onGoHomeTap();
          }
          _interstitialRetryAttempt = 0;
        },
        onAdLoadFailedCallback: (adUnitId, error) {
          LogPrint.d(
            'AdLoadFailed:$adUnitId,code:${error.code},message:${error.message}',
          );
          if (adUnitId == this.adUnitId && isSplashScreen) {
            isSplashScreen = false;
            onGoHomeTap();
          }
          // Applovin建议您以指数级更高的延迟重试，最大延迟可达64秒
          _interstitialRetryAttempt = _interstitialRetryAttempt + 1;
          if (_interstitialRetryAttempt > _maxExponentialRetryCount) return;
          int retryDelay = pow(
              2,
              min(
                _maxExponentialRetryCount,
                _interstitialRetryAttempt,
              )).toInt();

          Future.delayed(Duration(milliseconds: retryDelay * 1000), () {
            AppLovinMAX.loadInterstitial(adUnitId);
          });
        },
        onAdDisplayedCallback: (ad) {
          LogPrint.d('AdDisplayedSuccess:${ad.adUnitId}');
          UPCache.getInstance().setData<int>(
            "lastAdTime",
            DateTime.now().millisecondsSinceEpoch,
          );
          // 打点
          FirebaseAnalyticsManager.logAdImpression(
              ad.adUnitId, ad.networkName, 1, 1, 0);
        },
        onAdDisplayFailedCallback: (ad, error) {
          LogPrint.d(
            'AdDisplayFailed:${ad.adUnitId},code:${error.code},message:${error.message}',
          );
          // 打点
          FirebaseAnalyticsManager.logAdImpression(
              ad.adUnitId, ad.networkName, 1, 0, 1);
        },
        onAdClickedCallback: (ad) {},
        onAdHiddenCallback: (ad) {
          LogPrint.d('AdHidden:${ad.adUnitId}');
          UPCache.getInstance().setData<int>(
            "lastAdTime",
            DateTime.now().millisecondsSinceEpoch,
          );
          AppLovinMAX.loadInterstitial(ad.adUnitId);
        },
      ));

      AppLovinMAX.loadInterstitial(adUnitId);
      for (var e in adUnitIds) {
        AppLovinMAX.loadInterstitial(e);
      }
    }
  }

  /// 显示插页广告，如果准备好
  Future showAdIfReady({String? adUnitId}) async {
    bool? showAd = UPCache.getInstance().get<bool>("showAd")??false;
    if (!showAd) return;

    final packageInfo = await PackageInfo.fromPlatform();
    String version = UPCache.getInstance().get<String>("version")??"";
    if (version == packageInfo.version) return;

    int lastAdTime = UPCache.getInstance().get<int>("lastAdTime") ?? 0;
    int now = DateTime.now().millisecondsSinceEpoch;
    DateTime timestamp1 = DateTime.fromMillisecondsSinceEpoch(lastAdTime);
    DateTime timestamp2 = DateTime.fromMillisecondsSinceEpoch(now);
    Duration difference = timestamp2.difference(timestamp1);
    if (difference.inSeconds <= 5) return;

    if (!isInitialized) return;
    adUnitId ??= (adUnitIds..shuffle()).toList()[0];
    bool isReady = (await AppLovinMAX.isInterstitialReady(adUnitId))!;
    LogPrint.d("adUnitId:$adUnitId | isReady:$isReady");
    if (isReady) {
      AppLovinMAX.showInterstitial(adUnitId);
    } else {
      AppLovinMAX.loadInterstitial(adUnitId);
    }
  }
}
