package com.base.scanqr.ui.main

import android.content.Intent
import android.graphics.Color
import android.view.LayoutInflater
import android.widget.TextView
import androidx.activity.addCallback
import androidx.navigation.NavController
import androidx.navigation.fragment.NavHostFragment
import com.base.scanqr.R
import com.base.scanqr.ads.AdsMgr
import com.base.scanqr.base.BaseActivity
import com.base.scanqr.bean.ConstObject.mainStartTimes
import com.base.scanqr.bean.HomeTabUIBean
import com.base.scanqr.bean.NotificationSendBean.Companion.ACTION_ID_SCAN
import com.base.scanqr.databinding.ActivityMainBinding
import com.base.scanqr.databinding.ItemHomeTabBinding
import com.base.scanqr.qr.CameraUtils
import com.base.scanqr.ui.widget.AppExitDialog.showAppExitDialog
import com.base.scanqr.ui.widget.NotificationDialog.showNotificationTurnOn
import com.base.scanqr.utils.LogEx
import com.base.scanqr.utils.PermissionUtils.areNotificationsEnabled
import com.base.scanqr.utils.PermissionUtils.checkCameraPermission
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayout.OnTabSelectedListener
import com.gyf.immersionbar.ktx.immersionBar
import java.util.concurrent.atomic.AtomicBoolean

class MainActivity : BaseActivity<ActivityMainBinding>(ActivityMainBinding::inflate) {


    private var navController: NavController? = null
    var cameraUtils: CameraUtils? = null

    private val homeTabs by lazy {
        arrayOf(
            HomeTabUIBean(R.drawable.bg_selector_create, getString(R.string.create)),
            HomeTabUIBean(R.drawable.bg_selector_scan, getString(R.string.scan)),
            HomeTabUIBean(R.drawable.bg_selector_history, getString(R.string.history)),
            HomeTabUIBean(R.drawable.bg_selector_settings, getString(R.string.settings)),
        )
    }

    private var bannerShowed = AtomicBoolean(false)
    override fun onResumeOneShoot() {
        super.onResumeOneShoot()
        val flag = changeLanguage()
        if (flag) return

        mainStartTimes++
    }

    override fun onResume() {
        super.onResume()
        if (checkCameraPermission()) {
            if (!bannerShowed.get()) {
                bannerShowed.set(true)
                AdsMgr.showBanner(binding.flBanner, true) {
                    showNotificationDialog()
                }
            } else {
                showNotificationDialog()
            }
        }
    }

    private fun showNotificationDialog() {
        if (mainStartTimes > 2 && checkCameraPermission()) {
            if (!areNotificationsEnabled()) {
                showNotificationTurnOn(launcher)
            }
        }
    }

    override fun initView() {
        super.initView()
        navController = (supportFragmentManager.findFragmentById(R.id.fragment_container) as NavHostFragment).navController
        cameraUtils = CameraUtils(this)
        initTab()
    }

    override fun initListener() {
        super.initListener()
        onBackPressedDispatcher.addCallback {
            showAppExitDialog()
        }
        handleActionIdJump()
    }

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

    private fun handleActionIdJump() {
        val actionId = intent.extras?.getString("actionId")
        LogEx.logDebug(TAG, "actionId=$actionId")
        when (actionId) {
            ACTION_ID_SCAN -> {
                val defaultTab = binding.tabLayout.getTabAt(1)
                defaultTab?.select()
                defaultTab?.setSelected()
            }
        }
    }

    private fun initTab() {
        homeTabs.forEachIndexed { index, homeTab ->
            val tab = binding.tabLayout.newTab()
            val view = LayoutInflater.from(this).inflate(R.layout.item_home_tab, null)
            val tabBinding = ItemHomeTabBinding.bind(view)
            tabBinding.ivIcon.setImageResource(homeTab.icon)
            tabBinding.tvTab.text = homeTab.tab
//            tabBinding.tvTab.setTextColor(ContextCompat.getColor(this, R.color.color_tab_home))
            tab.customView = tabBinding.root
            tab.id = index
            binding.tabLayout.addTab(tab)
        }
        binding.tabLayout.addOnTabSelectedListener(object : OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab?) {
                tab?.setSelected()
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {
                tab?.setUnselected()
            }

            override fun onTabReselected(tab: TabLayout.Tab?) {

            }
        })

        val defaultTab = binding.tabLayout.getTabAt(tabAt)
        defaultTab?.select()
        defaultTab?.setSelected()
    }

    private fun naviFragment(id: Int) {
        when (id) {
            0 -> {
                tabAt = 0
                navController?.navigate(R.id.createFragment)
            }

            1 -> {
                tabAt = 1
                navController?.navigate(R.id.scanFragment)
            }

            2 -> {
                tabAt = 2
                navController?.navigate(R.id.historyFragment)
            }

            3 -> {
                tabAt = 3
                navController?.navigate(R.id.settingsFragment)
            }
        }
    }

    fun TabLayout.Tab.setUnselected() {
        val textView = customView?.findViewById<TextView>(R.id.tv_tab)
        LogEx.logDebug(TAG, "setUnselected ${textView?.text}")
        textView?.setTextColor(Color.parseColor("#696969"))
    }

    fun TabLayout.Tab.setSelected() {
        val textView = customView?.findViewById<TextView>(R.id.tv_tab)
        LogEx.logDebug(TAG, "setSelected ${textView?.text}")
        textView?.setTextColor(Color.parseColor("#6473F8"))
        naviFragment(this.id)
    }

    override fun onDestroy() {
        super.onDestroy()
        cameraUtils?.unBind()
    }

    override fun configSystemBar() {
        immersionBar {
            statusBarColor("#FFFFFFFF")
            statusBarDarkFont(true)
        }
    }

    companion object {
        var tabAt = 1
    }
}