package com.base.scanqrclear.ui.main

import android.content.Intent
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.activity.addCallback
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.base.scanqrclear.R
import com.base.scanqrclear.ads.AdsMgr
import com.base.scanqrclear.ads.AdsShowCallBack
import com.base.scanqrclear.base.BaseActivity
import com.base.scanqrclear.bean.ConstObject.mainStartTimes
import com.base.scanqrclear.bean.HomeTabUIBean
import com.base.scanqrclear.bean.NotificationSendBean.Companion.ACTION_ID_CLEAN_JUNK
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_WHATSAPP
import com.base.scanqrclear.bean.config.AdConfigBean
import com.base.scanqrclear.databinding.ActivityMainBinding
import com.base.scanqrclear.databinding.ItemHomeTabBinding
import com.base.scanqrclear.luma.ActivityJumpHelps
import com.base.scanqrclear.luma.HomeFragment
import com.base.scanqrclear.ui.widget.AppExitDialog.showAppExitDialog
import com.base.scanqrclear.ui.widget.NotificationDialog.showNotificationTurnOn
import com.base.scanqrclear.utils.AppPreferences
import com.base.scanqrclear.utils.LogEx
import com.base.scanqrclear.utils.PermissionUtils.areNotificationsEnabled
import com.base.scanqrclear.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 val homeTabs by lazy {
        arrayOf(
            HomeTabUIBean(R.drawable.bg_selector_create, getString(R.string.create)),
            HomeTabUIBean(R.drawable.bg_selector_clean, getString(R.string.files)),
            // 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 val createFragment by lazy(LazyThreadSafetyMode.NONE) {
        CreateFragment()
    }

    private val historyFragment by lazy(LazyThreadSafetyMode.NONE) {
        HistoryFragment()
    }

    private val settingFragment by lazy(LazyThreadSafetyMode.NONE) {
        SettingsFragment()
    }

    private val homeFragment by lazy(LazyThreadSafetyMode.NONE) {
        HomeFragment()
    }

    private val fragments = arrayOf(createFragment, homeFragment, historyFragment, settingFragment)
    private var pageAdapter: FragmentStateAdapter? = null


    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)
            val isGuideScan = AppPreferences.getInstance().getBoolean("isGuideScan", false)
            AdsMgr.showBanner(binding.flBanner, isGuideScan) {
                showNotificationDialog()
            }
        } else {
            showNotificationDialog()
        }
//        }
    }

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

    override fun initView() {
        super.initView()

        initViewPager2()
        initTab()
    }

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

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        LogEx.logDebug(TAG, "onNewIntent")
        //setIntent需要调用
        setIntent(intent)
        handleActionIdJump()
    }

    private fun handleActionIdJump() {
        val actionId = intent.extras?.getString("actionId")
        LogEx.logDebug(TAG, "actionId=$actionId")
        val permission = intent.extras?.getBoolean("permission", false) ?: false

        when (actionId) {
            ACTION_ID_STAY_SCAN, ACTION_ID_SCAN -> {
//                val defaultTab = binding.tabLayout.getTabAt(0)
//                defaultTab?.select()
//                defaultTab?.setSelected()
            }
            else -> {
                if (permission) {
                    var nameId = 0
                    if (actionId == ACTION_ID_CLEAN_JUNK) {
                        nameId = R.string.junk_scan
                    }
                    if (actionId == ACTION_ID_WHATSAPP) {
                        nameId = R.string.whatsapp_clean
                    }
                    if (actionId == ACTION_ID_SCREEN_SHORT) {
                        nameId = R.string.screenshot_clean
                    }
                    if (actionId == ACTION_ID_SIMILAR) {
                        nameId = R.string.similar_photos
                    }
                    ActivityJumpHelps.start(this, launcher, nameId)
                }
            }
        }
        intent.extras?.clear()
    }

    private fun initViewPager2() {
        pageAdapter = object : FragmentStateAdapter(this) {
            override fun getItemCount(): Int {
                return fragments.size
            }

            override fun createFragment(position: Int): Fragment {
                return fragments[position]
            }

        }
        binding.viewPager2.run {
            isUserInputEnabled = false
            //https://www.jianshu.com/p/f69bd30cf5b0
            //FragmentStateAdapter 这里必须传人fragment
            adapter = pageAdapter
            offscreenPageLimit = 4
        }
        binding.viewPager2.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {

            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels)
            }

            override fun onPageSelected(position: Int) {

            }
        })
    }

    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
            if (index == 1) {
                tabBinding.vDian.visibility = View.VISIBLE
            } else {
                tabBinding.vDian.visibility = View.GONE
            }
            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(0)
        defaultTab?.select()
        defaultTab?.setSelected()
    }

    private var isScanTabFirst: Boolean = true
    private fun naviFragment(id: Int) {
        if (binding.viewPager2.currentItem == id) return
        when (id) {
            0 -> {
                LogEx.logDebug(TAG, "naviFragment 0")
                binding.viewPager2.setCurrentItem(0, false)

                if (tabCanShowAd()) {
                    AdsMgr.showInsert(this, false, object : AdsShowCallBack() {
                        override fun show() {
                            mainFgTabLastShow = System.currentTimeMillis()
                        }

                        override fun close(where: Int) {
                        }

                        override fun failed(where: Int) {
                        }

                        override fun googleFailed(where: Int) {
                        }
                    })
                }
            }

            1 -> {
                LogEx.logDebug(TAG, "naviFragment 1")
                binding.viewPager2.setCurrentItem(1, false)
                val flag = !isScanTabFirst && tabCanShowAd() && AdConfigBean.adsConfigBean.scanTabShowAd
                LogEx.logDebug(TAG, "flag=$flag")
                if (flag) {
                    AdsMgr.showInsert(this, false, object : AdsShowCallBack() {
                        override fun show() {
                            mainFgTabLastShow = System.currentTimeMillis()
                        }

                        override fun close(where: Int) {
                        }

                        override fun failed(where: Int) {
                        }

                        override fun googleFailed(where: Int) {
                        }
                    })
                }
                isScanTabFirst = false
            }

            2 -> {
                LogEx.logDebug(TAG, "naviFragment 2")
                binding.viewPager2.setCurrentItem(2, false)
                if (tabCanShowAd()) {
                    AdsMgr.showInsert(this, false, object : AdsShowCallBack() {
                        override fun show() {
                            mainFgTabLastShow = System.currentTimeMillis()
                        }

                        override fun close(where: Int) {
                        }

                        override fun failed(where: Int) {
                        }

                        override fun googleFailed(where: Int) {
                        }
                    })
                }
            }

            3 -> {
                LogEx.logDebug(TAG, "naviFragment 3")
                binding.viewPager2.setCurrentItem(3, false)
                if (tabCanShowAd() && AdConfigBean.adsConfigBean.setTabShowAd) {
                    AdsMgr.showInsert(this, false, object : AdsShowCallBack() {
                        override fun show() {
                            mainFgTabLastShow = System.currentTimeMillis()
                        }

                        override fun close(where: Int) {
                        }

                        override fun failed(where: Int) {
                        }

                        override fun googleFailed(where: Int) {
                        }
                    })
                }
            }
        }
    }

    private fun tabCanShowAd(): Boolean {
        val tabChangePassTime = (System.currentTimeMillis() - mainFgTabLastShow)
        LogEx.logDebug(
            TAG,
            "tabChangePassTime=$tabChangePassTime " +
                    "tabFgInterval=${AdConfigBean.adsConfigBean.tabFgInterval}"
        )
        val flag = tabChangePassTime / 1000L > AdConfigBean.adsConfigBean.tabFgInterval
        return mainFgTabLastShow == 0L || flag
    }

    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 configSystemBar() {
        immersionBar {
            statusBarColor("#FFFFFFFF")
            statusBarDarkFont(true)
        }
    }

    companion object {
        var mainFgTabLastShow = 0L
    }
}