package com.base.datarecovery.activity.splash

import android.Manifest
import android.animation.ValueAnimator
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.os.Build
import android.os.CountDownTimer
import android.text.SpannableString
import android.text.Spanned
import android.text.style.UnderlineSpan
import android.view.animation.LinearInterpolator
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.view.isVisible
import com.base.datarecovery.GlobalConfig
import com.base.datarecovery.MyApplication
import com.base.datarecovery.activity.MainActivity
import com.base.datarecovery.activity.battery.BatteryInfoAnimationActivity
import com.base.datarecovery.activity.guide.FirstSelectActivity
import com.base.datarecovery.activity.junkclean.ScanJunkActivity
import com.base.datarecovery.activity.newfunction.WeatherInterface
import com.base.datarecovery.activity.photomanager.PhotoManagerAnimationActivity
import com.base.datarecovery.activity.recovery.FileScanResultActivity
import com.base.datarecovery.activity.videomanager.VideoCleanAnimationActivity
import com.base.datarecovery.ads.admob.AdmobManager
import com.base.datarecovery.bean.ConstObject
import com.base.datarecovery.bean.ConstObject.ifAgreePrivacy
import com.base.datarecovery.databinding.ActivitySplashBinding
import com.base.datarecovery.help.BaseActivity
import com.base.datarecovery.utils.BarUtils
import com.base.datarecovery.utils.EventUtils
import com.base.datarecovery.utils.UMPUtils.initUMP


class Splash2Activity : BaseActivity<ActivitySplashBinding>() {
    override val binding: ActivitySplashBinding by lazy {
        ActivitySplashBinding.inflate(layoutInflater)
    }
    private var notificationId = 0
    private var isLoadAdComplete = false

    private var progressAnimator: ValueAnimator? = null


    override fun initView() {
        BarUtils.setStatusBarLightMode(this, true)
        BarUtils.setStatusBarColor(this, Color.TRANSPARENT)
        // binding.idTopImg.updatePadding(top = BarUtils.getStatusBarHeight())
        notificationId = intent.getIntExtra("actionId", 0)
        val spannableString = SpannableString("Privacy Policy")
        spannableString.setSpan(
            UnderlineSpan(),
            0,
            spannableString.length,
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        binding.idTvPrivacyPolicy.text = spannableString
        binding.tvStart.setOnClickListener {
            binding.tvStart.isEnabled = false
            ifAgreePrivacy = true
            showLoading()
            EventUtils.event("app_start")
            MyApplication.initApp()
        }
        notificationId = intent.getIntExtra("actionId", 0)
        initUMP()
        showLoading()
        binding.idTvPrivacyPolicy.setOnClickListener {
            val intent = Intent(
                Intent.ACTION_VIEW,
                Uri.parse(GlobalConfig.URL_PRIVACY)
            )
            startActivity(intent)
        }
        // jumpMain()
        if (Build.VERSION.SDK_INT >= 33) {
            registerForActivityResult(ActivityResultContracts.RequestPermission()) {}.launch(
                Manifest.permission.POST_NOTIFICATIONS
            )
        }

    }

    private fun showLoading() {
        binding.idLlStart.isVisible = !ifAgreePrivacy
        binding.llTips.isVisible = !ifAgreePrivacy
        binding.idLlJindu.isVisible = ifAgreePrivacy
        if (ifAgreePrivacy) {
            initAd()
            showProgress()
        }
    }

    private fun initAd() {
        AdmobManager.init(
            this,
            {
                if (isFinishing || isDestroyed) return@init
                isLoadAdComplete = true
                showProgress(binding.pb.progress, 10)
                when (it) {
                    0 -> {
                        countdownTimer.start()
                    }

                    1 -> {
                        AdmobManager.showInterstitialAd(
                            this,
                            dismissed = { delayedToHome() },
                            failed = { delayedToHome() }
                        )
                    }

                    else -> {
                        toHome()
                    }
                }
            }, {
                delayedToHome()
            }
        )
    }

    private val countdownTimer = object : CountDownTimer(3000, 1000) {
        override fun onTick(millisUntilFinished: Long) {
            val seconds = (millisUntilFinished / 1000).toInt()
            binding.tvAdDes.text = "This process may contain ads (${seconds})"
        }

        override fun onFinish() {
            AdmobManager.showAppOpenAd(
                this@Splash2Activity,
                dismissed = { delayedToHome() },
                failed = { delayedToHome() }
            )
        }
    }

    private fun showProgress(start: Int = 1, timeout: Long = 15000) {
        progressAnimator?.cancel()
        progressAnimator = ValueAnimator.ofInt(start, 100).apply {
            duration = timeout
            interpolator = LinearInterpolator()
            addUpdateListener { animation ->
                val value = animation.animatedValue as Int
                binding.pb.progress = value
                if (value == 100 && !isLoadAdComplete) {
                    toHome()
                }
            }
        }
        progressAnimator?.start()
    }

    private fun delayedToHome() {
        binding.tvStart.postDelayed({ toHome() }, 300)
    }

    private fun toHome() {
        if (isFinishing || isDestroyed) return
        when (notificationId) {
            ConstObject.ID_JUNK_CLEAN_PUSH -> {
                startActivity(Intent(this, ScanJunkActivity::class.java))
            }

            ConstObject.ID_SIMILAR_IMAGE -> {
                startActivity(Intent(this, PhotoManagerAnimationActivity::class.java))
            }

            ConstObject.ID_SCREENSHOT_CLEAN -> {
                startActivity(Intent(this, PhotoManagerAnimationActivity::class.java))
            }

            ConstObject.ID_RECOVERY_PHOTOS -> {
                startActivity(
                    Intent(this, FileScanResultActivity::class.java)
                        .putExtra("ScanType", ConstObject.SCAN_PHOTOS)
                )
            }

            ConstObject.ID_RECOVERY_VIDEOS -> {
                startActivity(
                    Intent(this, FileScanResultActivity::class.java)
                        .putExtra("ScanType", ConstObject.SCAN_VIDEOS)
                )
            }

            ConstObject.ID_RECOVERY_DOCUMENTS -> {
                startActivity(
                    Intent(this, FileScanResultActivity::class.java)
                        .putExtra("ScanType", ConstObject.SCAN_DOCUMENTS)
                )
            }

            ConstObject.ID_APP_MANAGER -> {
                startActivity(Intent(this, VideoCleanAnimationActivity::class.java))
            }

            ConstObject.ID_BATTERY_INFO -> {
                startActivity(Intent(this, BatteryInfoAnimationActivity::class.java))
            }

            ConstObject.ID_WEATHER -> {
                startActivity(Intent(this, WeatherInterface::class.java))
            }


            else -> {
                val isHotLaunch = intent?.extras?.getBoolean("isHotLaunch", false) ?: false
                if (!isHotLaunch) {
                    if (!ConstObject.isGuide) {
                        startActivity(Intent(this, FirstSelectActivity::class.java))
                    } else {
                        startActivity(Intent(this, MainActivity::class.java))
                    }
                }
            }
        }
        finish()
    }
}