package com.app.intelligent.board.uifragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.graphics.PorterDuff
import android.widget.ArrayAdapter
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentPagerAdapter
import com.app.intelligent.board.AppContextHelper
import com.app.intelligent.board.R
import com.app.intelligent.board.databinding.FragmentHomeMainBinding
import android.widget.ImageView
import android.widget.TextView
import android.graphics.Color
import android.content.Intent  // 新增：导入Intent
import com.app.intelligent.board.uiactivity.SearchActivity  // 新增：导入搜索页面Activity

class HomeMainFragment : Fragment() {

    private lateinit var vb: FragmentHomeMainBinding
    private val tabTitles by lazy {
        AppContextHelper.list.mapNotNull { it.parentName }.distinct()
    }
    private var currentSelectedPos = 0 // 记录当前选中位置

    companion object {
        @JvmStatic
        fun newInstance() = HomeMainFragment()
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        vb = FragmentHomeMainBinding.inflate(layoutInflater, container, false)
        initSpinnerAndViewPager()
        initSearchButton() // 初始化搜索按钮
        return vb.root
    }

    /**
     * 初始化搜索按钮点击事件（实现跳转）
     */
    private fun initSearchButton() {
        vb.ivSearch.setOnClickListener {
            // 1. 创建Intent，跳转到SearchActivity
            val intent = Intent(requireContext(), SearchActivity::class.java)
            // 2. 可选：传递当前选中的分类（供搜索页面使用）
            intent.putExtra("selectedCategory", tabTitles[currentSelectedPos])
            // 3. 启动搜索页面
            startActivity(intent)
        }
    }

    // 以下代码保持不变...
    private fun initSpinnerAndViewPager() {
        // 1. 初始化ViewPager适配器
        val pagerAdapter = object : FragmentPagerAdapter(childFragmentManager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
            override fun getCount(): Int = tabTitles.size
            override fun getItem(position: Int): Fragment = CategoryItemContentFragment.newInstance(tabTitles[position])
            override fun getPageTitle(position: Int): CharSequence? = tabTitles[position]
        }

        // 2. 绑定ViewPager
        vb.viewPager.adapter = pagerAdapter
        vb.viewPager.offscreenPageLimit = if (tabTitles.size > 3) 3 else tabTitles.size - 1

        // 3. 初始化Spinner（下拉选择器）
        initSpinner()
    }

    private fun initSpinner() {
        val spinnerAdapter = object : ArrayAdapter<String>(
            requireContext(),
            R.layout.custom_spinner_item,
            tabTitles
        ) {
            override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View {
                val view = convertView ?: LayoutInflater.from(context).inflate(R.layout.custom_spinner_dropdown_item, parent, false)
                val textView = view.findViewById<TextView>(R.id.spinner_text)
                textView.text = tabTitles[position]

                if (position == currentSelectedPos) {
                    textView.setBackgroundResource(R.drawable.spinner_selected_bg)
                    textView.setTextColor(Color.DKGRAY)
                } else {
                    textView.setBackgroundResource(0)
                    textView.setTextColor(resources.getColor(R.color.main_text_color))
                }
                return view
            }

            override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
                val view = convertView ?: LayoutInflater.from(context).inflate(R.layout.custom_spinner_item, parent, false)
                val textView = view.findViewById<TextView>(R.id.spinner_text)
                val arrowView = view.findViewById<ImageView>(R.id.spinner_arrow)
                textView.text = tabTitles[position]

                val targetColor = resources.getColor(R.color.dark_gray)
                textView.setTextColor(targetColor)
                arrowView.setColorFilter(targetColor, PorterDuff.Mode.SRC_IN)

                return view
            }
        }

        vb.categorySpinner.adapter = spinnerAdapter

        // 宽度计算（适配文字+箭头+间距）
        vb.categorySpinner.post {
            val longestText = tabTitles.maxByOrNull { it.length } ?: "recommend"
            val tempTextView = TextView(requireContext()).apply {
                text = longestText
                textSize = 16f
            }
            tempTextView.measure(
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
            )
            val arrowWidth = (14 * resources.displayMetrics.density).toInt()
            val textArrowMargin = (30 * resources.displayMetrics.density).toInt()
            val paddingWidth = (32 * resources.displayMetrics.density).toInt()
            val finalWidth = tempTextView.measuredWidth + arrowWidth + textArrowMargin + paddingWidth

            vb.categorySpinner.layoutParams.width = finalWidth
            vb.categorySpinner.requestLayout()
        }

        // Spinner选择监听
        vb.categorySpinner.onItemSelectedListener = object : android.widget.AdapterView.OnItemSelectedListener {
            override fun onItemSelected(parent: android.widget.AdapterView<*>, view: View?, position: Int, id: Long) {
                currentSelectedPos = position
                vb.viewPager.currentItem = position
                spinnerAdapter.notifyDataSetChanged()
            }

            override fun onNothingSelected(parent: android.widget.AdapterView<*>) {}
        }

        // ViewPager切换监听
        vb.viewPager.addOnPageChangeListener(object : androidx.viewpager.widget.ViewPager.OnPageChangeListener {
            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {}
            override fun onPageSelected(position: Int) {
                currentSelectedPos = position
                vb.categorySpinner.setSelection(position, false)
                spinnerAdapter.notifyDataSetChanged()
            }
            override fun onPageScrollStateChanged(state: Int) {}
        })
    }

    private fun refreshCurrentCategoryFragment(position: Int, categoryName: String) {
        val fragmentTag = "android:switcher:${vb.viewPager.id}:$position"
        val currentFragment = childFragmentManager.findFragmentByTag(fragmentTag)
        if (currentFragment is CategoryItemContentFragment) {
            currentFragment.refreshCategoryData(categoryName)
        }
    }
}