package astonishic.chandelieric

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 tooic.fatalityic.Runawayic.ifAgreePrivacy
import androidx.lifecycle.lifecycleScope
import tooic.fatalityic.GlobalConfig.URL_PRIVACY
import tooic.fatalityic.Adventurousic
import com.easy.clean.R
import tooic.fatalityic.Runawayic
import tooic.fatalityic.Runawayic.isGuided
import tooic.fatalityic.jittersic.Reinstateic
import tooic.fatalityic.jittersic.jumpAction
import tooic.fatalityic.corroborateic.Protegeic.Companion.BATTERY_INFO
import tooic.fatalityic.corroborateic.indexic.Lurkic
import autonomyic.polemicalic.congestionic.Unwindic
import autonomyic.polemicalic.congestionic.NASAic
import incredibleic.guffawic.Glowwormic
import incredibleic.guffawic.Equalizeic
import incredibleic.guffawic.Equalizeic.requestCfgCallBack
import incredibleic.guffawic.Equalizeic.spConfig
import cottonwoodic.proprietoric.gutic.Wasic.Companion.startStayJobService
import com.easy.clean.databinding.BroodicBinding
import rememberic.Categoricallyic
import foamyic.Friskic
import waific.Teflonic.therapistic.Hauntingic
import tooic.fatalityic.redic.speckledic.hankeringic.Oustic.checkStorePermission
import tooic.fatalityic.redic.speckledic.hankeringic.Oustic.requestStoragePermission
import tooic.fatalityic.redic.speckledic.hankeringic.Moatic
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.util.concurrent.atomic.AtomicBoolean

@SuppressLint("CustomSplashScreen")
class Jostleic : Reinstateic<BroodicBinding>(BroodicBinding::inflate) {

    private val viewModel: Headhunteric 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.utilityic.max = viewModel.totalTimeMs.toInt()
    }

    private fun setPrivacyPolicy() {
        val privacyPolicy = getString(R.string.arcadeic)
        val text = "${getString(R.string.acquaintedic)} $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.robic)
                ds.bgColor = 0
            }
        }
        spannableString.setSpan(clickableSpan, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
        binding.emancipationic.text = spannableString
        binding.emancipationic.movementMethod = LinkMovementMethod.getInstance()
        binding.emancipationic.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) Adventurousic.appContext.startStayJobService()
            }
        }
    }

    override fun initListener() {
        super.initListener()
        binding.handsomeic.setOnClickListener {
            ifAgreePrivacy = true
            showLoadingAd()
            Glowwormic.event("app_start")
            Glowwormic.event("page_${javaClass.simpleName}")
            viewModel.startCountdown()
            Adventurousic.appContext.initApp()
        }
        viewModel.onTick = { p, _ ->
            binding.utilityic.progress = p.toInt()
        }
        viewModel.jumpNext = {
            jumpNext()
        }
    }

    override fun handleBackCallBack() {

    }

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

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

    private fun showLoadingAd() {
        binding.fornicationic.visibility = if (ifAgreePrivacy) View.GONE else View.VISIBLE
        binding.vehicularic.visibility = if (ifAgreePrivacy) View.VISIBLE else View.GONE
        binding.interposeic.visibility = if (ifAgreePrivacy) View.GONE else View.VISIBLE

        if (ifAgreePrivacy) {

            val acAction = {
                Unwindic.showOpen(this, showCallBack = object : NASAic() {
                    override fun show() {
                        viewModel.stopCountdown()
                    }

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

                })
            }

            if (spConfig.isNotEmpty()) {
                Log.e(TAG, "1")
                acAction.invoke()
            } else {
                if (Equalizeic.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(Friskic::class.java)
                finish()
            }

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

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

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

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

            else -> {
                if (checkStorePermission()) {
                    jumpAction(actionId)
                    finish()
                } else {
                    val dialog = Categoricallyic(this)
                    dialog.action = {
                        requestStoragePermission(launcher) {
                            if (it) {
                                jumpAction(actionId)
                                finish()
                            } else {
                                goToAc(Hauntingic::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
    }

}