package com.base.scanqrclear.ui.start

import android.Manifest
import android.content.Intent
import android.os.Build
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.base.scanqrclear.ads.AdsMgr
import com.base.scanqrclear.ads.AdsShowCallBack
import com.base.scanqrclear.base.BaseActivity
import com.base.scanqrclear.bean.ConstObject
import com.base.scanqrclear.bean.ConstObject.isFirstLauncher
import com.base.scanqrclear.bean.NotificationSendBean.Companion.ACTION_ID_APP_PROCESS
import com.base.scanqrclear.bean.NotificationSendBean.Companion.ACTION_ID_CLEAN_JUNK
import com.base.scanqrclear.bean.NotificationSendBean.Companion.ACTION_ID_CONSTELLATION
import com.base.scanqrclear.bean.NotificationSendBean.Companion.ACTION_ID_EMAIL
import com.base.scanqrclear.bean.NotificationSendBean.Companion.ACTION_ID_SCAN
import com.base.scanqrclear.bean.NotificationSendBean.Companion.ACTION_ID_SCREEN_SHORT
import com.base.scanqrclear.bean.NotificationSendBean.Companion.ACTION_ID_SIMILAR
import com.base.scanqrclear.bean.NotificationSendBean.Companion.ACTION_ID_STAY_SCAN
import com.base.scanqrclear.bean.NotificationSendBean.Companion.ACTION_ID_TEXT
import com.base.scanqrclear.bean.NotificationSendBean.Companion.ACTION_ID_WEATHER
import com.base.scanqrclear.bean.NotificationSendBean.Companion.ACTION_ID_WEBSITE
import com.base.scanqrclear.bean.NotificationSendBean.Companion.ACTION_ID_WHATSAPP
import com.base.scanqrclear.bean.NotificationSendBean.Companion.ACTION_ID_WIFI
import com.base.scanqrclear.databinding.ActivityStartBinding
import com.base.scanqrclear.fcm.notification.NotificationHoverUtils
import com.base.scanqrclear.luma.AppProcessActivity
import com.base.scanqrclear.luma.CleanJunkActivity
import com.base.scanqrclear.luma.ScreenshotCleanActivity
import com.base.scanqrclear.luma.SimilarPhotosActivity
import com.base.scanqrclear.luma.WeatherInterface
import com.base.scanqrclear.luma.WhatsappCleanActivity
import com.base.scanqrclear.service.StayJobService.Companion.startJob
import com.base.scanqrclear.ui.email.EmailActivity
import com.base.scanqrclear.ui.language.LanguageActivity
import com.base.scanqrclear.ui.main.MainActivity
import com.base.scanqrclear.ui.main.ScanAc
import com.base.scanqrclear.ui.text.TextActivity
import com.base.scanqrclear.ui.website.WebsiteActivity
import com.base.scanqrclear.ui.webview.WebBrowserActivity
import com.base.scanqrclear.ui.wifi.WifiActivity
import com.base.scanqrclear.utils.LogEx
import com.base.scanqrclear.utils.PermissionUtils.checkStorePermission
import com.gyf.immersionbar.ktx.immersionBar
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import java.util.concurrent.atomic.AtomicBoolean

class StartActivity : BaseActivity<ActivityStartBinding>(ActivityStartBinding::inflate) {

    private val viewModel by lazy(LazyThreadSafetyMode.NONE) {
        ViewModelProvider(this)[StartViewModel::class.java]
    }

    override fun initView() {
        super.initView()
//
//        startActivity(Intent(this, ContractActivity::class.java))
//        finish()
//        return

        NotificationHoverUtils.stopNotificationHandler()

        if (ConstObject.ifAgreePrivacy) {
            agreePrivacy()
        }

        startJob()

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            launcher.launch(arrayOf(Manifest.permission.POST_NOTIFICATIONS)) {
                LogEx.logDebug(TAG, "POST_NOTIFICATIONS")
            }
        }
    }


    private fun agreePrivacy() {

        AdsMgr.showOpen(this, true, object : AdsShowCallBack() {
            override fun show() {
                super.show()
                viewModel.cancelJumpJob()
                cancelProgressJob()
            }

            override fun close(where: Int) {
                jumpNext()
            }

            override fun failed(where: Int) {
                jumpNext()
            }

            override fun googleFailed(where: Int) {
                jumpNext()
            }
        })
        viewModel.startJumpJob = true
        viewModel.startJumpJob(lifecycleScope, ::jumpNext)

        startProgressJob = true
        startProgressJob()
    }

    private var startProgressJob: Boolean = false
    private var progressJob: Job? = null

    private fun startProgressJob() {
        if (ConstObject.ifAgreePrivacy && startProgressJob) {
            if (progressJob == null) {
                progressJob = lifecycleScope.launch(Dispatchers.Main) {
                    while (isActive) {
                        binding.progressBar.progress += 1
                        delay(200)
                    }
                }
            }
        }
    }

    private fun cancelProgressJob() {
        progressJob?.cancel()
        progressJob = null
    }

    private var jump: AtomicBoolean = AtomicBoolean(false)
    private fun jumpNext() {
        if (jump.get()) {
            return
        }
        jump.set(true)
        binding.progressBar.progress = 100

        binding.root.postDelayed({
            if (isFirstLauncher) {
                isFirstLauncher = false
                firstLauncherJump()
            } else {
                handleActionIdJump()
            }
        }, 100)
    }

    private fun handleActionIdJump() {
        val actionId = intent.extras?.getString("actionId")
        val isHotLaunch = intent.extras?.getBoolean("isHotLaunch", false) ?: false
        LogEx.logDebug(TAG, "actionId=$actionId isHotLaunch=$isHotLaunch")
        if (isHotLaunch) {
            finish()
            return
        }
        when (actionId) {
            ACTION_ID_STAY_SCAN, ACTION_ID_SCAN -> {
                LogEx.logDebug(TAG, "actionId MainActivity")
//                startActivity(Intent(this, MainActivity::class.java).apply {
//                    putExtra("actionId", actionId)
//                    addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)
//                })

                startActivity(Intent(this, ScanAc::class.java))
            }

            ACTION_ID_WIFI -> {
                startActivity(Intent(this, WifiActivity::class.java).apply {
//                    putExtra("actionId", actionId)
//                    addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)
                })
            }

            ACTION_ID_TEXT -> {
                startActivity(Intent(this, TextActivity::class.java).apply {
//                    putExtra("actionId", actionId)
//                    addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)
                })
            }

            ACTION_ID_EMAIL -> {
                startActivity(Intent(this, EmailActivity::class.java).apply {
//                    putExtra("actionId", actionId)
//                    addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)
                })
            }

            ACTION_ID_WEBSITE -> {
                startActivity(Intent(this, WebsiteActivity::class.java).apply {
//                    putExtra("actionId", actionId)
//                    addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)
                })
            }

            ACTION_ID_CLEAN_JUNK -> {

                if (checkStorePermission()) {
                    startActivity(Intent(this, CleanJunkActivity::class.java))
                } else {
                    startActivity(Intent(this, MainActivity::class.java).apply {
                        putExtra("actionId", actionId)
                        putExtra("permission", true)
                        addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)
                    })
                }
            }

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

            ACTION_ID_APP_PROCESS -> {
                startActivity(Intent(this, AppProcessActivity::class.java))
            }

            ACTION_ID_WHATSAPP -> {
                if (checkStorePermission()) {
                    startActivity(Intent(this, WhatsappCleanActivity::class.java))
                } else {
                    startActivity(Intent(this, MainActivity::class.java).apply {
                        putExtra("actionId", actionId)
                        putExtra("permission", true)
                        addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)
                    })
                }
            }

            ACTION_ID_SCREEN_SHORT -> {
                if (checkStorePermission()) {
                    startActivity(Intent(this, ScreenshotCleanActivity::class.java))
                } else {
                    startActivity(Intent(this, MainActivity::class.java).apply {
                        putExtra("actionId", actionId)
                        putExtra("permission", true)
                        addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)
                    })
                }
            }

            ACTION_ID_SIMILAR -> {
                if (checkStorePermission()) {
                    startActivity(Intent(this, SimilarPhotosActivity::class.java))
                } else {
                    startActivity(Intent(this, MainActivity::class.java).apply {
                        putExtra("actionId", actionId)
                        putExtra("permission", true)
                        addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)
                    })
                }
            }

            ACTION_ID_CONSTELLATION -> {
                startActivity(Intent(this, WebBrowserActivity::class.java).apply {
                    putExtra("url", "https://www.horoscope.com/us/index.aspx")
                })
            }

            else -> {
                startActivity(Intent(this, MainActivity::class.java).apply {
                    putExtra("actionId", actionId)
                    addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)
                })
            }
        }
        finish()
        intent.extras?.clear()
    }

    private fun firstLauncherJump() {
        startActivity(Intent(this, LanguageActivity::class.java).apply {
            putExtra("isGuide", true)
        })
        finish()
    }

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

    override fun configSystemBar() {
        immersionBar {
            statusBarColor("#00FFFFFF")
            statusBarDarkFont(false)
        }
    }

    override fun onResume() {
        super.onResume()
        viewModel.startJumpJob(lifecycleScope, ::jumpNext)
        startProgressJob()
    }

    override fun onPause() {
        super.onPause()
        viewModel.cancelJumpJob()
        cancelProgressJob()
    }

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