package com.app.input.breeze.board.uiactivity

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ObjectAnimator
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.os.CountDownTimer
import android.os.Handler
import android.os.Looper
import android.view.View
import android.view.animation.AccelerateDecelerateInterpolator
import android.view.animation.DecelerateInterpolator
import android.widget.ProgressBar
import android.widget.TextView
import com.ad.tradpluslibrary.TPAdManager
import com.app.input.breeze.board.App
import com.app.input.breeze.board.R
import com.app.input.breeze.board.utils.AppUtils
import kotlin.math.roundToInt


/**
 * 不要修改启动页继承Activity这点
 */
class SplashActivity : Activity() {

    private lateinit var progressBar: ProgressBar
    private lateinit var loadingText: TextView
    private lateinit var logoView: View
    private var countTime = 15000L
    private lateinit var timer: CountDownTimer

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        // 全屏沉浸式设置
        setupImmersiveMode()
        
        setContentView(R.layout.splash_activity)
        
        progressBar = findViewById(R.id.nova_progress)
        loadingText = findViewById(R.id.loading_text)
        logoView = findViewById(R.id.image)
        
        init()
    }
    
    private fun setupImmersiveMode() {
        val decorView = window.decorView
        // 内容延伸到系统栏下方，但保持系统栏可见
        val flags = (View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)
        decorView.systemUiVisibility = flags
        
        // 设置状态栏透明，导航栏白色
        window.statusBarColor = android.graphics.Color.TRANSPARENT
        window.navigationBarColor = android.graphics.Color.WHITE
    }
    
    override fun onResume() {
        super.onResume()
        // 保持全屏沉浸式状态
        setupImmersiveMode()
    }
    
    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
        if (hasFocus) {
            // 保持全屏沉浸式状态
            setupImmersiveMode()
        }
    }

    private fun init() {
        // 启动动画
        startAnimations()

        TPAdManager.init(
            this,
            App.TAG,
            "491CF93F7A3E504CC90F215A3B43D011",
            "163EB8E51E42672FDBB21327BF580412",
            "ACF89F38DB6757D632C0ED73E4E3F712",
            "56A126D9C53FCAEAFCEADB9FA6070612"
        ) {

        }
        timer = TPAdManager.showWelcomeAd(this, countTime, { millisUntilFinished ->
            //倒计时更新
            val progressPercentage = (100 * millisUntilFinished) / countTime
            val percentage = 100 - progressPercentage
            progressBar.progress = percentage.toInt()

            // 更新加载文字
            updateLoadingText(percentage.toInt())
        }) {
            //跳转首页
            progressBar.progress = 100
            updateLoadingText(100)

            // 延迟一点再跳转，让用户看到完成状态
            Handler(Looper.getMainLooper()).postDelayed({
                toHome()
            }, 200)
        }
        timer.start()
    }

    private fun startAnimations() {
        // Logo 淡入和缩放动画
        logoView.alpha = 0f
        logoView.scaleX = 0.8f
        logoView.scaleY = 0.8f
        
        val logoFadeIn = ObjectAnimator.ofFloat(logoView, "alpha", 0f, 1f)
        val logoScaleX = ObjectAnimator.ofFloat(logoView, "scaleX", 0.8f, 1f)
        val logoScaleY = ObjectAnimator.ofFloat(logoView, "scaleY", 0.8f, 1f)
        
        logoFadeIn.duration = 600
        logoScaleX.duration = 600
        logoScaleY.duration = 600
        
        logoFadeIn.interpolator = DecelerateInterpolator()
        logoScaleX.interpolator = DecelerateInterpolator()
        logoScaleY.interpolator = DecelerateInterpolator()
        
        logoFadeIn.start()
        logoScaleX.start()
        logoScaleY.start()
        
        // 应用名称淡入
        val appNameView = findViewById<View>(R.id.tv)
        appNameView.alpha = 0f
        appNameView.translationY = 20f
        
        Handler(Looper.getMainLooper()).postDelayed({
            val nameFadeIn = ObjectAnimator.ofFloat(appNameView, "alpha", 0f, 1f)
            val nameTranslate = ObjectAnimator.ofFloat(appNameView, "translationY", 20f, 0f)
            
            nameFadeIn.duration = 500
            nameTranslate.duration = 500
            
            nameFadeIn.interpolator = DecelerateInterpolator()
            nameTranslate.interpolator = DecelerateInterpolator()
            
            nameFadeIn.start()
            nameTranslate.start()
        }, 300)
        
        // 进度条淡入
        progressBar.alpha = 0f
        Handler(Looper.getMainLooper()).postDelayed({
            val progressFadeIn = ObjectAnimator.ofFloat(progressBar, "alpha", 0f, 1f)
            progressFadeIn.duration = 400
            progressFadeIn.start()
            
            loadingText.alpha = 0f
            val textFadeIn = ObjectAnimator.ofFloat(loadingText, "alpha", 0f, 1f)
            textFadeIn.duration = 400
            textFadeIn.start()
        }, 600)
    }

    private fun updateLoadingText(progress: Int) {
        when {
            progress < 30 -> loadingText.text = getString(R.string.initializing)
            progress < 60 -> loadingText.text = getString(R.string.loading_themes)
            progress < 90 -> loadingText.text = getString(R.string.preparing_interface)
            else -> loadingText.text = getString(R.string.almost_done)
        }
    }

    private fun toHome() {
        // 淡出动画
        val fadeOut = ObjectAnimator.ofFloat(findViewById<View>(R.id.main), "alpha", 1f, 0f)
        fadeOut.duration = 300
        fadeOut.interpolator = AccelerateDecelerateInterpolator()
        fadeOut.addListener(object : AnimatorListenerAdapter() {
            override fun onAnimationEnd(animation: Animator) {
                startActivity(Intent(this@SplashActivity, MainActivity::class.java))
                overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out)
                finish()
            }
        })
        fadeOut.start()
    }

    override fun onDestroy() {
        super.onDestroy()
        if (::timer.isInitialized) {
            timer.cancel()
        }
    }
}