package com.easy.clean.ui.splash

import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.text.Spannable
import android.text.SpannableString
import android.text.TextPaint
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.util.Log
import android.view.View
import androidx.activity.viewModels
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.easy.clean.SpConstObject.ifAgreePrivacy
import androidx.lifecycle.lifecycleScope
import com.easy.clean.GlobalConfig.URL_PRIVACY
import com.easy.clean.MyApplication
import com.easy.clean.R
import com.easy.clean.SpConstObject
import com.easy.clean.SpConstObject.isGuided
import com.easy.clean.base.BaseActivity
import com.easy.clean.base.jumpAction
import com.easy.clean.bean.FeatureBean.Companion.BATTERY_INFO
import com.easy.clean.bean.config.AdConfigBean
import com.easy.clean.business.ads.AdsMgr
import com.easy.clean.business.ads.AdsShowCallBack
import com.easy.clean.business.helper.EventUtils
import com.easy.clean.business.helper.NewComUtils
import com.easy.clean.business.helper.NewComUtils.requestCfgCallBack
import com.easy.clean.business.helper.NewComUtils.spConfig
import com.easy.clean.business.service.StayJobService.Companion.startStayJobService
import com.easy.clean.databinding.ActivitySplashBinding
import com.easy.clean.ui.dialog.StoragePermissionDialog
import com.easy.clean.ui.guide.GuideCleanActivity
import com.easy.clean.ui.main.MainActivity
import com.easy.clean.utils.PermissionUtils.checkStorePermission
import com.easy.clean.utils.PermissionUtils.requestStoragePermission
import com.easy.clean.utils.UmpUtils
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() {
        setStatusBarColor()
        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?) {
//        initUMP()
        super.onCreate(savedInstanceState)
        handleIntentExtras()
    }

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

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

    override fun initView() {
        super.initView()
        showLoadingAd()
        setPrivacyPolicy()
        requestNotificationPermission()
        binding.progress.max = viewModel.totalTimeMs.toInt()
    }

    private fun setPrivacyPolicy() {
        val privacyPolicy = getString(R.string.privacy_policy)
        val text = "${getString(R.string.agree)} $privacyPolicy"
        val spannableString = SpannableString(text)
        val start = text.indexOf(privacyPolicy)
        val end = start + privacyPolicy.length
        val clickableSpan = object : ClickableSpan() {
            override fun onClick(widget: View) {
                startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(URL_PRIVACY)))
            }

            override fun updateDrawState(ds: TextPaint) {
                super.updateDrawState(ds)
                ds.color = getColor(R.color.colorPrimary)
                ds.bgColor = 0
            }
        }
        spannableString.setSpan(clickableSpan, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
        binding.tvAgree.text = spannableString
        binding.tvAgree.movementMethod = LinkMovementMethod.getInstance()
        binding.tvAgree.highlightColor = Color.TRANSPARENT
    }

    private fun requestNotificationPermission() {
        if (isGuided) {
            return
        }
        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()
        }
        viewModel.onTick = { p, _ ->
            binding.progress.progress = p.toInt()
        }
        viewModel.jumpNext = {
            jumpNext()
        }
    }

    override fun handleBackCallBack() {

    }

    private fun initUMP() {
        val ump = UmpUtils(this)

        if (ump.consentInformation.canRequestAds()) {
            AdsMgr.init(this)
        } else {
            ump.callback = {
                AdsMgr.init(this)
            }
            ump.requestUMP()
        }
    }

    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 = {
                AdsMgr.showOpen(this, showCallBack = object : AdsShowCallBack() {
                    override fun show() {
                        viewModel.stopCountdown()
                    }

                    override fun next() {
                        binding.root.postDelayed({ jumpNext() }, 200)
                    }

                })
            }

            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
    }

}