package com.wall.snap.wallpaper.acctivitysnap

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.os.CountDownTimer
import android.view.View
import android.widget.Toast
import com.airbnb.lottie.LottieAnimationView
import com.airbnb.lottie.LottieDrawable
import com.tradplus.ads.base.bean.TPAdInfo
import com.wall.snap.wallpaper.R
import com.wall.snap.wallpaper.ad.AdShowFailed
import com.wall.snap.wallpaper.ad.AdsInsUtil
import com.wall.snap.wallpaper.ad.LoadListener
import com.wall.snap.wallpaper.ad.ShowListener
import com.wall.snap.wallpaper.databinding.ActivitySplashsnapBinding
import com.wall.snap.wallpaper.toolsnap.ComUtilssnap

class SplashsnapActivity : BaseActivity() {

    private var countDownTimer: CountDownTimer? = null
    private lateinit var vb: ActivitySplashsnapBinding

    private val tickInterval = 100L
    private val totalTime = 15_000L

    /**
     * 总 tick 次数 15次
     */
    private val totalTicks = totalTime / tickInterval

    /**
     * 每 tick 增加的进度 0.6666~
     */
    private val normalStep = 100f / totalTicks
    private val fastStep = normalStep * 4   // 加速倍率
    private var currentStep = normalStep
    // 进度控制
    private var progress = 0f

    // 广告状态
    private var adAvailable = false
    private var hasNavigated = false

    // Lottie
    private lateinit var lottieAnimationView: LottieAnimationView

    @SuppressLint("MissingInflatedId")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        vb = ActivitySplashsnapBinding.inflate(layoutInflater)
        ComUtilssnap.initFull(this, true)
        setContentView(vb.root)

        // 1. 进来就 load 广告
        loadSplashAd()

        // 2. 启动进度条（只启动一次）
        startProgressTimer()

        // 3. Lottie 动画
        lottieAnimationView = findViewById(R.id.lottieAnimationView)
        lottieAnimationView.visibility = View.VISIBLE
        lottieAnimationView.setAnimation("xingqiu.json")
        lottieAnimationView.repeatCount = LottieDrawable.INFINITE
        lottieAnimationView.playAnimation()
    }

    private fun startProgressTimer() {
        countDownTimer?.cancel()

        countDownTimer = object : CountDownTimer(totalTime, tickInterval) {

            override fun onTick(millisUntilFinished: Long) {
                progress += currentStep
                if (progress >= 100f) {
                    progress = 100f
                    vb.progressbar.progress = 100
                    cancel()
                    onProgressFinished()
                } else {
                    vb.progressbar.progress = progress.toInt()
                }
            }

            override fun onFinish() {
                // 不使用
            }
        }.start()
    }


    // 进度走完后的统一出口
    private fun onProgressFinished() {
        if (hasNavigated) return

        if (adAvailable) {
            showSplashAd()
        } else {
            navigateToNext()
        }
    }

    private fun loadSplashAd() {
        AdsInsUtil.loadAd(
            act = this,
            adID = AdsInsUtil.Placement.TOP_ON_AD_ONE,
            loadListener = object : LoadListener {

                override fun loaded(ad: TPAdInfo) {
                    adAvailable = true
                    accelerateProgress()
                }

                override fun loadFailed(error: String) {
                    adAvailable = false
                    accelerateProgress()
                }
            }
        )
    }

    // 广告 load 完 → 加速
    private fun accelerateProgress() {
        currentStep = fastStep
    }

    private fun showSplashAd() {
        AdsInsUtil.showAd(
            act = this,
            adID = AdsInsUtil.Placement.TOP_ON_AD_ONE,
            listener = object : ShowListener {

                override fun onAdShown(ad: TPAdInfo?) {}

                override fun onAdShowFailed(error: AdShowFailed?) {
                    navigateToNext()
                }

                override fun onAdClosed() {
                    navigateToNext()
                }
            }
        )
    }

    private fun navigateToNext() {
        if (hasNavigated) return
        hasNavigated = true
        navigateToMainActivity()
    }

    override fun shouldInterceptBackPress(): Boolean = true
    override fun onInterceptBackPressed() {}

    @SuppressLint("QueryPermissionsNeeded")
    private fun navigateToMainActivity() {
        try {
            startActivity(Intent(this, MainsnapActivity::class.java))
            finish()
        } catch (e: Exception) {
            Toast.makeText(this, "跳转失败", Toast.LENGTH_SHORT).show()
            e.printStackTrace()
            finish()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        countDownTimer?.cancel()
        countDownTimer = null
    }
}
