package com.simplecleaner.app.ui.main

import android.view.View
import androidx.constraintlayout.widget.ConstraintLayout
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 com.simplecleaner.app.R
import com.simplecleaner.app.SpConstObject.mainPageCount
import com.simplecleaner.app.base.BaseActivity
import com.simplecleaner.app.bean.FeatureBean.Companion.JUNK_CLEAN
import com.simplecleaner.app.bean.HomeTabUIBean
import com.simplecleaner.app.bean.config.AdConfigBean
import com.simplecleaner.app.business.ads.AdsMgr
import com.simplecleaner.app.databinding.ActivityMainBinding
import com.simplecleaner.app.ui.dialog.AppExitDialog
import com.simplecleaner.app.ui.dialog.NotificationTurnOnDialog
import com.simplecleaner.app.ui.dialog.RateDialog
import com.simplecleaner.app.ui.dialog.StoragePermissionDialog
import com.simplecleaner.app.ui.dialog.permissionStorageJump
import com.simplecleaner.app.ui.set.SettingsFragment
import com.simplecleaner.app.utils.PermissionUtils.requestNotificationPermission
import com.simplecleaner.app.utils.PermissionUtils.requestStoragePermission
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import com.simplecleaner.app.base.jumpAction
import com.simplecleaner.app.bean.FeatureBean.Companion.BATTERY_INFO
import com.simplecleaner.app.ui.batteryinfo.BatteryReceiver
import com.simplecleaner.app.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]
        }
    }

    // Tab管理器
    private val tabManager by lazy {
        TabManager(this, binding.tabLayout, binding.viewPager2, fragmentList)
    }

    // 定义Tab数据，便于维护和扩展
    private val tabDataList by lazy {
        listOf(
            HomeTabUIBean.createDefault(
                icon = R.drawable.tab_home_selector,
                tab = getString(R.string.home)
            ),
            HomeTabUIBean.createDefault(
                icon = R.drawable.tab_settings_selector,
                tab = getString(R.string.settings),
                showRedDot = true
            )
        )
    }


    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() {
        // 使用TabManager初始化Tab
        tabManager.initTabs(tabDataList)
        
        // 设置Tab重新选择监听器
        tabManager.setOnTabReselectedListener { tabIndex ->
            handleTabReselected(tabIndex)
        }
    }

    /**
     * 处理Tab重新选择事件
     */
    private fun handleTabReselected(tabIndex: Int) {
        when (tabIndex) {
            TAB_INDEX_HOME -> {
                // 首页重新选择，可以刷新数据
//                (fragmentList[TAB_INDEX_HOME] as? HomeFragment)?.refreshData()
            }
            TAB_INDEX_SETTINGS -> {
                // 设置页面重新选择，可以刷新设置状态
//                (fragmentList[TAB_INDEX_SETTINGS] as? SettingsFragment)?.refreshSettings()
            }
        }
    }

    /**
     * 更新Tab红点状态
     */
    fun updateTabRedDot(tabIndex: Int, showRedDot: Boolean) {
        tabManager.updateTabRedDot(tabIndex, showRedDot)
    }

    /**
     * 设置Tab启用状态
     */
    fun setTabEnabled(tabIndex: Int, enabled: Boolean) {
        tabManager.setTabEnabled(tabIndex, enabled)
    }

    private fun initViewPager2() {
        binding.viewPager2.adapter = viewPagerAdapter
        // ViewPager监听器现在由TabManager处理
    }


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


    companion object {
        private const val TAB_INDEX_HOME = 0
        private const val TAB_INDEX_SETTINGS = 1
    }
}