package com.base.filerecoveryrecyclebin.ads.max

import android.animation.ObjectAnimator
import android.app.Activity
import android.app.Dialog
import android.os.Handler
import android.os.Looper
import android.view.View
import android.view.Window
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import com.applovin.mediation.MaxAd
import com.applovin.mediation.MaxAdListener
import com.applovin.mediation.MaxError
import com.applovin.mediation.ads.MaxAppOpenAd
import com.base.filerecoveryrecyclebin.GlobalConfig
import com.base.filerecoveryrecyclebin.MyApplication.Companion.isInterOpenShowing
import com.base.filerecoveryrecyclebin.R
import com.base.filerecoveryrecyclebin.activity.splash.Splash2Activity
import com.base.filerecoveryrecyclebin.ads.AdDisplayUtils
import com.base.filerecoveryrecyclebin.help.ConfigHelper
import com.base.filerecoveryrecyclebin.utils.EventUtils
import com.base.filerecoveryrecyclebin.utils.LogEx
import org.json.JSONObject
import java.util.UUID

object AdMaxOpenUtils {
    private val TAG = "AdMaxOpenUtils"
    private var appOpenAd: MaxAppOpenAd? = null
    private var openLoadTime = Long.MAX_VALUE
    private var onHidden: (() -> Unit)? = null
    private var loadingListener: ((flag: Boolean) -> Unit)? = null
    private var activityString = ""

    private fun setListener(activity: Activity) {
        activityString = activity::class.java.toString().split(".").last()
        if (appOpenAd == null) {
            appOpenAd = MaxAppOpenAd(GlobalConfig.ID_MAX_OPEN, activity)

            appOpenAd?.setListener(object : MaxAdListener {
                override fun onAdLoaded(p0: MaxAd) {
                    LogEx.logDebug(TAG, "广告拉取成功")
                    openLoadTime = System.currentTimeMillis()
                    loadingListener?.invoke(true)
                    loadingListener = null
                    AdMaxEvent.pullAd(p0, "openAd")
                }

                override fun onAdLoadFailed(p0: String, p1: MaxError) {
                    LogEx.logDebug(TAG, "广告拉取失败了，onAdLoadFailed:" + p0)
                    LogEx.logDebug(TAG, "广告拉取失败了，onAdLoadFailed:" + p1.message.toString())
                    LogEx.logDebug(TAG, "广告拉取失败了，onAdLoadFailed:" + p1.code)
                    loadingListener?.invoke(false)
                    loadingListener = null
                    AdDisplayUtils.getInstance().incrementAdRequestFailCount()
                    val reqId = UUID.randomUUID().toString()
                    AdMaxEvent.pullAd(null, "openAd", reqId = reqId, error = p1.message, code = p1.code)
                }

                override fun onAdDisplayed(p0: MaxAd) {
                    AdDisplayUtils.getInstance().incrementAdDisplayCount()
                    AdMaxEvent.showAd(p0, "openAd", activityString)

                    isInterOpenShowing = true
                }

                override fun onAdHidden(p0: MaxAd) {
                    LogEx.logDebug(TAG, "onAdHidden")
                    onHidden?.invoke()
                    onHidden = null
                    loadAppOpenAd(activity)

                    isInterOpenShowing = false
                }

                override fun onAdDisplayFailed(p0: MaxAd, p1: MaxError) {
                    LogEx.logDebug(TAG, "onAdDisplayFailed")
                    onHidden?.invoke()
                    onHidden = null
                    loadAppOpenAd(activity)
                    val obj = JSONObject()
                    obj.put("code", p1.code)
                    obj.put("reason", p1.message)
                    obj.put("ad_unit", "openAd")
                    EventUtils.event("ad_show_error", ext = obj)

                    isInterOpenShowing = false
                }

                override fun onAdClicked(p0: MaxAd) {
                    AdDisplayUtils.getInstance().incrementAdClickCount()
                    AdMaxEvent.clickAd(p0, "openAd")
                }

            })

            appOpenAd?.setRevenueListener(AdMaxEvent.EventOnPaidEventListener())
        }
    }

    fun showAppOpenAd(
        activity: Activity,
        showBefore: ((flag: Boolean) -> Unit)? = null,
        loadCallBack: ((loaded: Boolean) -> Unit)? = null,
        onHidden: (() -> Unit)? = null
    ) {

        setListener(activity)

        if (activity.isFinishing || activity.isDestroyed) {
            return
        }

        if (!AdDisplayUtils.getInstance().shouldShowAd("openAd")) {
            LogEx.logDebug(TAG, "!shouldShowAd")
            onHidden?.invoke()
            return
        }

        if (System.currentTimeMillis() - openLoadTime > 1000 * 60 * 60) {
            LogEx.logDebug(TAG, "openLoadTime > ")
            onHidden?.invoke()
            val obj2 = JSONObject()
            obj2.put("ad_unit", "openAd")
            EventUtils.event("ad_expire", ext = obj2)
            appOpenAd?.loadAd()
        }



        LogEx.logDebug(TAG, "showAppOpenAd")
        val obj1 = JSONObject()
        obj1.put("ad_unit", "openAd")
        EventUtils.event("ad_prepare_show", ext = obj1)

        isInterOpenShowing = false

        if (appOpenAd?.isReady == true) {
            LogEx.logDebug(TAG, "广告准备好了，展示广告")
            AdMaxOpenUtils.onHidden = onHidden
            LogEx.logDebug(TAG, "Splash2Activity.isSplashHot=${Splash2Activity.isSplashHot}")
            showBefore?.invoke(true)
            if (Splash2Activity.isSplashHot) {
                startCountdownAndShowAd {
                    appOpenAd?.showAd()
                }
            } else {
                appOpenAd?.showAd()
            }
        } else {
            val obj = JSONObject()
            obj.put("reason", "no cache ad")
            obj.put("ad_unit", "openAd")
            EventUtils.event("ad_nocache_pull", ext = obj)
            LogEx.logDebug(TAG, "展示时候，发现广告需要拉取")
            val loaded = loadAppOpenAd(activity)
            if (loaded) {
                loadingListener = { loadResult ->
                    loadCallBack?.invoke(loadResult)
                    LogEx.logDebug(TAG, "loadingListener callback")
                    if (appOpenAd?.isReady == true) {
                        AdMaxOpenUtils.onHidden = onHidden
                        showBefore?.invoke(true)
                        LogEx.logDebug(TAG, "Splash2Activity.isSplashHot=${Splash2Activity.isSplashHot}")
                        if (Splash2Activity.isSplashHot) {
                            startCountdownAndShowAd {
                                appOpenAd?.showAd()
                            }
                        } else {
                            appOpenAd?.showAd()
                        }
                    } else {
                        showBefore?.invoke(false)
                        onHidden?.invoke()
                    }
                }
            } else {
                onHidden?.invoke()
            }

        }
    }

    fun loadAppOpenAd(activity: Activity): Boolean {
        setListener(activity)

        if (!AdDisplayUtils.getInstance().shouldShowAd("openAd")) {
            LogEx.logDebug(TAG, "!shouldShowAd")
            return false
        }

        val reqId = UUID.randomUUID().toString()
        val obj = JSONObject()
        obj.put("req_id", reqId)
        obj.put("ad_type", "openAd")
        EventUtils.event("ad_pull_start", ext = obj)
        appOpenAd?.loadAd()
        AdDisplayUtils.getInstance().incrementAdRequestCount()
        return true
    }

    fun isOpenAdLoaded(): Boolean {
        return appOpenAd?.isReady == true
    }


    private fun showLoadingScreen(activity: Activity, callBack: (() -> Unit)) {
        if (activity.isFinishing || activity.isDestroyed) {
            return
        }
        if (loadingDialog == null) {
            loadingDialog = Dialog(activity).apply {
                requestWindowFeature(Window.FEATURE_NO_TITLE)
                setContentView(R.layout.dialog_loading)
                setCancelable(false)
                window?.setBackgroundDrawable(ContextCompat.getDrawable(activity, R.drawable.bg_loadingads))
            }
        }

        val imageView = loadingDialog?.findViewById<ImageView>(R.id.loading_image)
        val countdownTextView = loadingDialog?.findViewById<TextView>(R.id.countdown_text)

        imageView?.let { startRotateAnimation(it) } // 开始旋转动画

        // 控制倒计时文本是否显示
        countdownTextView?.visibility = View.VISIBLE

        loadingDialog?.show()

        startCountdownAndShowAd(callBack = callBack)
    }

    private fun startRotateAnimation(imageView: ImageView) {
        ObjectAnimator.ofFloat(imageView, "rotation", 0f, 360f).apply {
            duration = 3000 // 持续 3 秒
            repeatCount = ObjectAnimator.INFINITE // 无限循环
            start()
        }
    }


    private var countdown = 3 // 初始倒计时
    private var countdownHandler: Handler? = null
    private var loadingDialog: Dialog? = null
    private fun startCountdownAndShowAd(callBack: (() -> Unit)?) {
        countdown = 3

        updateCountdownText(count = countdown)  // 显示倒计时文本

        countdownHandler?.removeCallbacksAndMessages(null)
        countdownHandler = Handler(Looper.getMainLooper())
        countdownHandler?.post(object : Runnable {
            override fun run() {
                if (countdown <= 0) {
                    loadingDialog?.dismiss()
                    Splash2Activity.progressCallBack = null
                    callBack?.invoke()
                } else {
                    Splash2Activity.progressCallBack?.invoke()
                    updateCountdownText(countdown)  // 更新倒计时文本
                    countdown--
                    LogEx.logDebug(TAG, "startCountdownAndShowAd countdown=$countdown")
                    countdownHandler?.postDelayed(this, 1000)
                }
            }
        })
    }

    // 更新倒计时文本并控制是否显示括号和数字
    private fun updateCountdownText(count: Int) {
        val countdownTextView = loadingDialog?.findViewById<TextView>(R.id.countdown_text)
//        LogEx.logDebug(AdmobOpenUtils.TAG, "updateCountdownText $count countdownTextView=$countdownTextView")
        countdownTextView?.text = "Ads are about to be shown($count)"
        countdownTextView?.visibility = View.VISIBLE
    }
}

