package com.gamedog.vididin.features.splash

import android.animation.ObjectAnimator
import android.animation.ValueAnimator
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.os.PersistableBundle
import android.view.LayoutInflater
import android.view.animation.LinearInterpolator
import androidx.lifecycle.lifecycleScope
import com.ama.core.architecture.appBase.AppViewsEmptyViewModelActivity
import com.gamedog.statisticreporter.StatisticUtil
import com.gamedog.vididin.main.interfaces.OnTabStyleListener
import com.gamedog.vididin.router.Router
import com.remax.base.report.DataReportManager
import com.remax.bill.ads.AdResult
import com.remax.bill.ads.PreloadController
import com.remax.bill.ads.bidding.AppOpenBiddingInitializer
import com.remax.bill.ads.config.AdConfigManager
import com.remax.bill.ads.ext.AdShowExt
import com.remax.bill.ads.log.AdLogger
import com.viddin.videos.free.R
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.math.ceil
import com.viddin.videos.free.databinding.ActivitySplashBinding as ViewBinding



@AndroidEntryPoint
class SplashActivity : AppViewsEmptyViewModelActivity<ViewBinding>(), OnTabStyleListener {

    private var mStartMs: Long = 0L
    private var isAdLoaded = false
    private var startTime = 0L

    override fun inflateViewBinding(inflater: LayoutInflater) = ViewBinding.inflate(inflater)

    override var mEnableBannerAd = false

    override fun ViewBinding.initViews() {
        startTime = System.currentTimeMillis()

        with(binding) {
        }
    }

    override fun onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) {
        super.onCreate(savedInstanceState, persistentState)
        mStartMs = System.currentTimeMillis()
        StatisticUtil.reportEvents(StatisticUtil.KEY_Loading_Start, mapOf("Time" to (System.currentTimeMillis() - mStartMs)/1000))
    }

    override fun onDestroy() {
        super.onDestroy()
        StatisticUtil.reportEvents(StatisticUtil.KEY_Loading_End, )
    }

    override fun ViewBinding.initWindowInsets() {
        setImmerseRootView(contentRoot)
    }

    override fun ViewBinding.initListeners() {
        startJumpTimer()
        startLoadingAnim()
        initializeApp()
    }

    override fun ViewBinding.initObservers() {
        //TODO("Not yet implemented")
    }

    override fun onTabIsDarkFont(isDarkFont: Boolean) {
        //TODO("Not yet implemented")
    }

    private fun startJumpTimer() {
        lifecycleScope.launch {
            delay(MAX_SPLASH_TIME)
            gotoMain()
        }
    }

    private fun initializeApp() {
        lifecycleScope.launch() {
            try {
                async { performOtherInitializations() }
                val adMobInitDeferred = async { initializeAd() }

                val adMobResult = adMobInitDeferred.await()

                // 处理AdMob初始化结果
                when (adMobResult) {
                    is AdResult.Success -> {
                        // 2. 加载开屏广告
                        showAppOpenAd()
                    }

                    is AdResult.Failure -> {
                        AdLogger.e("AdMob SDK初始化失败: ${adMobResult.error.message}")
                        // 初始化失败，延迟后直接跳转
                        delayAndJumpToMain()
                    }

                    AdResult.Loading -> {
                        AdLogger.d("AdMob SDK初始化中...")
                    }
                }

            } catch (e: Exception) {
                AdLogger.e("应用初始化异常", e)
                delayAndJumpToMain()
            }
        }
    }


    private suspend fun initializeAd(): AdResult<Unit> {
        return AppOpenBiddingInitializer.initialize(this@SplashActivity, R.mipmap.ic_launcher)
    }

    private suspend fun performOtherInitializations() {
        for (i in 0..100 step 1) {
            // 检测到广告已显示，立即设置进度为100
            if (isAdLoaded) {
                //selfBindView.progressBar.progress = 100
                break
            }
            //selfBindView.progressBar.progress = i
            delay(100) // 改为100毫秒，总共10秒完成动画
        }
    }


    private suspend fun showAppOpenAd() {
        if (isAdLoaded) {
            return
        }

        when (val result = AdShowExt.showAppOpenAd(this@SplashActivity) { loaded ->
            isAdLoaded = loaded
            PreloadController.preload(this)
            PreloadController.preloadPangle(this)
            PreloadController.preloadTopOn(this)
            DataReportManager.reportData(
                "loading_page_end", mapOf(
                    "pass_time" to ceil((System.currentTimeMillis() - startTime) / 1000.0).toInt()
                )
            )
        }) {
            is AdResult.Success -> {
                delayAndJumpToMain()
            }

            is AdResult.Failure -> {
                AdLogger.e("开屏广告显示失败: ${result.error.message}")
                // 开屏失败尝试展示插页
                if (AdConfigManager.shouldShowInterstitialAfterAppOpenFailure()) {
                    lifecycleScope.launch {
                        try {
                            when (val interstitialResult = AdShowExt.showInterstitialAd(this@SplashActivity)) {
                                is AdResult.Success -> {
                                    delayAndJumpToMain()
                                }

                                is AdResult.Failure -> {
                                    delayAndJumpToMain()
                                }

                                AdResult.Loading -> {
                                }
                            }

                        } catch (e: Exception) {
                            delayAndJumpToMain()
                        }
                    }
                } else {
                    delayAndJumpToMain()
                }
            }

            AdResult.Loading -> {
                AdLogger.d("开屏广告显示中...")
            }
        }
    }

    private suspend fun delayAndJumpToMain() {
        val elapsedTime = System.currentTimeMillis() - startTime
        val remainingTime = MIN_SPLASH_TIME - elapsedTime

        if (remainingTime > 0) {
            delay(remainingTime)
        }

        gotoMain()
    }

    private fun gotoMain() {
        Router.Main.startActivity(this@SplashActivity)
        finish()
    }

    private fun startLoadingAnim() {
        val imageView = binding.ivAnim
        ObjectAnimator.ofFloat(imageView, "rotation", 0f, 360f).apply {
            duration = 2000L
            interpolator = LinearInterpolator()
            repeatCount = ValueAnimator.INFINITE
            start()
        }
    }

    companion object {
        const val MAX_SPLASH_TIME = 5 * 1000L
        const val MIN_SPLASH_TIME = 2 * 1000L

        internal fun startActivity(activity: Activity) {
            activity.startActivity(Intent(activity.applicationContext, SplashActivity::class.java))
        }
    }

}