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 SymbolKeyboard(
    env: KeyboardEnvironment
) : BaseKeyboard(env) {

    override val rootView: View = env.layoutInflater.inflate(
        env.ctx.resources.getIdentifier("symbol_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 {
        // 按键背景图片（跟你原来 applyPerKeyBackgroundForSymbolKeyboard 一样）
        applyPerKeyBackgroundForSymbolKeyboard(rootView)

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

        setupListenersForSymbolView(rootView)
    }

    // ================== 背景（完全按你原来的 key 列表） ==================

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

        val symbolKeys = listOf(
            // 第一行
            "key_bracket_l",
            "key_bracket_r",
            "key_brace_l",
            "key_brace_r",
            "key_hash",
            "key_percent",
            "key_caret",
            "key_asterisk",
            "key_plus",
            "key_equal",

            // 第二行
            "key_underscore",
            "key_backslash",
            "key_pipe",
            "key_tilde",
            "key_lt",
            "key_gt",
            "key_euro",
            "key_pound",
            "key_money",
            "key_bullet",

            // 第三行
            "key_dot",
            "key_comma",
            "key_question",
            "key_exclam",
            "key_quote"
        )

        symbolKeys.forEach { idName ->
            applyKeyBackground(root, idName)
        }

        // 背景整体
        applyKeyBackground(root, "background")

        // 功能键
        val others = listOf(
            "key_symbols_123",
            "key_backspace",
            "key_abc",
            "key_ai",
            "key_space",
            "key_send"
        )

        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 setupListenersForSymbolView(symView: View) {
        val res = env.ctx.resources
        val pkg = env.ctx.packageName

        val pairs = listOf(
            // 第一行
            "key_bracket_l" to '[',
            "key_bracket_r" to ']',
            "key_brace_l" to '{',
            "key_brace_r" to '}',
            "key_hash" to '#',
            "key_percent" to '%',
            "key_caret" to '^',
            "key_asterisk" to '*',
            "key_plus" to '+',
            "key_equal" to '=',

            // 第二行
            "key_underscore" to '_',
            "key_backslash" to '\\',
            "key_pipe" to '|',
            "key_tilde" to '~',
            "key_lt" to '<',
            "key_gt" to '>',
            "key_euro" to '€',
            "key_pound" to '£',
            "key_money" to '¥',
            "key_bullet" to '•',

            // 第三行
            "key_dot" to '.',
            "key_comma" to ',',
            "key_question" to '?',
            "key_exclam" to '!',
            "key_quote" to '\''
        )

        pairs.forEach { (name, ch) ->
            val id = res.getIdentifier(name, "id", pkg)
            symView.findViewById<View?>(id)?.let { v ->
                attachKeyTouch(v) { ch }
            }
        }

        // 切换回数字
        symView.findViewById<View?>(res.getIdentifier("key_symbols_123", "id", pkg))
            ?.setOnClickListener {
                vibrateKey()
                env.showNumberKeyboard()
            }

        // 切回字母
        symView.findViewById<View?>(res.getIdentifier("key_abc", "id", pkg))
            ?.setOnClickListener {
                vibrateKey()
                env.showMainKeyboard()
            }

        // 空格
        symView.findViewById<View?>(res.getIdentifier("key_space", "id", pkg))
            ?.setOnClickListener {
                vibrateKey()
                env.commitKey(' ')
            }

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

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

        // 跳 AI 键盘
        symView.findViewById<View?>(res.getIdentifier("key_ai", "id", pkg))
            ?.setOnClickListener {
                vibrateKey()
                env.showAiKeyboard()
            }
    }

    // ================== 触摸 + 预览 ==================

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