package com.base.appzxhy.ui.main

import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.core.content.ContextCompat
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.base.appzxhy.R
import com.base.appzxhy.SpConstObject.mainPageCount
import com.base.appzxhy.base.BaseActivity
import com.base.appzxhy.bean.HomeTabUIBean
import com.base.appzxhy.business.ads.AdsMgr
import com.base.appzxhy.databinding.ActivityMainBinding
import com.base.appzxhy.databinding.ItemHomeTabBinding
import com.base.appzxhy.ui.dialog.ExitDialog
import com.base.appzxhy.ui.dialog.NotificationTurnOnDialog
import com.base.appzxhy.ui.dialog.RateDialog
import com.base.appzxhy.ui.dialog.StoragePermissionDialog
import com.base.appzxhy.ui.recyclebin.RecycleBinFragment
import com.base.appzxhy.ui.set.SettingsFragment
import com.base.appzxhy.utils.PermissionUtils.requestNotificationPermission
import com.base.appzxhy.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

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

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

    lateinit var exitDialog: ExitDialog
    private val fragmentList = listOf(
//        Home2Fragment(),
        Home3Fragment(),
        SettingsFragment(),
//        RecycleBinFragment()
    )

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

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

    override fun initView() {
        super.initView()

        initTab()
        initViewPager2()
        initDialogFlow()
        AdsMgr.showBanner(binding.flBanner, false)
        exitDialog = ExitDialog(this)
        exitDialog.init()
        setStatusBarColor(getColor(R.color.colorPrimary))
    }

    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)
                    }
                }
            }
        }
    }

    private fun initViewPager2() {
        binding.viewPager2.adapter = viewPagerAdapter
        binding.viewPager2.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
//                if (position == 0) {
//                    setStatusBarColor(getColor(R.color.colorPrimary))
//                } else {
//                    setStatusBarColor(getColor(R.color.transparent))
//                }
                val defaultTab = binding.tabLayout.getTabAt(position)
                defaultTab?.select()
                defaultTab?.setSelected()
            }
        })
    }

    private fun initTab() {
        arrayOf(
            HomeTabUIBean(R.drawable.tab_home_selector, getString(R.string.home)),
//            HomeTabUIBean(R.drawable.tab_recovery_selector, getString(R.string.recovery)),
            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.colorPrimary))
            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)
                    tab.setSelected()
                }
            }

            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(Color.parseColor("#999999"))
    }

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

        viewModel.checkDialog(this)
        viewModel.refreshRecycleBin()
    }

    override fun handleBackCallBack() {
        exitDialog.show()
    }
}