package com.base.datarecovery.ads.max

import android.annotation.SuppressLint
import android.app.Activity
import com.applovin.mediation.MaxAd
import com.applovin.mediation.MaxAdListener
import com.applovin.mediation.MaxError
import com.applovin.mediation.ads.MaxInterstitialAd
import com.base.datarecovery.R
import com.base.datarecovery.ads.AdDisplayUtils
import com.base.datarecovery.help.ConfigHelper
import com.base.datarecovery.utils.EventUtils
import com.base.datarecovery.utils.LogEx
import com.base.datarecovery.view.CustomDialog
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.json.JSONObject
import java.util.concurrent.TimeUnit
import kotlin.math.min
import kotlin.math.pow

object AdMaxInterstitialUtils {

    private val TAG = "AdMaxInterstitialUtils"
    private var interstitialAd: MaxInterstitialAd? = null
    private var interLoadTime = Long.MAX_VALUE
    private var onHidden: (() -> Unit)? = null
    private var loadingListener: (() -> Unit)? = null
    private var retryAttempt = 0
    private var maxRetryAttempt = 8

    @SuppressLint("StaticFieldLeak")
    private var customDialog: CustomDialog? = null

    private fun setListener(activity: Activity) {
        if (interstitialAd == null) {
            interstitialAd = MaxInterstitialAd(ConfigHelper.interAdMaxId, activity)
        }

        interstitialAd?.setListener(object : MaxAdListener {
            override fun onAdLoaded(p0: MaxAd) {
                LogEx.logDebug(TAG, "onAdLoaded")
                loadingListener?.invoke()
                interLoadTime = System.currentTimeMillis()
                retryAttempt = 0
            }

            override fun onAdLoadFailed(p0: String, p1: MaxError) {
                LogEx.logDebug(TAG, "onAdLoadFailed")
                AdDisplayUtils.getInstance().incrementAdRequestFailCount()
                retryAttempt++
                val delayMillis = TimeUnit.SECONDS.toMillis(2.0.pow(min(6, retryAttempt)).toLong())
                LogEx.logDebug(TAG, "onAdLoadFailed retryAttempt=$retryAttempt delayMillis=$delayMillis")
                if (retryAttempt == 2) {
                    onHidden?.invoke()
                    customDialog?.dismiss()
                }
                if (retryAttempt <= maxRetryAttempt) {
                    MainScope().launch {
                        delay(delayMillis)
                        interstitialAd?.loadAd()
                    }
                } else {
                    retryAttempt = 0
                }

            }

            override fun onAdDisplayed(p0: MaxAd) {
                LogEx.logDebug(TAG, "onAdDisplayed")
                AdDisplayUtils.getInstance().incrementAdDisplayCount()
            }

            override fun onAdHidden(p0: MaxAd) {
                LogEx.logDebug(TAG, "onAdHidden")
                onHidden?.invoke()
                interstitialAd?.loadAd()
            }

            override fun onAdClicked(p0: MaxAd) {
                LogEx.logDebug(TAG, "onAdClicked")
                AdDisplayUtils.getInstance().incrementAdClickCount()
            }


            override fun onAdDisplayFailed(p0: MaxAd, p1: MaxError) {
                LogEx.logDebug(TAG, "onAdDisplayFailed")
            }
        })
    }

    fun showInterstitialAd(
        activity: Activity,
        isReLoadAd: Boolean = false,
        isShowDialog: Boolean = true,
        onHidden: (() -> Unit)? = null
    ) {
        setListener(activity)

        if (activity.isFinishing || activity.isDestroyed) {
            return
        }
        val obj1 = JSONObject()
        obj1.put("ad_unit", "interAd")
        EventUtils.event("ad_prepare_show", ext = obj1)

        if (isAdExpired()) {
            val obj2 = JSONObject()
            obj2.put("ad_unit", "interAd")
            EventUtils.event("ad_expire", ext = obj2)
            interstitialAd?.loadAd()
            onHidden?.invoke()
            return
        }


        if (!AdDisplayUtils.getInstance().shouldShowAd()) {
            onHidden?.invoke()
            return
        }

        AdMaxInterstitialUtils.onHidden = onHidden
        if (interstitialAd?.isReady == true) {
            LogEx.logDebug(TAG, "isReady=true")
            showIntervalDialogAndShowAd(activity, isShowDialog, onHidden, 2)
        } else {
            interstitialAd?.loadAd()
            LogEx.logDebug(TAG, "isReady=false")
            showAdDialogAndLoadInterstitial(activity, isShowDialog)
        }

    }

    private fun isAdExpired(): Boolean {
        return System.currentTimeMillis() - interLoadTime > 1000 * 60 * 60
    }

    private fun showIntervalDialogAndShowAd(
        activity: Activity,
        isShowDialog: Boolean,
        onHidden: (() -> Unit)?,
        interval: Int
    ) {
//        if (!isShowDialog) {
//            return
//        }
//
//        if (customDialog != null && customDialog?.isShowing == true) {
//            return  // 如果对话框已经显示，则不再显示
//        }
//
//        customDialog = CustomDialog(activity, R.layout.dialog_ad_loading)
//        customDialog?.setCountdownText(R.id.dialog_ad_loading_text)
//        val countdownTimer = object : CountDownTimer((interval * 1000).toLong(), 1000) {
//            override fun onTick(millisUntilFinished: Long) {
//                val seconds = (millisUntilFinished / 1000).toInt()
//                customDialog?.updateCountdownText("Advertising in preparation ($seconds" + "s)...")
//            }
//
//            override fun onFinish() {
//                if (!activity.isDestroyed && !activity.isFinishing) {
//                    customDialog?.dismiss()
//                }
//                customDialog = null
//                LogEx.logDebug(TAG, "onFinish")
        interstitialAd?.showAd()
//            }
//        }
//        countdownTimer.start()
//        customDialog?.show()
    }

    private fun showAdDialogAndLoadInterstitial(
        activity: Activity,
        isShowDialog: Boolean,
    ) {
        if (!isShowDialog) {
            return
        }

        if (!activity.isFinishing && !activity.isDestroyed) {
            customDialog = CustomDialog(activity, R.layout.dialog_ad_loading)
            // 设置对话框的样式和内容
            customDialog?.show()
        }
        loadingListener = {
            customDialog?.dismiss()
            interstitialAd?.showAd()
            loadingListener = null
        }

    }

    fun loadInterstitialAd(activity: Activity) {
        setListener(activity)
        if (AdMaxInit.isAdMaxInit.get()) {
            LogEx.logDebug(TAG, "loadInterstitialAd")
            interstitialAd?.loadAd()
        }
    }


}