package com.example.myapplication.ui.shop

import android.content.Intent
import android.graphics.Typeface
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.HorizontalScrollView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import androidx.viewpager2.widget.ViewPager2
import com.example.myapplication.R
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.adapter.FragmentStateAdapter
import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.animation.ValueAnimator
import android.animation.ArgbEvaluator

class ShopFragment : Fragment() {

    private lateinit var viewPager: ViewPager2
    private lateinit var tagScroll: HorizontalScrollView
    private lateinit var tagContainer: LinearLayout

    // 标签标题，可以根据需要修改
    private val tabTitles = listOf("全部", "数码", "服饰", "家居", "美食","数码", "服饰", "家居", "美食")

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_shop, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        
        // 金币充值按钮点击
        view.findViewById<View>(R.id.rechargeButton).setOnClickListener {
            findNavController().navigate(R.id.action_global_goldCoinRechargeFragment)
        }
        // 我的皮肤按钮点击
        view.findViewById<View>(R.id.skinButton).setOnClickListener {
            findNavController().navigate(R.id.action_shopfragment_to_myskin)
        }
        // 搜索按钮点击
        view.findViewById<View>(R.id.searchButton).setOnClickListener {
            findNavController().navigate(R.id.action_shopfragment_to_searchfragment)
        }
        


        tagScroll = view.findViewById(R.id.tagScroll)
        tagContainer = view.findViewById(R.id.tagContainer)
        viewPager = view.findViewById(R.id.viewPager)
        val rechargeButton = view.findViewById<LinearLayout>(R.id.rechargeButton)
        rechargeButton.setOnClickListener {
            findNavController().navigate(R.id.action_global_goldCoinRechargeFragment)
        }
        // 1. 设置 ViewPager2 的 Adapter
        viewPager.adapter = ShopPagerAdapter(this, tabTitles.size)

        // 2. 创建顶部标签
        setupTags()

        // 3. 绑定 ViewPager2 滑动 & 标签联动
        setupViewPager()
    }

/** 动态创建标签 TextView */
private fun setupTags() {
    tagContainer.removeAllViews()

    val context = requireContext()
    val density = context.resources.displayMetrics.density

    // ⬇⬇⬇ 你要求的 padding 值（已适配 dp）
    val paddingHorizontal = (16 * density).toInt()   // 左右 16dp
    val paddingVertical = (6 * density).toInt()      // 上下 6dp
    val marginEnd = (8 * density).toInt()            // 标签之间 8dp 间距

    tabTitles.forEachIndexed { index, title ->
        val tv = TextView(context).apply {
            text = title
            textSize = 12f  // 字体大小 12sp

            // ✅ 设置内边距（左右16dp，上下6dp）
            setPadding(
                paddingHorizontal,
                paddingVertical,
                paddingHorizontal,
                paddingVertical
            )

            layoutParams = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.MATCH_PARENT
            ).apply {
                setMargins(0, 0, marginEnd, 0)  // 右侧 8dp 间距
            }

            gravity = android.view.Gravity.CENTER

            // 胶囊大圆角背景
            background = createCapsuleBackground()

            // 初始化选中状态
            isSelected = index == 0
            updateTagStyleNoAnim(this, isSelected) // 初始化不用动画，避免闪烁

            // 点击切换页面
            setOnClickListener {
                if (viewPager.currentItem != index) {
                    viewPager.currentItem = index
                }
            }
        }

        tagContainer.addView(tv)
    }
}


    
    private fun createCapsuleBackground(): GradientDrawable {
        val density = resources.displayMetrics.density
        return GradientDrawable().apply {
            shape = GradientDrawable.RECTANGLE
            cornerRadius = 50f * density  // 大圆角
            setColor(Color.parseColor("#F1F1F1")) // 默认未选中背景
            setStroke((2 * density).toInt(), Color.parseColor("#F1F1F1"))
        }
    }
    

    /** 设置 ViewPager2 的监听，实现滑动联动标签 */
    private fun setupViewPager() {
        viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                updateTagState(position)
            }
        })
    }

    /** 根据当前位置更新所有标签的选中状态 */
    private fun updateTagState(position: Int) {
        for (i in 0 until tagContainer.childCount) {
            val child = tagContainer.getChildAt(i) as TextView
            val newSelected = i == position
    
            // ✅ 如果这个标签的选中状态没有变化，就不要动它，避免“闪一下”
            if (child.isSelected == newSelected) continue
    
            child.isSelected = newSelected
            updateTagStyleWithAnim(child, newSelected)
    
            if (newSelected) {
                // 让选中项尽量居中显示
                child.post {
                    val scrollX = child.left - (tagScroll.width - child.width) / 2
                    tagScroll.smoothScrollTo(scrollX, 0)
                }
            }
        }
    }
    

    /** 统一控制标签样式，可根据自己项目主题改颜色/大小 **/
    private fun updateTagStyle(textView: TextView, selected: Boolean) {
        val context = textView.context
        val density = context.resources.displayMetrics.density
    
        // 确保背景是 GradientDrawable，方便改边框和背景色
        val bg = (textView.background as? GradientDrawable)
            ?: createCapsuleBackground().also { textView.background = it }
    
        // 颜色配置（按你要求）
        val selectedTextColor = Color.parseColor("#1B1F1A")
        val unselectedTextColor = Color.parseColor("#9F9F9F")
    
        val selectedStrokeColor = Color.parseColor("#02BEAC")
        val unselectedStrokeColor = Color.parseColor("#F1F1F1")
    
        val selectedBgColor = Color.parseColor("#FFFFFF")
        val unselectedBgColor = Color.parseColor("#F1F1F1")
    
        // 当前颜色作为起点
        val startTextColor = textView.currentTextColor
        val startStrokeColor = try {
            // 没有方便的 getter，这里通过 isSelected 反推一个“起点”
            if (selected) unselectedStrokeColor else selectedStrokeColor
        } catch (e: Exception) {
            if (selected) unselectedStrokeColor else selectedStrokeColor
        }
        val startBgColor = if (selected) unselectedBgColor else selectedBgColor
    
        // 目标颜色
        val endTextColor = if (selected) selectedTextColor else unselectedTextColor
        val endStrokeColor = if (selected) selectedStrokeColor else unselectedStrokeColor
        val endBgColor = if (selected) selectedBgColor else unselectedBgColor
    
        val strokeWidth = (2 * density).toInt()
    
        val animator = ValueAnimator.ofFloat(0f, 1f).apply {
            duration = 200L // 动画时长可以自己调
            addUpdateListener { va ->
                val fraction = va.animatedFraction
                val evaluator = ArgbEvaluator()
    
                val currentTextColor =
                    evaluator.evaluate(fraction, startTextColor, endTextColor) as Int
                val currentStrokeColor =
                    evaluator.evaluate(fraction, startStrokeColor, endStrokeColor) as Int
                val currentBgColor =
                    evaluator.evaluate(fraction, startBgColor, endBgColor) as Int
    
                textView.setTextColor(currentTextColor)
                bg.setStroke(strokeWidth, currentStrokeColor)
                bg.setColor(currentBgColor)
            }
        }
        animator.start()
    
        // 字重变化
        textView.setTypeface(null, if (selected) Typeface.BOLD else Typeface.NORMAL)
    }
    
    
    

    /** ViewPager2 的 Adapter，可以替换成你的真实 Fragment */
    private class ShopPagerAdapter(
        fragment: Fragment,
        private val pageCount: Int
    ) : FragmentStateAdapter(fragment) {

        override fun getItemCount(): Int = pageCount

        override fun createFragment(position: Int): Fragment {
            // 根据 position 返回不同的页面 Fragment
            
            // 这里先用一个简单的占位示例
            return SimplePageFragment.newInstance("当前页：${position + 1}")
        }
    }

    private fun updateTagStyleNoAnim(textView: TextView, selected: Boolean) {
        val density = resources.displayMetrics.density
        val bg = (textView.background as? GradientDrawable)
            ?: createCapsuleBackground().also { textView.background = it }
    
        val strokeWidth = (2 * density).toInt()
    
        if (selected) {
            bg.setColor(Color.parseColor("#FFFFFF"))          // 背景白色
            bg.setStroke(strokeWidth, Color.parseColor("#02BEAC")) // 边框 #02BEAC
            textView.setTextColor(Color.parseColor("#1B1F1A"))     // 字体 #1B1F1A
            textView.setTypeface(null, Typeface.BOLD)
        } else {
            bg.setColor(Color.parseColor("#F1F1F1"))          // 背景 #F1F1F1
            bg.setStroke(strokeWidth, Color.parseColor("#F1F1F1")) // 边框 #F1F1F1
            textView.setTextColor(Color.parseColor("#9F9F9F"))     // 字体 #9F9F9F
            textView.setTypeface(null, Typeface.NORMAL)
        }
    }

    private fun updateTagStyleWithAnim(textView: TextView, selected: Boolean) {
        val density = resources.displayMetrics.density
        val bg = (textView.background as? GradientDrawable)
            ?: createCapsuleBackground().also { textView.background = it }
    
        val strokeWidth = (2 * density).toInt()
    
        // 颜色配置
        val selectedTextColor = Color.parseColor("#1B1F1A")
        val unselectedTextColor = Color.parseColor("#9F9F9F")
    
        val selectedStrokeColor = Color.parseColor("#02BEAC")
        val unselectedStrokeColor = Color.parseColor("#F1F1F1")
    
        val selectedBgColor = Color.parseColor("#FFFFFF")
        val unselectedBgColor = Color.parseColor("#F1F1F1")
    
        // 起点、终点颜色我们自己定义，而不是乱读当前值，避免抖动
        val startTextColor: Int
        val endTextColor: Int
        val startStrokeColor: Int
        val endStrokeColor: Int
        val startBgColor: Int
        val endBgColor: Int
    
        if (selected) {
            // 未选中 -> 选中
            startTextColor = unselectedTextColor
            endTextColor = selectedTextColor
    
            startStrokeColor = unselectedStrokeColor
            endStrokeColor = selectedStrokeColor
    
            startBgColor = unselectedBgColor
            endBgColor = selectedBgColor
        } else {
            // 选中 -> 未选中
            startTextColor = selectedTextColor
            endTextColor = unselectedTextColor
    
            startStrokeColor = selectedStrokeColor
            endStrokeColor = unselectedStrokeColor
    
            startBgColor = selectedBgColor
            endBgColor = unselectedBgColor
        }
    
        val evaluator = ArgbEvaluator()
    
        val animator = ValueAnimator.ofFloat(0f, 1f).apply {
            duration = 200L
            addUpdateListener { va ->
                val fraction = va.animatedFraction
    
                val currentTextColor =
                    evaluator.evaluate(fraction, startTextColor, endTextColor) as Int
                val currentStrokeColor =
                    evaluator.evaluate(fraction, startStrokeColor, endStrokeColor) as Int
                val currentBgColor =
                    evaluator.evaluate(fraction, startBgColor, endBgColor) as Int
    
                textView.setTextColor(currentTextColor)
                bg.setStroke(strokeWidth, currentStrokeColor)
                bg.setColor(currentBgColor)
            }
        }
        animator.start()
    
        textView.setTypeface(null, if (selected) Typeface.BOLD else Typeface.NORMAL)
    }
    
}
