package com.ritoq.quickphone.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.view.View
import androidx.activity.viewModels
import androidx.core.graphics.toColorInt
import androidx.core.net.toUri
import com.ritoq.quickphone.GlobalConfig.URL_PRIVACY
import com.ritoq.quickphone.MyApplication
import com.ritoq.quickphone.R
import com.ritoq.quickphone.SpConstObject.ifAgreePrivacy
import com.ritoq.quickphone.SpConstObject.isGuided
import com.ritoq.quickphone.base.BaseActivity
import com.ritoq.quickphone.base.jumpAction
import com.ritoq.quickphone.bean.FeatureBean.Companion.BATTERY_INFO
import com.ritoq.quickphone.business.helper.EventUtils
import com.ritoq.quickphone.business.service.StayJobService.Companion.startStayJobService
import com.ritoq.quickphone.databinding.ActivitySplashBinding
import com.ritoq.quickphone.ui.dialog.StoragePermissionDialog
import com.ritoq.quickphone.ui.guide.GuideExperienceActivity
import com.ritoq.quickphone.ui.main.MainActivity
import com.ritoq.quickphone.utils.PermissionUtils.checkStorePermission
import com.ritoq.quickphone.utils.PermissionUtils.requestStoragePermission
import java.util.concurrent.atomic.AtomicBoolean


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

    private val viewModel: SplashViewModel by viewModels()

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

    override fun initView() {
        super.initView()
        requestNotificationPermission()
        setPrivacyPolicy()
        showLoadingAd()
        viewModel.onTick = { a, b, c ->
            binding.progressBar.progress = c.toInt()
        }
        viewModel.jumpNext = {
            jumpNext()
        }
    }

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


    private fun setPrivacyPolicy() {

        val spannableString = SpannableString(getString(R.string.privacy_policy))
        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("#999999".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("#2DD29E".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}")
            MyApplication.appContext.initApp()
        }
    }

    override fun handleBackCallBack() {

    }

    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

        viewModel.startCountdown()
    }

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

        when {
            !isGuided -> {
                isGuided = true
                goToAc(GuideExperienceActivity::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 -> {

                val actionStorage = {
                    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()
                    }
                }

                actionStorage.invoke()

            }

        }
    }

    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
    }

}