package com.wall.dream.wallpapers.acacctivity

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.os.CountDownTimer
import android.widget.Toast
import androidx.core.view.ViewCompat
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import com.tradplus.ads.base.bean.TPAdInfo
import com.wall.dream.wallpapers.R
import com.wall.dream.wallpapers.ad.AdShowFailed
import com.wall.dream.wallpapers.ad.AdsInsUtil
import com.wall.dream.wallpapers.ad.LoadListener
import com.wall.dream.wallpapers.ad.ShowListener
import com.wall.dream.wallpapers.databinding.ViewSplashBinding
import kotlin.jvm.java

class SplashActivity : BaseActivity() {

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

    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

    @SuppressLint("MissingInflatedId")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        vb = ViewSplashBinding.inflate(layoutInflater)
        setContentView(vb.root)

        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        val windowInsetsController = WindowCompat.getInsetsController(window, window.decorView)
        windowInsetsController.isAppearanceLightStatusBars = true//状态栏文字颜色

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

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

    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, MainViewActivity::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
    }
}
