package com.example.myapplication.keyboard

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.myapplication.R

class InfiniteFlatPagerAdapter(
    private var spanCount: Int,
    private val onItemClick: (String) -> Unit
) : RecyclerView.Adapter<InfiniteFlatPagerAdapter.PageVH>() {

    private var flatPages: List<FlatPage> = emptyList()
    private var basePosition: Int = 0
    private var itemLayoutRes: Int = R.layout.item_emoji

    fun submit(pages: List<FlatPage>, newSpan: Int, newItemLayoutRes: Int) {
        flatPages = pages
        spanCount = newSpan
        itemLayoutRes = newItemLayoutRes
        basePosition = computeBasePosition()
        notifyDataSetChanged()
    }

    fun getBasePosition(): Int = basePosition

    fun realCount(): Int = flatPages.size

    fun getRealIndex(adapterPosition: Int): Int {
        val n = flatPages.size
        if (n == 0) return 0
        val x = adapterPosition - basePosition
        val m = x % n
        return if (m >= 0) m else (m + n)
    }

    fun getPageByAdapterPos(adapterPosition: Int): FlatPage? {
        if (flatPages.isEmpty()) return null
        return flatPages[getRealIndex(adapterPosition)]
    }

    override fun getItemCount(): Int {
        return if (flatPages.isEmpty()) 0 else Int.MAX_VALUE
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PageVH {
        val v = LayoutInflater.from(parent.context).inflate(R.layout.pager_page_grid, parent, false)
        return PageVH(v, spanCount, itemLayoutRes, onItemClick)
    }

    override fun onBindViewHolder(holder: PageVH, position: Int) {
        // 每次 bind 都把“当前 adapter 的配置”同步进去，避免复用交叉
        holder.updateConfig(spanCount, itemLayoutRes, onItemClick)
    
        val page = getPageByAdapterPos(position) ?: return
        holder.bind(page.items)
    }

    private fun computeBasePosition(): Int {
        val n = flatPages.size
        if (n == 0) return 0
        val mid = Int.MAX_VALUE / 2
        // 对齐到 realIndex=0
        return mid - (mid % n)
    }

    class PageVH(
        itemView: View,
        spanCount: Int,
        itemLayoutRes: Int,
        onItemClick: (String) -> Unit
    ) : RecyclerView.ViewHolder(itemView) {
    
        private val grid: RecyclerView = itemView.findViewById(R.id.page_grid)
    
        private var curSpan = spanCount
        private var curItemLayoutRes = itemLayoutRes
    
        private var adapter = SimpleStringGridAdapter(curItemLayoutRes, onItemClick)
    
        init {
            grid.layoutManager = GridLayoutManager(itemView.context, curSpan)
            grid.adapter = adapter
        }
    
        fun updateConfig(spanCount: Int, itemLayoutRes: Int, onItemClick: (String) -> Unit) {
            // 1) 更新 span（layoutManager 存在则改 spanCount）
            val lm = (grid.layoutManager as? GridLayoutManager)
            if (lm != null && curSpan != spanCount) {
                lm.spanCount = spanCount
                curSpan = spanCount
            }
    
            // 2) 更新 item 布局（需要换 adapter 或让 adapter 支持 setLayoutRes）
            if (curItemLayoutRes != itemLayoutRes) {
                curItemLayoutRes = itemLayoutRes
                adapter = SimpleStringGridAdapter(curItemLayoutRes, onItemClick)
                grid.adapter = adapter
            }
        }
    
        fun bind(items: List<String>) {
            adapter.submit(items)
        }
    }
    
}
