package com.example.myapplication.keyboard

import android.content.Context
import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.graphics.drawable.GradientDrawable
import android.os.Build
import android.os.VibrationEffect
import android.os.Vibrator
import android.util.TypedValue
import android.view.Gravity
import android.view.MotionEvent
import android.view.View
import android.widget.PopupWindow
import android.widget.TextView
import com.example.myapplication.theme.ThemeManager

class NumberKeyboard(
    env: KeyboardEnvironment
) : BaseKeyboard(env) {

    override val rootView: View = env.layoutInflater.inflate(
        env.ctx.resources.getIdentifier("number_keyboard", "layout", env.ctx.packageName),
        null
    )

    private var keyPreviewPopup: PopupWindow? = null

    init {
        applyPerKeyBackgroundForNumberKeyboard(rootView)
        applyTheme(env.currentTextColor, env.currentBorderColor, env.currentBackgroundColor)
        setupListenersForNumberView(rootView)
    }

    // -------------------- 背景 --------------------
    private fun applyPerKeyBackgroundForNumberKeyboard(root: View) {
        for (i in 0..9) applyKeyBackground(root, "key_$i")
        applyKeyBackground(root, "background")

        val symbolKeys = listOf(
            "key_comma","key_dot","key_minus","key_slash","key_colon","key_semicolon",
            "key_paren_l","key_paren_r","key_dollar","key_amp","key_at","key_question",
            "key_exclam","key_quote","key_quote_d"
        )
        symbolKeys.forEach { applyKeyBackground(root, it) }

        val others = listOf(
            "key_symbols_more","key_abc","key_ai","key_space","key_send","key_del","Key_collapse","key_emoji","key_revoke"
        )
        others.forEach { applyKeyBackground(root, it) }
    }

    private fun applyKeyBackground(root: View, viewIdName: String, drawableName: String? = null) {
        val res = env.ctx.resources
        val viewId = res.getIdentifier(viewIdName, "id", env.ctx.packageName)
        val v = root.findViewById<View?>(viewId) ?: return
        val keyName = drawableName ?: viewIdName
        val rawDrawable = ThemeManager.getDrawableForKey(env.ctx, keyName) ?: return

        if (viewIdName == "background") {
            v.background = scaleDrawableToHeight(rawDrawable, 243f)
        } else {
            v.background = rawDrawable
        }
    }

    private fun scaleDrawableToHeight(src: Drawable, targetDp: Float): Drawable {
        val res = env.ctx.resources
        val dm = res.displayMetrics
        val targetHeightPx = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, targetDp, dm).toInt()
        val bitmap = (src as? BitmapDrawable)?.bitmap ?: return src
        val ratio = targetHeightPx.toFloat() / bitmap.height
        val targetWidthPx = (bitmap.width * ratio).toInt()
        val scaled = Bitmap.createScaledBitmap(bitmap, targetWidthPx, targetHeightPx, true)
        return BitmapDrawable(res, scaled).apply { setBounds(0, 0, targetWidthPx, targetHeightPx) }
    }

    // -------------------- 实现主题刷新 --------------------
    override fun applyKeyBackgroundsForTheme() {
        // 刷新数字键
        for (i in 0..9) applyKeyBackground(rootView, "key_$i")

        // 刷新符号键
        val symbolKeys = listOf(
            "key_comma","key_dot","key_minus","key_slash","key_colon","key_semicolon",
            "key_paren_l","key_paren_r","key_dollar","key_amp","key_at","key_question",
            "key_exclam","key_quote","key_quote_d"
        )
        symbolKeys.forEach { applyKeyBackground(rootView, it) }

        // 刷新功能键和背景
        val others = listOf(
            "key_symbols_more","key_abc","key_ai","key_space","key_send","key_del","Key_collapse","background","key_emoji","key_revoke"
        )
        others.forEach { applyKeyBackground(rootView, it) }
    }

    // -------------------- 按键事件 --------------------
    private fun setupListenersForNumberView(numView: View) {
        val res = env.ctx.resources
        val pkg = env.ctx.packageName

        // 初始化时设置Revoke按钮的可见性
        updateRevokeButtonVisibility(numView, res, pkg)

        for (i in 0..9) {
            val id = res.getIdentifier("key_$i", "id", pkg)
            numView.findViewById<View?>(id)?.let { attachKeyTouch(it) { i.toString()[0] } }
        }

        val symbolMap: List<Pair<String, Char>> = listOf(
            "key_comma" to ',', "key_dot" to '.', "key_minus" to '-', "key_slash" to '/',
            "key_colon" to ':', "key_semicolon" to ';', "key_paren_l" to '(', "key_paren_r" to ')',
            "key_dollar" to '$', "key_amp" to '&', "key_at" to '@', "key_question" to '?',
            "key_exclam" to '!', "key_quote" to '\'', "key_quote_d" to '”'
        )
        symbolMap.forEach { (name, ch) ->
            val id = res.getIdentifier(name, "id", pkg)
            numView.findViewById<View?>(id)?.let { attachKeyTouch(it) { ch } }
        }

        // 功能键
        numView.findViewById<View?>(res.getIdentifier("key_symbols_more", "id", pkg))
            ?.setOnClickListener { vibrateKey(); env.showSymbolKeyboard() }

        numView.findViewById<View?>(res.getIdentifier("key_abc", "id", pkg))
            ?.setOnClickListener { vibrateKey(); env.showMainKeyboard() }

        numView.findViewById<View?>(res.getIdentifier("key_ai", "id", pkg))
            ?.setOnClickListener { vibrateKey(); env.showAiKeyboard() }

        numView.findViewById<View?>(res.getIdentifier("key_space", "id", pkg))
            ?.setOnClickListener { 
                vibrateKey(); env.commitKey(' ')
                // 输入新内容后更新按钮可见性
                updateRevokeButtonVisibility(numView, res, pkg)
            }

        numView.findViewById<View?>(res.getIdentifier("key_send", "id", pkg))
            ?.setOnClickListener { 
                vibrateKey(); env.performSendAction()
                // 发送后更新按钮可见性
                updateRevokeButtonVisibility(numView, res, pkg)
            }

        numView.findViewById<View?>(res.getIdentifier("key_del", "id", pkg))
            ?.setOnClickListener { 
                vibrateKey(); env.deleteOne()
                // 删除内容后更新按钮可见性
                updateRevokeButtonVisibility(numView, res, pkg)
            }

        numView.findViewById<View?>(res.getIdentifier("collapse_button", "id", pkg))
            ?.setOnClickListener { vibrateKey(); env.hideKeyboard() }
            
        numView.findViewById<View?>(res.getIdentifier("key_emoji", "id", pkg))
            ?.setOnClickListener { vibrateKey(); env.showEmojiKeyboard() }

        numView.findViewById<View?>(res.getIdentifier("key_revoke", "id", pkg))
            ?.setOnClickListener { 
                vibrateKey(); env.revokeLastClearedText()
                // 回填后更新按钮可见性
                updateRevokeButtonVisibility(numView, res, pkg)
            }
    }

    // 更新Revoke按钮的可见性
    private fun updateRevokeButtonVisibility(view: View, res: android.content.res.Resources, pkg: String) {
        val revokeButton = view.findViewById<View?>(res.getIdentifier("key_revoke", "id", pkg))
        revokeButton?.visibility = if (env.hasClearedText()) View.VISIBLE else View.GONE
    }
    
    // 公共方法：更新Revoke按钮的可见性（供外部调用）
    fun updateRevokeButtonVisibility() {
        val res = env.ctx.resources
        val pkg = env.ctx.packageName
        updateRevokeButtonVisibility(rootView, res, pkg)
    }

    // -------------------- 按键触摸 & 预览 --------------------
    private fun attachKeyTouch(view: View, charProvider: () -> Char) {
        view.setOnTouchListener { v, event ->
            when (event.actionMasked) {
                MotionEvent.ACTION_DOWN -> {
                    val ch = charProvider()
                    vibrateKey()
                    showKeyPreview(v, ch.toString())
                    v.isPressed = true
                    true
                }
                MotionEvent.ACTION_UP -> {
                    val ch = charProvider()
                    env.commitKey(ch)
                    keyPreviewPopup?.dismiss()
                    v.isPressed = false
                    true
                }
                MotionEvent.ACTION_CANCEL,
                MotionEvent.ACTION_OUTSIDE -> {
                    keyPreviewPopup?.dismiss()
                    v.isPressed = false
                    true
                }
                else -> false
            }
        }
    }

    private fun showKeyPreview(anchor: View, text: String) {
        keyPreviewPopup?.dismiss()
        val tv = TextView(env.ctx).apply {
            this.text = text
            textSize = 26f
            setTextColor(Color.BLACK)
            setPadding(20, 10, 20, 10)
            background = GradientDrawable().apply {
                shape = GradientDrawable.RECTANGLE
                cornerRadius = 16f
                setColor(Color.WHITE)
                setStroke(1, Color.parseColor("#33000000"))
            }
            gravity = Gravity.CENTER
        }

        val w = (anchor.width * 1.2f).toInt()
        val h = (anchor.height * 1.2f).toInt()

        keyPreviewPopup = PopupWindow(tv, w, h, false).apply { isClippingEnabled = false }
        keyPreviewPopup?.showAsDropDown(anchor, -(w - anchor.width) / 2, -(h + anchor.height * 1.1f).toInt())
    }
}
