// Author: fengshengxiong
// Date: 2024/5/20
// Description: 插页广告管理

import 'dart:async';
import 'dart:io';

import 'package:applovin_max/applovin_max.dart';
import 'package:flutter_translate/common/hive/remote_config_box.dart';
import 'package:flutter_translate/common/utils/log_utils.dart';
import 'package:flutter_translate/firebase/firebase_analytics_manager.dart';
import 'package:flutter_translate/pages/launch/launch_controller.dart';
import 'package:get/get.dart';

class InterstitialAdManager {
  InterstitialAdManager._();

  static final InterstitialAdManager _instance = InterstitialAdManager._();

  factory InterstitialAdManager() => _instance;

  /// sdkKey
  final String applovinKey = '3DO3vx0lv7JMzcKUzBTDPvC_khddtPtpMbruQtJPWTzR8LhPMWHzoPrCWsIz1TSHRclaIWfqyPxLIHJXJR7DaN';

  /// 广告单元Id
  /// 依次是开屏、页面返回按钮、面对面翻译、ocr识别
  final List<String> adIds = [
    Platform.isAndroid ? '' : '1cd8a161ef146654',
    Platform.isAndroid ? '' : 'ba63c3d53e30fac4',
    Platform.isAndroid ? '' : '60618d77c79b5d88',
    Platform.isAndroid ? '' : 'a74b32980e93e067',
  ];

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

  /// 是否显示
  bool isShowingAd = false;

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

  Function()? onTap;

  /// 初始化
  Future<void> init() async {
    try {
      MaxConfiguration? configuration = await AppLovinMAX.initialize(applovinKey);
      if (configuration != null) {
        isInitialized = true;
        _attachAdListeners();
      }
    } catch (e) {
      Log.d(e.toString());
    }
  }

  /// 广告监听
  void _attachAdListeners() {
    AppLovinMAX.setInterstitialListener(InterstitialListener(
      onAdLoadedCallback: (ad) async {
        Log.d('插页广告加载成功:${ad.adUnitId}');
        if (ad.adUnitId == adIds[0]) {
          if (Get.isRegistered<LaunchController>()) {
            LaunchController.to.editChangeValue();
          }
        }
        // _interstitialRetryAttempt = 0;
      },
      onAdLoadFailedCallback: (adUnitId, error) {
        Log.d('插页广告加载失败adUnitId:$adUnitId,code:${error.code},message:${error.message}');
        // Applovin建议您以指数级更高的延迟重试，最大延迟可达64秒
        // _interstitialRetryAttempt = _interstitialRetryAttempt + 1;
        // if (_interstitialRetryAttempt > _maxExponentialRetryCount) return;
        // int retryDelay = pow(2, min(_maxExponentialRetryCount, _interstitialRetryAttempt)).toInt();

        Future.delayed(const Duration(seconds: 10), () {
          bool adSwitch = RemoteConfigBox().getAdSwitch();
          if (adSwitch) {
            AppLovinMAX.loadInterstitial(adUnitId);
          }
        });
      },
      onAdDisplayedCallback: (ad) {
        Log.d('插页广告显示成功:${ad.adUnitId}');
        isShowingAd = true;
        FirebaseAnalyticsManager.logAdsShow();
      },
      onAdDisplayFailedCallback: (ad, error) {
        Log.d('插页广告显示失败adUnitId:${ad.adUnitId},code:${error.code},message:${error.message}');
        isShowingAd = false;

        _handleOnTap();
      },
      onAdClickedCallback: (ad) {},
      onAdHiddenCallback: (ad) {
        Log.d('插页广告关闭:${ad.adUnitId}');
        isShowingAd = false;

        bool adSwitch = RemoteConfigBox().getAdSwitch();
        if (adSwitch) {
          AppLovinMAX.loadInterstitial(ad.adUnitId);
        }
        _handleOnTap();
      },
    ));
  }

  Future<void> loadAllAd() async {
    bool adSwitch = RemoteConfigBox().getAdSwitch();
    if (!adSwitch) {
      return;
    }
    if (!isInitialized) {
      return;
    }
    for (var adId in adIds) {
      bool isReady = (await AppLovinMAX.isInterstitialReady(adId))!;
      if (!isReady) {
        Log.d('插页广告正在加载:$adId');
        AppLovinMAX.loadInterstitial(adId);
      }
    }
  }

  /// 显示插页广告，如果准备好
  Future<void> showAdIfReady(String adUnitId, {Function()? onTap}) async {
    if (onTap != null) {
      this.onTap = onTap;
    }
    bool adSwitch = RemoteConfigBox().getAdSwitch();
    if (!adSwitch) {
      _handleOnTap();
      return;
    }
    if (!isInitialized) {
      _handleOnTap();
      return;
    }
    bool isReady = (await AppLovinMAX.isInterstitialReady(adUnitId))!;
    if (isReady) {
      if (isShowingAd) {
        Log.d('尝试在已显示广告的情况下显示广告');
        _handleOnTap();
        return;
      }
      AppLovinMAX.showInterstitial(adUnitId);
    } else {
      _handleOnTap();
      AppLovinMAX.loadInterstitial(adUnitId);
    }
  }

  void _handleOnTap() {
    if (onTap != null) {
      onTap!();
      onTap = null;
    }
  }
}