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 MainKeyboard(
    env: KeyboardEnvironment,
    private val swipeAltMap: Map<Char, Char>,
    private val onToggleShift: () -> Boolean
) : BaseKeyboard(env) {

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

    private var isShiftOn: Boolean = false
    private var keyPreviewPopup: PopupWindow? = null

    init {
        applyPerKeyBackgroundForMainKeyboard(rootView)
        applyTheme(env.currentTextColor, env.currentBorderColor, env.currentBackgroundColor)
        setupListenersForMain(rootView)
    }

    // -------------------- 背景 --------------------
    private fun applyPerKeyBackgroundForMainKeyboard(root: View) {
        var c = 'a'
        while (c <= 'z') {
            applyKeyBackground(root, "key_$c")
            c++
        }

        applyKeyBackground(root, "background")

        val others = listOf(
            "key_space", "key_send", "key_del", "key_up",
            "key_123", "key_ai", "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() {
        // 刷新字母背景
        var c = 'a'
        while (c <= 'z') {
            val drawableName = if (isShiftOn) "key_${c}_up" else "key_$c"
            applyKeyBackground(rootView, "key_$c", drawableName)
            c++
        }
        // 刷新 Shift 键
        val upDrawableName = if (isShiftOn) "key_up_upper" else "key_up"
        applyKeyBackground(rootView, "key_up", upDrawableName)

        // 刷新其他功能键
        val others = listOf("key_space", "key_send", "key_del", "key_123", "key_ai","key_emoji", "Key_collapse", "background","key_revoke")
        others.forEach { applyKeyBackground(rootView, it) }
    }

    // -------------------- 事件绑定 --------------------
    private fun setupListenersForMain(view: View) {
        val res = env.ctx.resources
        val pkg = env.ctx.packageName

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

        var c = 'a'
        while (c <= 'z') {
            val tv = view.findViewById<TextView?>(res.getIdentifier("key_$c", "id", pkg))
            if (tv != null) {
                val baseChar = c
                val altChar = swipeAltMap[baseChar]
                attachKeyTouchWithSwipe(tv, { baseChar }, altChar?.let { { it } })
            }
            c++
        }

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

        view.findViewById<View?>(res.getIdentifier("key_up", "id", pkg))?.setOnClickListener {
            vibrateKey()
            isShiftOn = onToggleShift()
            it.isActivated = isShiftOn
            applyKeyBackgroundsForTheme() // 立即刷新主题背景
        }

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

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

        view.findViewById<View?>(res.getIdentifier("key_123", "id", pkg))?.setOnClickListener {
            vibrateKey(); env.showNumberKeyboard()
        }

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

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

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

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

    // 更新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 attachKeyTouchWithSwipe(
        view: View,
        normalCharProvider: () -> Char,
        altCharProvider: (() -> Char)?
    ) {
        val swipeThreshold = 20.dpToPx().toFloat()
        var downY = 0f
        var isAlt = false
        var currentChar: Char = '\u0000'

        view.setOnTouchListener { v, event ->
            when (event.actionMasked) {
                MotionEvent.ACTION_DOWN -> {
                    downY = event.rawY; isAlt = false
                    currentChar = normalCharProvider()
                    vibrateKey()
                    showKeyPreview(v, currentChar.toString())
                    v.isPressed = true
                    true
                }
                MotionEvent.ACTION_MOVE -> {
                    if (altCharProvider != null) {
                        val dy = event.rawY - downY
                        val shouldAlt = dy < -swipeThreshold
                        if (shouldAlt != isAlt) {
                            isAlt = shouldAlt
                            currentChar = if (isAlt) altCharProvider() else normalCharProvider()
                            showKeyPreview(v, currentChar.toString())
                        }
                    }
                    true
                }
                MotionEvent.ACTION_UP -> {
                    env.commitKey(currentChar)
                    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())
    }
}
