package com.example.myapplication.keyboard

import android.content.res.ColorStateList
import android.view.LayoutInflater
import android.view.View
import android.widget.HorizontalScrollView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.viewpager2.widget.ViewPager2
import com.example.myapplication.R

class EmojiKeyboard(private val env: KeyboardEnvironment) {

    val rootView: View = LayoutInflater.from(env.ctx).inflate(R.layout.keyboard_emoji, null, false)

    private val tabEmoji: TextView = rootView.findViewById(R.id.tab_emoji)
    private val tabKaomoji: TextView = rootView.findViewById(R.id.tab_kaomoji)

    private val subBar: LinearLayout = rootView.findViewById(R.id.subcategory_bar)
    private val subcategoryScrollView: HorizontalScrollView = rootView.findViewById<HorizontalScrollView>(R.id.subcategory_scroll)
    private val pager: ViewPager2 = rootView.findViewById(R.id.pager)
    // private val indicatorLayout: LinearLayout = rootView.findViewById(R.id.page_indicator)
    // private val indicator = PageIndicator(indicatorLayout)

    private val backspace: View = rootView.findViewById(R.id.key_del)
    private val toABC: View = rootView.findViewById(R.id.key_abc)

    private enum class Mode { EMOJI, KAOMOJI }
    private var mode: Mode = Mode.EMOJI
    private val recentStore = RecentStore(env.ctx)

    // 你按键格子大小决定
    private val emojiSpan = 6
    private val emojiPageSize = 6 * 4

    private val kaomojiSpan = 2
    private val kaomojiPageSize = 2 * 4

    private val pagerAdapter = InfiniteFlatPagerAdapter(
        spanCount = emojiSpan,
        onItemClick = { s ->
            val isEmojiNow = (mode == Mode.EMOJI)
    
            env.getInputConnection()?.commitText(s, 1)
            env.playKeyClick()
    
            // ✅ 写入最近
            recentStore.push(s, isEmojiNow)
    
            // ✅ 立刻刷新“最近分类”的数据并更新 pager（无论当前在哪个分类）
            refreshRecentsAndRebuildPages(isEmojiNow)
        }
    )

    private fun refreshRecentsAndRebuildPages(isEmojiNow: Boolean) {
        // 1) 用最新 recents 覆盖 categories 的“最近”项
        val newRecents = recentStore.get(isEmoji = isEmojiNow)
    
        if (categories.isNotEmpty()) {
            val first = categories[0]
            // 假设 categories[0] 就是“最近”（你的数据就是这么组织的）
            categories = categories.toMutableList().apply {
                this[0] = first.copy(items = newRecents)
            }
        }
    
        // 2) 用当前点击类型对应的 pageSize 重建 flatPages
        val (_, pageSize) = if (isEmojiNow)
            emojiSpan to emojiPageSize
        else
            kaomojiSpan to kaomojiPageSize
    
        flatPages = FlatPageBuilder.buildFlatPages(categories, pageSize)
    
        // 3) 记录当前页的 realIndex，避免刷新后把用户甩回“最近”
        val oldAdapterPos = pager.currentItem
        val oldRealIndex = pagerAdapter.getRealIndex(oldAdapterPos)
    
        // 4) 重新提交 pages（span 不变）
        val span = if (isEmojiNow) emojiSpan else kaomojiSpan
        val itemLayoutRes = if (isEmojiNow) {
            R.layout.item_emoji
        } else {
            R.layout.item_kaomoji
        }
        pagerAdapter.submit(flatPages, span, itemLayoutRes)
    
        // 5) 回到原来的 realIndex（对应同一位置）
        val base = pagerAdapter.getBasePosition()
        pager.setCurrentItem(base + oldRealIndex, false)
        pager.post { onForceSyncUI(base + oldRealIndex) }
    }
    

    // 当前模式下的数据
    private var categories: List<SubCategory> = emptyList()
    private var flatPages: List<FlatPage> = emptyList()

    init {
        pager.adapter = pagerAdapter

        toABC.setOnClickListener { env.showMainKeyboard() }
        backspace.setOnClickListener { env.deleteOne() }

        tabEmoji.setOnClickListener { switchMode(Mode.EMOJI) }
        tabKaomoji.setOnClickListener { switchMode(Mode.KAOMOJI) }

        pager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                val page = pagerAdapter.getPageByAdapterPos(position) ?: return
                // 1) 高亮子分类
                highlightSubTabs(page.catIndex)

                // // 2) dots：该分类有多少页，当前第几页
                // indicator.setPageCount(page.catPageCount)
                // indicator.setSelected(page.pageInCat)
            }
        })

        // 默认 Emoji
        switchMode(Mode.EMOJI)
    }

    private fun switchMode(m: Mode) {
        mode = m
        tabEmoji.isSelected = (mode == Mode.EMOJI)
        tabKaomoji.isSelected = (mode == Mode.KAOMOJI)
        rebuildForMode()
    }

    private fun rebuildForMode() {
        val recents = recentStore.get(isEmoji = (mode == Mode.EMOJI))

        categories = if (mode == Mode.EMOJI)
            EmojiKaomojiData.emojiCategories(recents)
        else
            EmojiKaomojiData.kaomojiCategories(recents)

        val (span, pageSize) = if (mode == Mode.EMOJI)
            emojiSpan to emojiPageSize
        else
            kaomojiSpan to kaomojiPageSize

        flatPages = FlatPageBuilder.buildFlatPages(categories, pageSize)

        // 重建子分类栏
        rebuildSubCategoryBar()

        // 更新 pager 数据（无限循环）
        val itemLayoutRes = if (mode == Mode.EMOJI) {
            R.layout.item_emoji
        } else {
            R.layout.item_kaomoji
        }
        pagerAdapter.submit(flatPages, span, itemLayoutRes)

        // 跳到 base（对齐 realIndex=0）
        val base = pagerAdapter.getBasePosition()
        if (pagerAdapter.itemCount > 0) {
            pager.setCurrentItem(base, false)
            // 主动刷新一次 UI（某些机型第一次不触发 onPageSelected）
            pager.post { onForceSyncUI(base) }
        } else {
            // indicator.clear()
        }
    }

    private fun onForceSyncUI(adapterPos: Int) {
        val page = pagerAdapter.getPageByAdapterPos(adapterPos) ?: return
        highlightSubTabs(page.catIndex)
        // indicator.setPageCount(page.catPageCount)
        // indicator.setSelected(page.pageInCat)
    }

    private fun rebuildSubCategoryBar() {
        subBar.removeAllViews()
    
        categories.forEachIndexed { idx, cat ->
            val tv = LayoutInflater.from(env.ctx)
                .inflate(R.layout.item_emoji_tab, subBar, false) as TextView
    
            val tabText = if (mode == Mode.EMOJI) {
                when (cat.label) {
                    "最近" -> "🕘" 
                    else -> cat.items.firstOrNull().orEmpty().ifBlank { cat.label }
                }
            } else {
                when (cat.label) {
                    "常用" -> "🕘"
                    else -> cat.items.firstOrNull().orEmpty().ifBlank { cat.label }
                }
                // cat.label
            }
    
            tv.text = tabText
            tv.isSelected = (idx == 0)
            tv.textSize = if (mode == Mode.EMOJI) 18f else 14f
    
            tv.setOnClickListener { jumpToCategory(idx) }
            subBar.addView(tv)
        }
    }
    private fun highlightSubTabs(catIndex: Int) {
        for (i in 0 until subBar.childCount) {
            (subBar.getChildAt(i) as? TextView)?.isSelected = (i == catIndex)
        }
        
        // 自动滚动到当前选中的子分类标签
        if (catIndex < subBar.childCount) {
            val selectedView = subBar.getChildAt(catIndex)
            subcategoryScrollView.post {
                val scrollTo = selectedView.left - (subcategoryScrollView.width - selectedView.width) / 2
                subcategoryScrollView.smoothScrollTo(scrollTo, 0)
            }
        }
    }

    /**
     * 跳到某个子分类的“第 1 页”
     * 本质：找到 flatPages 里该分类的第一个 page 的 realIndex，然后 setCurrentItem(base + realIndex)
     */
    private fun jumpToCategory(catIndex: Int) {
        if (flatPages.isEmpty()) return
        val realIndex = flatPages.indexOfFirst { it.catIndex == catIndex && it.pageInCat == 0 }
            .takeIf { it >= 0 } ?: return

        val base = pagerAdapter.getBasePosition()
        pager.setCurrentItem(base + realIndex, false)
        pager.post { onForceSyncUI(base + realIndex) }
    }

    fun applyTheme(text: ColorStateList, border: ColorStateList, bg: ColorStateList) {
        tabEmoji.setTextColor(text)
        tabKaomoji.setTextColor(text)
        for (i in 0 until subBar.childCount) {
            (subBar.getChildAt(i) as? TextView)?.setTextColor(text)
        }
        // dot 如果要跟主题走：可以把 item_dot 改成 View，然后 setBackgroundTintList
    }
}
