package com.example.myapplication.ui.shop

import android.annotation.SuppressLint
import android.animation.ArgbEvaluator
import android.animation.ValueAnimator
import android.graphics.Color
import android.graphics.Typeface
import android.graphics.drawable.GradientDrawable
import android.os.Bundle
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.widget.HorizontalScrollView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.example.myapplication.R
import com.example.myapplication.network.ApiResponse
import com.example.myapplication.network.RetrofitClient
import com.example.myapplication.network.Theme
import com.example.myapplication.network.Wallet
import com.example.myapplication.network.themeStyle
import kotlinx.coroutines.launch

class ShopFragment : Fragment(R.layout.fragment_shop) {

    private lateinit var viewPager: ViewPager2
    private lateinit var tagScroll: HorizontalScrollView
    private lateinit var tagContainer: LinearLayout
    private lateinit var balance: TextView
    private lateinit var swipeRefreshLayout: SwipeRefreshLayout

    // 风格 tabs
    private var tabTitles: List<Theme> = emptyList()
    private var styleIds: List<Int> = emptyList()

    // ✅ 共享数据/缓存/加载都交给 VM
    private val vm: ShopViewModel by viewModels()

    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)
        balance = view.findViewById(R.id.balance)
        swipeRefreshLayout = view.findViewById<SwipeRefreshLayout>(R.id.swipeRefreshLayout)

        // 设置下拉刷新监听器
        swipeRefreshLayout.setOnRefreshListener {
            refreshData()
        }

        // 设置刷新指示器颜色
        swipeRefreshLayout.setColorSchemeColors(
            Color.parseColor("#02BEAC"),
            Color.parseColor("#1B1F1A"),
            Color.parseColor("#9F9F9F")
        )

        // 禁用默认的刷新行为，使用自定义逻辑
        swipeRefreshLayout.isEnabled = false

        // 设置 ViewPager 的子页面滚动监听
        setupViewPagerScrollListener()

        loadInitialData()
        
        // 修复 ViewPager2 和 SwipeRefreshLayout 的手势冲突
        fixViewPager2SwipeConflict()
    }

    private fun loadInitialData() {
        viewLifecycleOwner.lifecycleScope.launch {
            val walletResp = getwalletBalance()
            val balanceText = (walletResp?.data?.balanceDisplay ?: 0).toString()
            balance.text = balanceText
            adjustBalanceTextSize(balanceText)

            val themeListResp = getThemeList()
            tabTitles = themeListResp?.data ?: emptyList()
            Log.d("1314520-Shop", "风格列表: $tabTitles")

            styleIds = tabTitles.map { it.id }

            viewPager.adapter = ShopPagerAdapter(this@ShopFragment, styleIds)

            setupTags()
            setupViewPager()

            // ✅ 默认加载第一个（交给 VM）
            viewPager.post {
                styleIds.firstOrNull()?.let { vm.loadStyleIfNeeded(it) }
            }
        }
    }

    /**
     * 根据字符数量调整余额文本的字体大小
     * 字符数量越多，字体越小
     */
    private fun adjustBalanceTextSize(text: String) {
        val maxFontSize = 40f // 最大字体大小（sp）
        val minFontSize = 16f // 最小字体大小（sp）
        
        // 根据字符数量计算字体大小
        val fontSize = when (text.length) {
            0, 1, 2, 3 -> maxFontSize // 0-3个字符使用最大字体
            4 -> 36f
            5 -> 32f
            6 -> 28f
            7 -> 24f
            8 -> 22f
            9 -> 20f
            else -> minFontSize // 10个字符及以上使用最小字体
        }
        
        balance.textSize = fontSize
    }

    private fun refreshData() {
        viewLifecycleOwner.lifecycleScope.launch {
            try {
                // 重新获取钱包余额
                val walletResp = getwalletBalance()
                val balanceText = (walletResp?.data?.balanceDisplay ?: 0).toString()
                balance.text = balanceText
                adjustBalanceTextSize(balanceText)

                // 重新获取主题列表
                val themeListResp = getThemeList()
                val newTabTitles = themeListResp?.data ?: emptyList()
                
                // 检查主题列表是否有变化
                if (newTabTitles != tabTitles) {
                    tabTitles = newTabTitles
                    styleIds = tabTitles.map { it.id }
                    
                    // 重新设置适配器
                    viewPager.adapter = ShopPagerAdapter(this@ShopFragment, styleIds)
                    
                    // 重新设置标签
                    setupTags()
                    
                    // 通知 ViewModel 清除缓存
                    vm.clearCache()
                    
                    // 强制重新加载所有页面的数据
                    styleIds.forEach { styleId ->
                        // 强制重新加载，即使有缓存也要重新获取
                        vm.forceLoadStyle(styleId)
                    }
                } else {
                    // 主题列表没有变化，强制重新加载当前页面的数据
                    val currentPosition = viewPager.currentItem
                    styleIds.getOrNull(currentPosition)?.let { vm.forceLoadStyle(it) }
                }
                
                Log.d("1314520-Shop", "下拉刷新完成")
            } catch (e: Exception) {
                Log.e("1314520-Shop", "下拉刷新失败", e)
            } finally {
                // 停止刷新动画
                swipeRefreshLayout.isRefreshing = false
            }
        }
    }

    /** 子页读取缓存（从 VM 读） */
    fun getCachedList(styleId: Int): List<themeStyle> = vm.getCached(styleId)

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

        val context = requireContext()
        val density = context.resources.displayMetrics.density
        val paddingHorizontal = (16 * density).toInt()
        val paddingVertical = (6 * density).toInt()
        val marginEnd = (8 * density).toInt()

        tabTitles.forEachIndexed { index, title ->
            val tv = TextView(context).apply {
                text = title.styleName
                textSize = 12f
                setPadding(paddingHorizontal, paddingVertical, paddingHorizontal, paddingVertical)

                layoutParams = LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.MATCH_PARENT
                ).apply { setMargins(0, 0, marginEnd, 0) }

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

    private fun setupViewPager() {
        // ✅ 只设置一次
        viewPager.offscreenPageLimit = 1

        viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                updateTagState(position)

                // ✅ 切换到某页就按需加载（交给 VM）
                styleIds.getOrNull(position)?.let { vm.loadStyleIfNeeded(it) }
            }
        })
    }

    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 setupViewPagerScrollListener() {
        // 监听 AppBarLayout 的展开状态来判断是否在顶部
        view?.findViewById<com.google.android.material.appbar.AppBarLayout>(R.id.appBar)?.addOnOffsetChangedListener { appBarLayout, verticalOffset ->
            val isAtTop = verticalOffset == 0
            swipeRefreshLayout.isEnabled = isAtTop
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    private fun fixViewPager2SwipeConflict() {
        val rv = viewPager.getChildAt(0) as? RecyclerView ?: return
        rv.setOnTouchListener { v, ev ->
            when (ev.actionMasked) {
                MotionEvent.ACTION_DOWN -> v.parent?.requestDisallowInterceptTouchEvent(true)
                MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> 
                    v.parent?.requestDisallowInterceptTouchEvent(false)
            }
            false
        }
    }

    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"))
            textView.setTextColor(Color.parseColor("#1B1F1A"))
            textView.setTypeface(null, Typeface.BOLD)
        } else {
            bg.setColor(Color.parseColor("#F1F1F1"))
            bg.setStroke(strokeWidth, Color.parseColor("#F1F1F1"))
            textView.setTextColor(Color.parseColor("#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 colorsArray = if (selected) {
            arrayOf(
                unselectedTextColor, selectedTextColor,
                unselectedStrokeColor, selectedStrokeColor,
                unselectedBgColor, selectedBgColor
            )
        } else {
            arrayOf(
                selectedTextColor, unselectedTextColor,
                selectedStrokeColor, unselectedStrokeColor,
                selectedBgColor, unselectedBgColor
            )
        }
        
        val startTextColor = colorsArray[0]
        val endTextColor = colorsArray[1]
        val startStrokeColor = colorsArray[2]
        val endStrokeColor = colorsArray[3]
        val startBgColor = colorsArray[4]
        val endBgColor = colorsArray[5]

        val evaluator = ArgbEvaluator()
        ValueAnimator.ofFloat(0f, 1f).apply {
            duration = 200L
            addUpdateListener { va ->
                val f = va.animatedFraction
                textView.setTextColor(evaluator.evaluate(f, startTextColor, endTextColor) as Int)
                bg.setStroke(strokeWidth, evaluator.evaluate(f, startStrokeColor, endStrokeColor) as Int)
                bg.setColor(evaluator.evaluate(f, startBgColor, endBgColor) as Int)
            }
            start()
        }

        textView.setTypeface(null, if (selected) Typeface.BOLD else Typeface.NORMAL)
    }

    private inner class ShopPagerAdapter(
        fragment: Fragment,
        private val styleIds: List<Int>
    ) : FragmentStateAdapter(fragment) {

        override fun getItemCount(): Int = styleIds.size

        override fun createFragment(position: Int): Fragment {
            val styleId = styleIds[position]
            return ShopStylePageFragment.newInstance(styleId)
        }
    }

    // ============================ 网络请求 ============================

    private suspend fun getwalletBalance(): ApiResponse<Wallet>? {
        return try {
            RetrofitClient.apiService.walletBalance()
        } catch (e: Exception) {
            Log.e("1314520-ShopFragment", "获取钱包余额失败", e)
            null
        }
    }

    private suspend fun getThemeList(): ApiResponse<List<Theme>>? {
        return try {
            RetrofitClient.apiService.themeList()
        } catch (e: Exception) {
            Log.e("1314520-ShopFragment", "获取主题风格失败", e)
            null
        }
    }
    /**
     * 根据余额值计算字体大小
     * 基础字体大小16sp，数字越大字体越小
     */
    // private fun calculateFontSize(balance: Double): Float {
    //     val baseSize = 40f // 基础字体大小
    //     val minSize = 5f  // 最小字体大小
    //     val maxSize = 40f  // 最大字体大小
        
    //     // 使用对数函数实现平滑的字体大小变化
    //     // 当余额为0时使用最大字体，余额越大字体越小
    //     val scaleFactor = when {
    //         balance <= 0 -> 1.0
    //         balance < 10 -> 0.93
    //         balance < 100 -> 0.86
    //         balance < 1000 -> 0.79
    //         balance < 10000 -> 0.72
    //         balance < 100000 -> 0.65
    //         balance < 1000000 -> 0.58
    //         balance < 10000000 -> 0.51
    //         balance < 100000000 -> 0.44
    //         balance < 1000000000 -> 0.37
    //         balance < 10000000000 -> 0.3
    //         balance < 100000000000 -> 0.23
    //         balance < 1000000000000 -> 0.16
    //         else -> 0.09
    //     }
        
    //     val calculatedSize = baseSize * scaleFactor.toFloat()
        
    //     // 确保字体大小在最小和最大限制范围内
    //     return calculatedSize.coerceIn(minSize, maxSize)
    // }
}
