package com.app.input.inputaura.kmnhffs

import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.PopupWindow
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.app.input.inputaura.InputAura
import com.app.input.inputaura.R
import com.app.input.inputaura.dasda.Shikamaru
import com.app.input.inputaura.databinding.HgiusBinding
import com.app.input.inputaura.onjfsgvfsf.DubTbf
import com.google.android.material.tabs.TabLayoutMediator
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class FragmentHome : Fragment() {

    private lateinit var vb: HgiusBinding
    private lateinit var categoryViewPagerAdapter: CategoryViewPagerAdapter
    private lateinit var categoryNames: List<String>
    private var popupWindow: PopupWindow? = null

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

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        vb = HgiusBinding.inflate(inflater, container, false)
        return vb.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        // 获取所有分类名称
        categoryNames = InputAura.Companion.list.map { it.parentName }
        initCategoryViewPager()
        setupSeeAllDropdown()
    }

    private fun initCategoryViewPager() {
        // 创建ViewPager适配器
        categoryViewPagerAdapter = CategoryViewPagerAdapter(this, categoryNames)
        vb.categoryViewPager.adapter = categoryViewPagerAdapter

        // 设置TabLayout和ViewPager的联动
        TabLayoutMediator(vb.categoryTabLayout, vb.categoryViewPager) { tab, position ->
            tab.text = categoryNames[position]
        }.attach()

        // 设置ViewPager预加载数量
        vb.categoryViewPager.offscreenPageLimit = 1

        // 监听页面变化
        vb.categoryViewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                // 可以在这里添加页面切换时的逻辑
            }
        })
    }

    private fun setupSeeAllDropdown() {
        vb.seeAllButton.setOnClickListener { view ->
            // 如果已经显示，则关闭
            if (popupWindow?.isShowing == true) {
                popupWindow?.dismiss()
            } else {
                showDropdownPopup(view)
            }
        }
    }

    private fun showDropdownPopup(anchorView: View) {
        // 创建弹出窗口的内容视图
        val inflater = requireContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
        val popupView = inflater.inflate(R.layout.litdg, null)

        // 获取当前选中的位置
        val currentPosition = vb.categoryViewPager.currentItem

        // 计算文本宽度，找到最长的文本
        val paint = TextView(requireContext()).paint
        paint.textSize = resources.getDimension(R.dimen.text_size_14sp)

        var maxTextWidth = 0
        for (category in categoryNames) {
            val width = paint.measureText(category).toInt()
            if (width > maxTextWidth) {
                maxTextWidth = width
            }
        }

        // 添加内边距（左右各16dp）
        val horizontalPadding = resources.getDimensionPixelSize(R.dimen.dropdown_item_padding) * 2
        val calculatedWidth = (maxTextWidth + horizontalPadding).coerceIn(
            resources.getDimensionPixelSize(R.dimen.dropdown_min_width),
            resources.getDimensionPixelSize(R.dimen.dropdown_max_width)
        )

        // 设置RecyclerView
        val recyclerView = popupView.findViewById<RecyclerView>(R.id.dropdown_recycler_view)
        recyclerView.layoutManager = LinearLayoutManager(requireContext())

        // 设置适配器
        recyclerView.adapter = CategoryDropdownAdapter(categoryNames, currentPosition) { position ->
            vb.categoryViewPager.currentItem = position
            vb.categoryTabLayout.getTabAt(position)?.select()
            popupWindow?.dismiss()
        }

        // 设置收起按钮点击事件
        popupView.findViewById<View>(R.id.collapse_container).setOnClickListener {
            popupWindow?.dismiss()
        }

        // 创建PopupWindow
        popupWindow = PopupWindow(
            popupView,
            calculatedWidth, // 使用计算出的宽度
            ViewGroup.LayoutParams.WRAP_CONTENT,
            true
        )

        // 设置弹出窗口的背景和动画
        popupWindow?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        popupWindow?.elevation = 8f

        // 显示在按钮下方
        popupWindow?.showAsDropDown(anchorView, 0, 0, Gravity.NO_GRAVITY)

        // 设置外部点击关闭
        popupWindow?.setOutsideTouchable(true)

        // 设置关闭监听
        popupWindow?.setOnDismissListener {
            popupWindow = null
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        popupWindow?.dismiss()
        popupWindow = null
    }
}

// 下拉列表适配器
// 下拉列表适配器
class CategoryDropdownAdapter(
    private val categories: List<String>,
    private val selectedPosition: Int,
    private val onItemClick: (Int) -> Unit
) : RecyclerView.Adapter<CategoryDropdownAdapter.ViewHolder>() {

    class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val textView: TextView = view.findViewById(R.id.category_text)
        val container: ViewGroup = view.findViewById(R.id.item_container) // 确保使用正确的ID
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.posd, parent, false)
        return ViewHolder(view)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.textView.text = categories[position]

        // 设置选中状态
        if (position == selectedPosition) {
            holder.container.setBackgroundResource(R.drawable.bnfnbfgh)
        } else {
            holder.container.setBackgroundResource(android.R.color.transparent)
        }

        holder.itemView.setOnClickListener {
            onItemClick(position)
        }
    }

    override fun getItemCount(): Int = categories.size
}

// ViewPager适配器
class CategoryViewPagerAdapter(
    fragment: Fragment,
    private val categoryNames: List<String>
) : FragmentStateAdapter(fragment) {

    override fun getItemCount(): Int = categoryNames.size

    override fun createFragment(position: Int): Fragment {
        return CategoryFragment.newInstance(categoryNames[position])
    }
}

// CategoryFragment类
class CategoryFragment : Fragment() {

    private lateinit var binding: com.app.input.inputaura.databinding.ZudgBinding
    private var categoryName: String? = null

    // 懒加载标记
    private var isViewCreated = false
    private var isDataLoaded = false

    companion object {
        private const val ARG_CATEGORY_NAME = "category_name"

        @JvmStatic
        fun newInstance(categoryName: String): CategoryFragment {
            return CategoryFragment().apply {
                arguments = Bundle().apply {
                    putString(ARG_CATEGORY_NAME, categoryName)
                }
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // 在onCreate中获取参数，避免在onViewCreated中重复获取
        categoryName = arguments?.getString(ARG_CATEGORY_NAME)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = com.app.input.inputaura.databinding.ZudgBinding.inflate(inflater, container, false)
        isViewCreated = true
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        // 初始化RecyclerView配置
        setupRecyclerViewConfig()

        // 尝试加载数据
        tryLoadDataIfNeeded()
    }

    private fun setupRecyclerViewConfig() {
        // 设置网格布局管理器
        val layoutManager = GridLayoutManager(requireContext(), 2)
        binding.recyclerView.layoutManager = layoutManager

        // 启用固定大小优化
//        binding.recyclerView.setHasFixedSize(true)

        // 启用item缓存
        binding.recyclerView.setItemViewCacheSize(20)
    }

    private fun tryLoadDataIfNeeded() {
        if (isViewCreated && userVisibleHint && !isDataLoaded) {
            loadData()
        }
    }

    private fun loadData() {
        lifecycleScope.launch {
            // 在IO线程查找对应分类的数据
            val keyboardList = withContext(Dispatchers.IO) {
                InputAura.Companion.list.find { it.parentName == categoryName }?.keyboardList ?: emptyList()
            }

            // 回到主线程更新UI
            if (keyboardList.isNotEmpty()) {
                setupAdapter(keyboardList)
            } else {
                showEmptyView()
            }

            isDataLoaded = true
        }
    }

    private fun setupAdapter(keyboardList: List<Shikamaru>) {
        // 创建适配器
        val adapter = object : DubTbf(requireContext(), keyboardList) {
            // 使用自定义的适配器
        }

        binding.recyclerView.adapter = adapter

        // 添加间距装饰器
        val spacing = resources.getDimensionPixelSize(com.app.input.inputaura.R.dimen.grid_spacing)
        binding.recyclerView.addItemDecoration(
            GridSpacingItemDecoration(2, spacing, false)
        )
    }

    private fun showEmptyView() {
        // 显示空状态视图
        binding.recyclerView.visibility = View.GONE
    }

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        if (isVisibleToUser && isViewCreated && !isDataLoaded) {
            loadData()
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        // 清理资源
        binding.recyclerView.adapter = null
        isViewCreated = false
        isDataLoaded = false
    }

    // 网格间距装饰器
    class GridSpacingItemDecoration(
        private val spanCount: Int,
        private val spacing: Int,
        private val includeEdge: Boolean
    ) : androidx.recyclerview.widget.RecyclerView.ItemDecoration() {

        override fun getItemOffsets(
            outRect: android.graphics.Rect,
            view: View,
            parent: androidx.recyclerview.widget.RecyclerView,
            state: androidx.recyclerview.widget.RecyclerView.State
        ) {
            val position = parent.getChildAdapterPosition(view)
            if (position < 0) return

            val column = position % spanCount

            if (includeEdge) {
                outRect.left = spacing - column * spacing / spanCount
                outRect.right = (column + 1) * spacing / spanCount

                if (position < spanCount) {
                    outRect.top = spacing
                }
                outRect.bottom = spacing
            } else {
                outRect.left = column * spacing / spanCount
                outRect.right = spacing - (column + 1) * spacing / spanCount

                if (position >= spanCount) {
                    outRect.top = spacing
                }
            }
        }
    }
}