package com.rgt.superr.ui.main

import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.rgt.superr.R
import com.rgt.superr.SpConstObject.mainPageCount
import com.rgt.superr.base.BaseActivity
import com.rgt.superr.bean.FeatureBean.Companion.JUNK_CLEAN
import com.rgt.superr.bean.HomeTabUIBean
import com.rgt.superr.bean.config.AdConfigBean
import com.rgt.superr.business.ads.AdsMgr
import com.rgt.superr.databinding.ActivityMainBinding
import com.rgt.superr.databinding.ItemHomeTabBinding
import com.rgt.superr.ui.dialog.AppExitDialog
import com.rgt.superr.ui.dialog.NotificationTurnOnDialog
import com.rgt.superr.ui.dialog.RateDialog
import com.rgt.superr.ui.dialog.StoragePermissionDialog
import com.rgt.superr.ui.dialog.permissionStorageJump
import com.rgt.superr.ui.set.SettingsFragment
import com.rgt.superr.utils.PermissionUtils.requestNotificationPermission
import com.rgt.superr.utils.PermissionUtils.requestStoragePermission
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayout.OnTabSelectedListener
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import androidx.core.graphics.toColorInt
import com.rgt.superr.base.jumpAction
import com.rgt.superr.bean.FeatureBean.Companion.BATTERY_INFO
import com.rgt.superr.ui.batteryinfo.BatteryReceiver
import com.rgt.superr.ui.dialog.BatteryUseDialog

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

    val viewModel by lazy { ViewModelProvider(this)[MainViewModel::class.java] }

    private val fragmentList = listOf(
        HomeFragment(),
        SettingsFragment()
    )
    private val viewPagerAdapter by lazy {
        object : FragmentStateAdapter(this) {
            override fun getItemCount(): Int = fragmentList.size

            override fun createFragment(position: Int): Fragment = fragmentList[position]
        }
    }


    override fun useDefaultImmersive() {
        ViewCompat.setOnApplyWindowInsetsListener(binding.root) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, 0, systemBars.right, systemBars.bottom)
            insets
        }

    }

    private fun initDialogFlow() {
        lifecycleScope.launch {
            viewModel.dialogFlow.collectLatest { dialogType ->

                when (dialogType) {
                    "StoreDialog" -> {
                        val dialog = StoragePermissionDialog(this@MainActivity)
                        dialog.action = {
                            requestStoragePermission(launcher) {
                                viewModel.nextShowDialog = false
                            }
                        }
                        dialog.showDialog()
                    }

                    "NotificationDialog" -> {
                        val dialog = NotificationTurnOnDialog(this@MainActivity)
                        dialog.action = {
                            requestNotificationPermission(launcher) {
                                viewModel.nextShowDialog = false
                            }
                        }
                        dialog.showDialog()
                    }

                    "RateDialog" -> {
                        val dialog = RateDialog(this@MainActivity)
                        dialog.showDialog(false)
                    }

                    "BatteryDialog" -> {
                        val percent = BatteryReceiver.level / BatteryReceiver.scale.toFloat()
                        val dl = (percent * 100).toInt()
                        val dialog = BatteryUseDialog(this@MainActivity)
                        dialog.action = {
                            jumpAction(BATTERY_INFO)
                        }
                        dialog.showDialog(dl)

                    }
                }
            }
        }
    }

    override fun initView() {
        super.initView()

        initViewPager2()
        initTab()


        initDialogFlow()
        AdsMgr.showBanner(binding.flBanner, false)

        val lp = binding.fragment.layoutParams as ConstraintLayout.LayoutParams
        if (!AdConfigBean.adsConfigBean.isAdShow) {
            lp.setMargins(0, 0, 0, 0)
        } else {
            lp.setMargins(0, 0, 0, resources.getDimensionPixelSize(R.dimen.dp_60))
        }
        binding.fragment.layoutParams = lp
    }

    private fun initTab() {
        arrayOf(
            HomeTabUIBean(R.drawable.tab_home_selector, getString(R.string.home)),
            HomeTabUIBean(R.drawable.tab_settings_selector, getString(R.string.settings)),
        ).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?.let {
                    if (binding.viewPager2.currentItem == tab.id) return
                    binding.viewPager2.setCurrentItem(tab.id, false)
                }
            }

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

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

            }
        })
    }

    fun TabLayout.Tab.setSelected() {
        val textView = customView?.findViewById<TextView>(R.id.tv_tab)
        textView?.setTextColor(
            ContextCompat.getColor(this@MainActivity, R.color.colorPrimary)
        )
    }

    fun TabLayout.Tab.setUnselected() {
        val textView = customView?.findViewById<TextView>(R.id.tv_tab)
        textView?.setTextColor("#A6A6A6".toColorInt())
    }

    private fun initViewPager2() {
        binding.viewPager2.adapter = viewPagerAdapter
        binding.viewPager2.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                val defaultTab = binding.tabLayout.getTabAt(position)
                defaultTab?.select()
                defaultTab?.setSelected()
            }
        })

    }


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

    override fun handleBackCallBack() {
        val dialog = AppExitDialog(this)
        dialog.action = {
            permissionStorageJump(JUNK_CLEAN)
        }
        dialog.showDialog()
    }

    override fun onResumeOneShoot() {
        super.onResumeOneShoot()
        mainPageCount = mainPageCount + 1

        viewModel.checkDialog(this)
    }


}