package com.example.myapplication.keyboard

import android.content.Intent
import android.content.res.ColorStateList
import android.graphics.Bitmap
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.util.TypedValue
import android.view.Gravity
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import com.example.myapplication.MainActivity
import com.example.myapplication.theme.ThemeManager

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

    override val rootView: View = run {
        val res = env.ctx.resources
        val layoutId = res.getIdentifier("ai_keyboard", "layout", env.ctx.packageName)
        if (layoutId != 0) {
            env.layoutInflater.inflate(layoutId, null) as View
        } else {
            // 如果找不到布局，创建一个默认的View
            LinearLayout(env.ctx).apply {
                orientation = LinearLayout.VERTICAL
                gravity = Gravity.CENTER
                addView(TextView(env.ctx).apply {
                    text = "AI Keyboard"
                })
            }
        }
    }

    init {
        applyKeyBackground(rootView, "background")
        applyTheme(
            env.currentTextColor,
            env.currentBorderColor,
            env.currentBackgroundColor
        )
        setupListeners()
    }
    
    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 scaled = Bitmap.createScaledBitmap(bitmap, targetWidthPx, targetHeightPx, true)
        return BitmapDrawable(res, scaled).apply {
            setBounds(0, 0, targetWidthPx, targetHeightPx)
        }
    }


    private fun setupListeners() {
        val res = env.ctx.resources
        val pkg = env.ctx.packageName

        // 如果 ai_keyboard.xml 里有 “返回主键盘” 的按钮，比如 key_abc，就绑定一下
        val backId = res.getIdentifier("key_abc", "id", pkg)
        if (backId != 0) {
            rootView.findViewById<ImageView?>(backId)?.setOnClickListener {
                env.showMainKeyboard()
            }
        }

        // 绑定 VIP 按钮点击事件，跳转到充值页面
        val vipButtonId = res.getIdentifier("key_vip", "id", pkg)
        if (vipButtonId != 0) {
            rootView.findViewById<ImageView?>(vipButtonId)?.setOnClickListener {
                navigateToRechargeFragment()
            }
        }
    }

    private fun navigateToRechargeFragment() {
        try {
            val intent = Intent(env.ctx, MainActivity::class.java).apply {
                addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
                putExtra("navigate_to", "recharge_fragment")
            }
            env.ctx.startActivity(intent)
        } catch (e: Exception) {
            // 如果启动失败，记录错误日志
            android.util.Log.e("AiKeyboard", "Failed to navigate to recharge fragment", e)
        }
    }

    override fun applyTheme(
        textColor: ColorStateList,
        borderColor: ColorStateList,
        backgroundColor: ColorStateList
    ) {
       
    }
}
