package com.simplecleaner.app.ui.main

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.core.graphics.toColorInt
import androidx.fragment.app.Fragment
import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.tabs.TabLayout
import com.simplecleaner.app.R
import com.simplecleaner.app.bean.HomeTabUIBean
import com.simplecleaner.app.databinding.ItemHomeTabBinding

/**
 * Tab管理器，负责管理Tab的创建、配置和交互
 */
class TabManager(
    private val context: Context,
    private val tabLayout: TabLayout,
    private val viewPager2: ViewPager2,
    private val fragmentList: List<Fragment>
) {

    private val tabDataList = mutableListOf<HomeTabUIBean>()
    private var onTabReselectedListener: ((Int) -> Unit)? = null

    /**
     * 初始化Tab
     */
    fun initTabs(tabConfigs: List<HomeTabUIBean>) {
        tabDataList.clear()
        tabDataList.addAll(tabConfigs)
        
        setupTabData()
        setupTabListener()
        setupViewPagerListener()
    }

    /**
     * 设置Tab数据
     */
    private fun setupTabData() {
        tabDataList.forEachIndexed { index, tabData ->
            val tab = createTab(tabData, index)
            tabLayout.addTab(tab)
        }
    }

    /**
     * 创建单个Tab
     */
    private fun createTab(tabData: HomeTabUIBean, index: Int): TabLayout.Tab {
        val tab = tabLayout.newTab()
        val tabView = createTabView(tabData, index)
        tab.customView = tabView
        tab.id = index
        return tab
    }

    /**
     * 创建Tab视图
     */
    private fun createTabView(tabData: HomeTabUIBean, index: Int): View {
        val view = LayoutInflater.from(context).inflate(R.layout.item_home_tab, null)
        val tabBinding = ItemHomeTabBinding.bind(view)
        
        // 设置图标和文本
        tabBinding.ivIcon.setImageResource(tabData.icon)
        tabBinding.tvTab.text = tabData.tab
        
        // 设置红点显示逻辑
        tabBinding.vDian.visibility = if (tabData.showRedDot) View.VISIBLE else View.GONE
        
        // 设置Tab启用状态
        view.isEnabled = tabData.isEnabled
        if (!tabData.isEnabled) {
            view.alpha = 0.5f
        }
        
        return tabBinding.root
    }

    /**
     * 设置Tab选择监听器
     */
    private fun setupTabListener() {
        tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab?) {
                tab?.let { selectedTab ->
                    // 检查Tab是否启用
                    val tabData = tabDataList.getOrNull(selectedTab.id)
                    if (tabData?.isEnabled == false) {
                        // Tab被禁用，不执行切换
                        return@let
                    }
                    
                    if (viewPager2.currentItem != selectedTab.id) {
                        viewPager2.setCurrentItem(selectedTab.id, false)
                    }
                }
            }

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

            override fun onTabReselected(tab: TabLayout.Tab?) {
                onTabReselectedListener?.invoke(tab?.id ?: -1)
            }
        })
    }

    /**
     * 设置ViewPager监听器
     */
    private fun setupViewPagerListener() {
        viewPager2.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                val defaultTab = tabLayout.getTabAt(position)
                defaultTab?.select()
                defaultTab?.setSelected()
            }
        })
    }

    /**
     * 设置Tab重新选择监听器
     */
    fun setOnTabReselectedListener(listener: (Int) -> Unit) {
        onTabReselectedListener = listener
    }

    /**
     * 更新Tab红点状态
     */
    fun updateTabRedDot(tabIndex: Int, showRedDot: Boolean) {
        if (tabIndex in tabDataList.indices) {
            val tab = tabLayout.getTabAt(tabIndex)
            tab?.let { tabLayout ->
                val tabView = tabLayout.customView
                val redDot = tabView?.findViewById<View>(R.id.vDian)
                redDot?.visibility = if (showRedDot) View.VISIBLE else View.GONE
            }
        }
    }

    /**
     * 设置Tab启用状态
     */
    fun setTabEnabled(tabIndex: Int, enabled: Boolean) {
        if (tabIndex in tabDataList.indices) {
            val tab = tabLayout.getTabAt(tabIndex)
            tab?.let { tabLayout ->
                val tabView = tabLayout.customView
                tabView?.isEnabled = enabled
                tabView?.alpha = if (enabled) 1.0f else 0.5f
            }
        }
    }

    /**
     * 获取Tab数据列表
     */
    fun getTabDataList(): List<HomeTabUIBean> = tabDataList.toList()

    /**
     * Tab选中状态设置
     */
    fun TabLayout.Tab.setSelected() {
        val textView = customView?.findViewById<TextView>(R.id.tv_tab)
        textView?.setTextColor(
            ContextCompat.getColor(context, R.color.colorPrimary)
        )
    }

    /**
     * Tab未选中状态设置
     */
    fun TabLayout.Tab.setUnselected() {
        val textView = customView?.findViewById<TextView>(R.id.tv_tab)
        textView?.setTextColor("#A6A6A6".toColorInt())
    }
} 