package com.dumpster.cleaner.ui.splash

import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.text.SpannableString
import android.text.Spanned
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.text.style.UnderlineSpan
import android.util.Log
import android.view.View
import androidx.activity.viewModels
import androidx.core.graphics.toColorInt
import androidx.core.net.toUri
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.lifecycleScope
import com.dumpster.cleaner.GlobalConfig.URL_PRIVACY
import com.dumpster.cleaner.GlobalConfig.URL_USE
import com.dumpster.cleaner.MyApplication
import com.dumpster.cleaner.SpConstObject.ifAgreePrivacy
import com.dumpster.cleaner.SpConstObject.isGuided
import com.dumpster.cleaner.base.BaseActivity
import com.dumpster.cleaner.base.jumpAction
import com.dumpster.cleaner.bean.FeatureBean.Companion.BATTERY_INFO
import com.dumpster.cleaner.bean.config.AdConfigBean
import com.dumpster.cleaner.business.ads.AdsMgr
import com.dumpster.cleaner.business.ads.AdsShowCallBack
import com.dumpster.cleaner.business.helper.EventUtils
import com.dumpster.cleaner.business.helper.NewComUtils
import com.dumpster.cleaner.business.helper.NewComUtils.requestCfgCallBack
import com.dumpster.cleaner.business.helper.NewComUtils.spConfig
import com.dumpster.cleaner.business.service.StayJobService.Companion.startStayJobService
import com.dumpster.cleaner.databinding.ActivitySplashBinding
import com.dumpster.cleaner.ui.dialog.StoragePermissionDialog
import com.dumpster.cleaner.ui.guide.GuideCleanActivity
import com.dumpster.cleaner.ui.main.MainActivity
import com.dumpster.cleaner.utils.LogEx
import com.dumpster.cleaner.utils.PermissionUtils.checkStorePermission
import com.dumpster.cleaner.utils.PermissionUtils.requestStoragePermission
import com.dumpster.cleaner.utils.UmpUtils
import com.dumpster.cleaner.utils.umpCalled
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.util.concurrent.atomic.AtomicBoolean


@SuppressLint("CustomSplashScreen")
class SplashActivity : BaseActivity<ActivitySplashBinding>(ActivitySplashBinding::inflate) {

    private val viewModel: SplashViewModel by viewModels()

    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
    }

    override fun useDefaultImmersive() {
        ViewCompat.setOnApplyWindowInsetsListener(binding.root) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, 0, systemBars.right, systemBars.bottom)
            insets
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        handleIntentExtras()
    }

    override fun onResumeOneShoot() {
        super.onResumeOneShoot()
        viewModel.startCountdown()
    }

    override fun onStop() {
        super.onStop()
        viewModel.stopCountdown()
    }

    override fun initView() {
        super.initView()
        requestNotificationPermission()
        showLoadingAd()
        setPrivacyPolicy()
    }

    private fun setPrivacyPolicy() {

        val spannableString = SpannableString("privacy")
        spannableString.setSpan(UnderlineSpan(), 0, spannableString.length, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
        spannableString.setSpan(object : ClickableSpan() {
            override fun onClick(widget: View) {
                startActivity(Intent(Intent.ACTION_VIEW, URL_PRIVACY.toUri()))
            }
        }, 0, spannableString.length, Spanned.SPAN_INCLUSIVE_INCLUSIVE)

        binding.tvPrivacy.text = spannableString
        binding.tvPrivacy.movementMethod = LinkMovementMethod.getInstance()
        binding.tvPrivacy.setLinkTextColor("#328EF6".toColorInt())

        val spannableString2 = SpannableString("terms of service")
        spannableString2.setSpan(UnderlineSpan(), 0, spannableString2.length, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
        spannableString2.setSpan(object : ClickableSpan() {
            override fun onClick(widget: View) {
                startActivity(Intent(Intent.ACTION_VIEW, URL_USE.toUri()))
            }
        }, 0, spannableString2.length, Spanned.SPAN_INCLUSIVE_INCLUSIVE)

        binding.tvTerms.text = spannableString2
        binding.tvTerms.movementMethod = LinkMovementMethod.getInstance()
        binding.tvTerms.setLinkTextColor("#328EF6".toColorInt())

    }

    private fun requestNotificationPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            val array = arrayOf(Manifest.permission.POST_NOTIFICATIONS)
            launcher.launch(array) { permissions ->
                val flag = permissions.values.all { it }
                if (flag) MyApplication.appContext.startStayJobService()
            }
        }
    }

    override fun initListener() {
        super.initListener()
        binding.tvStart.setOnClickListener {
            ifAgreePrivacy = true
            showLoadingAd()
            EventUtils.event("app_start")
            EventUtils.event("page_${javaClass.simpleName}")
            viewModel.startCountdown()
            MyApplication.appContext.initApp()
        }
    }

    override fun handleBackCallBack() {

    }

    private fun initUMP(callBack: () -> Unit) {

        if (AdConfigBean.adsConfigBean.requestUmp && !umpCalled) {
            umpCalled = true

            val ump = UmpUtils(this)
            if (ump.consentInformation.canRequestAds()) {
                callBack.invoke()
            } else {
                ump.callback = {
                    callBack.invoke()
                }
                LogEx.logDebug(TAG, "requestUMP")
                ump.requestUMP()
            }

        } else {
            callBack.invoke()
        }


    }


    private fun showLoadingAd() {
        binding.clBottomStart.visibility = if (ifAgreePrivacy) View.GONE else View.VISIBLE
        binding.clBottomLoading.visibility = if (ifAgreePrivacy) View.VISIBLE else View.GONE
        binding.llConsent.visibility = if (ifAgreePrivacy) View.GONE else View.VISIBLE

        if (ifAgreePrivacy) {

            val acAction = {
                initUMP {
                    LogEx.logDebug(TAG, "initUMP callback")

                    AdsMgr.showOpen(this, showCallBack = object : AdsShowCallBack() {
                        override fun show() {
                            super.show()
                            viewModel.stopCountdown()
                        }

                        override fun next() {
                            val action = {
                                LogEx.logDebug(TAG, "next")
                                viewModel.overCountDown()
//                                binding.progressBar.setProgress(100.0)
                                binding.root.postDelayed({ jumpNext() }, 250)
                            }
                            LogEx.logDebug("AdmobEvent", "inter adShowed=${adShowed}")
                            if (adShowed) {
                                action.invoke()
                            } else {
                                LogEx.logDebug("AdmobEvent", "inter open show inter")
                                AdsMgr.showInsert(this@SplashActivity, showCallBack = object : AdsShowCallBack() {
                                    override fun next() {
                                        action.invoke()
                                    }
                                })
                            }

                        }

                    })
                }
            }


            if (spConfig.isNotEmpty()) {
                Log.e(TAG, "1")
                acAction.invoke()
            } else {
                if (NewComUtils.requestCfgIng.get()) {
                    requestCfgCallBack = {
                        lifecycleScope.launch(Dispatchers.Main) {
                            Log.e(TAG, "2")
                            acAction.invoke()
                        }
                    }
                } else {
                    Log.e(TAG, "3")
                    acAction.invoke()
                }
            }
        }
    }

    val jumped = AtomicBoolean(false)
    fun jumpNext() {
        if (jumped.get()) return
        jumped.set(true)

        when {
            !isGuided -> {
                isGuided = true
                goToAc(GuideCleanActivity::class.java)
                finish()
            }

            isHotLaunch -> {
                goToAc(MainActivity::class.java)
                finish()
            }

            actionId.isNotEmpty() -> {
                actionIdJump()
            }

            else -> {
                goToAc(MainActivity::class.java)
                finish()
            }
        }
        intent.extras?.clear()
    }

    fun actionIdJump() {
        when (actionId) {
            BATTERY_INFO -> {
                jumpAction(actionId)
                finish()
            }

            else -> {
                if (checkStorePermission()) {
                    jumpAction(actionId)
                    finish()
                } else {
                    val dialog = StoragePermissionDialog(this)
                    dialog.action = {
                        requestStoragePermission(launcher) {
                            if (it) {
                                jumpAction(actionId)
                                finish()
                            } else {
                                goToAc(MainActivity::class.java)
                                finish()
                            }
                        }
                    }
                    dialog.showDialog()
                }
            }

        }
    }


    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        handleIntentExtras()
    }

    var isHotLaunch: Boolean = false
    var actionId = ""
    fun handleIntentExtras() {
        super.onNewIntent(intent)
        actionId = intent?.extras?.getString("actionId") ?: ""
        isHotLaunch = intent?.extras?.getBoolean("isHotLaunch") == true
    }

}