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.R
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

    // ================= 震动相关 =================

    private val vibrator: Vibrator? =
        env.ctx.getSystemService(Context.VIBRATOR_SERVICE) as? Vibrator

        private fun vibrateKey(
            duration: Long = 20L,     // 时间：10~40 推荐
            amplitude: Int = 150      // 1~255，100~150 最舒服
        ) {
            val v = vibrator ?: return
            if (!v.hasVibrator()) return
        
            try {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    v.vibrate(
                        VibrationEffect.createOneShot(duration, amplitude)
                    )
                } else {
                    @Suppress("DEPRECATION")
                    v.vibrate(duration)
                }
            } catch (_: SecurityException) {
                // 没权限就自动静音，不崩溃
            }
        }

    init {
        applyPerKeyBackgroundForNumberKeyboard(rootView)

        // 初次创建立刻应用当前主题
        applyTheme(
            env.currentTextColor,
            env.currentBorderColor,
            env.currentBackgroundColor
        )

        setupListenersForNumberView(rootView)
    }

    // ================= 背景（完全拷贝原逻辑，只是换成 env.ctx.resources） =================

    private fun applyPerKeyBackgroundForNumberKeyboard(root: View) {
        val res = env.ctx.resources

        // 0..9
        for (i in 0..9) {
            val idName = "key_$i"
            applyKeyBackground(root, idName)
        }

        // 背景
        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 { idName ->
            applyKeyBackground(root, idName)
        }

        // 功能键
        val others = listOf(
            "key_symbols_more",
            "key_abc",
            "key_ai",
            "key_space",
            "key_send",
            "key_del"
        )
        others.forEach { idName ->
            applyKeyBackground(root, idName)
        }
    }

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

        val keyName = drawableName ?: viewIdName
        val rawDrawable = ThemeManager.getDrawableForKey(env.ctx, keyName) ?: return

        if (viewIdName == "background") {
            val scaled = scaleDrawableToHeight(rawDrawable, 243f)
            v.background = scaled
            return
        }
        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 w = bitmap.width
        val h = bitmap.height

        val ratio = targetHeightPx.toFloat() / h
        val targetWidthPx = (w * ratio).toInt()

        val scaledBitmap = Bitmap.createScaledBitmap(
            bitmap,
            targetWidthPx,
            targetHeightPx,
            true
        )
        return BitmapDrawable(res, scaledBitmap).apply {
            setBounds(0, 0, targetWidthPx, targetHeightPx)
        }
    }

    // ================= 按键事件 =================

    private fun setupListenersForNumberView(numView: View) {
        val res = env.ctx.resources
        val pkg = env.ctx.packageName

        // 0~9
        for (i in 0..9) {
            val id = res.getIdentifier("key_$i", "id", pkg)
            numView.findViewById<View?>(id)?.let { v ->
                attachKeyTouch(v) { 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 { v ->
                attachKeyTouch(v) { 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()
            }

        // 跳 AI
        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(' ')
            }

        // 发送
        numView.findViewById<View?>(res.getIdentifier("key_send", "id", pkg))
            ?.setOnClickListener {
                vibrateKey()
                env.performSendAction()
            }

        // 删除（单击；长按连删在 MyInputMethodService 里挂）
        numView.findViewById<View?>(res.getIdentifier("key_del", "id", pkg))
            ?.setOnClickListener {
                vibrateKey()
                env.deleteOne()
            }
    }

    // ================= 按键触摸 & 预览 =================

    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()
        )
    }
}
