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.Rect
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.app.intelligent.board.AppContextHelper
import com.app.intelligent.board.uimodel.KeyboardItemInfo
import com.app.intelligent.board.databinding.FragmentCategoryItemContentBinding
import com.app.intelligent.board.uiadapter.HomeItemSubAdapter

// 确保项目中只有这一个CategoryContentFragment类
class CategoryItemContentFragment : Fragment() {
    private lateinit var binding: FragmentCategoryItemContentBinding
    private lateinit var categoryName: String
    private lateinit var keyboardAdapter: HomeItemSubAdapter
    private val allKeyboards = mutableListOf<KeyboardItemInfo>()

    companion object {
        private const val KEY_CATEGORY_NAME = "category_name"

        fun newInstance(categoryName: String): CategoryItemContentFragment {
            val fragment = CategoryItemContentFragment()
            val args = Bundle().apply {
                putString(KEY_CATEGORY_NAME, categoryName)
            }
            fragment.arguments = args
            return fragment
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        categoryName = arguments?.getString(KEY_CATEGORY_NAME).orEmpty()
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentCategoryItemContentBinding.inflate(inflater, container, false)
        initRecyclerView()
        loadAllKeyboards()
        return binding.root
    }

    private fun initRecyclerView() {
        keyboardAdapter = HomeItemSubAdapter(requireContext(), allKeyboards)
        binding.categoryRecycler.apply {
            adapter = keyboardAdapter
            // 保留1列网格布局（和原逻辑一致）
            layoutManager = GridLayoutManager(requireContext(), 1)
            // 移除原有ListDecoration，替换为自定义间距
            if (itemDecorationCount > 0) {
                removeItemDecorationAt(0)
            }
            // 核心：添加自定义ItemDecoration，强制设置上下间距
            addItemDecoration(CustomKeyboardDecoration())
            setHasFixedSize(true)
            isNestedScrollingEnabled = true
        }
    }

    // 自定义ItemDecoration：控制键盘之间的上下间距
    inner class CustomKeyboardDecoration : RecyclerView.ItemDecoration() {
        override fun getItemOffsets(
            outRect: Rect,
            view: View,
            parent: RecyclerView,
            state: RecyclerView.State
        ) {
            super.getItemOffsets(outRect, view, parent, state)
            // 上下间距设为4dp
            val verticalMargin = dp2px(4)
            // 左右间距保留6dp
            val horizontalMargin = dp2px(6)

            outRect.top = verticalMargin
            outRect.bottom = verticalMargin
            outRect.left = horizontalMargin
            outRect.right = horizontalMargin
        }
    }

    // 工具方法：dp转px（适配不同屏幕）
    private fun dp2px(dp: Int): Int {
        return (dp * resources.displayMetrics.density).toInt()
    }

    private fun loadAllKeyboards() {
        allKeyboards.clear()
        AppContextHelper.list.forEach { beanWrapper ->
            if (beanWrapper.parentName == categoryName) {
                @Suppress("UNCHECKED_CAST")
                val keyboardList = beanWrapper.getKeyboardList() as? List<KeyboardItemInfo>
                keyboardList?.let { allKeyboards.addAll(it) }
            }
        }
        keyboardAdapter.notifyDataSetChanged()
        println("分类[$categoryName]加载键盘数：${allKeyboards.size}")
    }

    fun refreshCategoryData(newCategoryName: String) {
        if (newCategoryName.isNotEmpty()) {
            categoryName = newCategoryName
            loadAllKeyboards()
        }
    }
}