package com.atmob.keyboard_android.keyboard

import android.annotation.SuppressLint
import android.inputmethodservice.InputMethodService
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.Button
import android.widget.EditText
import android.widget.GridLayout
import android.widget.Toast
import com.atmob.keyboard_android.R
import com.atmob.keyboard_android.util.InputMethodUtil
import com.atmob.keyboard_android.util.KeyboardHolder
import com.atmob.keyboard_android.util.LogUtil
import io.flutter.embedding.engine.FlutterEngineCache
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel

/**
 * 自定义键盘的输入法服务
 */
class CustomKeyboardService : InputMethodService() {
    /**
     * 用于与 Flutter 端通信的 MethodChannel
     */
    private lateinit var mMethodChannel: MethodChannel

    /**
     * 保存键盘视图
     */
    private var vKeyboardView: View? = null

    /**
     * 存储按键映射
     */
    private var mKeyMappings: List<Pair<String, String>> = listOf()

    override fun onCreate() {
        super.onCreate()
        LogUtil.d("输入法服务已启动！")

        val flutterEngine = FlutterEngineCache.getInstance().get("my_engine_id")
        if (flutterEngine != null) {
            mMethodChannel =
                MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "keyboard_android")
            LogUtil.d("MethodChannel 初始化成功")

            // 设置 MethodChannel 的回调
            mMethodChannel.setMethodCallHandler { call: MethodCall, result: MethodChannel.Result ->
                when (call.method) {
                    "inputText" -> {
                        val text = call.argument<String>("text")
                        if (text != null) {
                            InputMethodUtil.inputText(this.currentInputConnection, text)
                        }
                    }

                    else -> {
                        result.notImplemented()
                    }
                }
            }
        } else {
            LogUtil.e("FlutterEngine 未找到，MethodChannel 无法初始化")
        }
    }

    override fun onCreateInputView(): View {
        LogUtil.d("onCreateInputView！")
        val keyboardView = layoutInflater.inflate(R.layout.keyboard_layout, null)
        vKeyboardView = keyboardView
        KeyboardHolder.attachKeyboardRootView(keyboardView)

        // 获取按键映射
        fetchKeyMappings()

        return keyboardView
    }

    override fun onDestroy() {
        super.onDestroy()
        KeyboardHolder.detachKeyboardRootView()
    }

    override fun onStartInputView(info: EditorInfo?, restarting: Boolean) {
        super.onStartInputView(info, restarting)
        LogUtil.d("onStartInputView: 重新加载键盘数据")
        // 重新获取按键映射
        fetchKeyMappings()
    }

    /**
     * 通过 KeyboardAndroidPlugin 获取按键映射
     */
    private fun fetchKeyMappings() {
        // 通过 methodChannel 获取按键映射
        mMethodChannel.invokeMethod("getKeyMappings", null, object : MethodChannel.Result {
            override fun success(result: Any?) {
                // 如果获取成功，处理键映射
                if (result is List<*>) {
                    mKeyMappings = result.filterIsInstance<Map<String, String>>().map {
                        it["label"]!! to it["method"]!!
                    }
                    LogUtil.d("按键映射获取成功: $mKeyMappings")
                    setupKeyboardButtons(vKeyboardView!!)
                }
            }

            override fun error(errorCode: String, errorMessage: String?, errorDetails: Any?) {
                LogUtil.d("获取按键映射失败: $errorMessage")
            }

            override fun notImplemented() {
                LogUtil.d("Flutter 端未实现 getKeyMappings 方法")
            }
        })
    }

    /**
     * 设置键盘按钮
     *
     * @param keyboardView 键盘视图
     */
    @SuppressLint("ClickableViewAccessibility")
    private fun setupKeyboardButtons(keyboardView: View) {
        LogUtil.d("当前键映射: $mKeyMappings")
        val editText = keyboardView.findViewById<EditText>(R.id.keyboard_input)
        val btnPaste = keyboardView.findViewById<Button>(R.id.btn_paste)
        val btnDelete = keyboardView.findViewById<Button>(R.id.btn_delete)
        val btnClear = keyboardView.findViewById<Button>(R.id.btn_clear)
        val btnSend = keyboardView.findViewById<Button>(R.id.btn_send)
        val numberPad = keyboardView.findViewById<GridLayout>(R.id.number_pad)

        // 禁止触摸输入
        editText.setOnTouchListener { _, _ ->
            true
        }
        // 清空，避免重复创建
        numberPad.removeAllViews()

        LogUtil.d("setupKeyboardButtons: 添加 ${mKeyMappings.size} 个按钮")

        mKeyMappings.forEach { (label, methodName) ->
            val button = Button(this).apply {
                text = label
                layoutParams = GridLayout.LayoutParams()
                // 每次点击时，都动态获取数据
                setOnClickListener {
                    sendDynamicTextRequest(methodName, editText.text.toString())
                }
            }
            numberPad.addView(button)
        }

        btnPaste.setOnClickListener {
            InputMethodUtil.pasteInput(editText, fail = {
                Toast.makeText(this, "剪贴板为空", Toast.LENGTH_SHORT).show()
            })
        }

        btnDelete.setOnClickListener {
            InputMethodUtil.deleteInput(currentInputConnection)
        }

        btnClear.setOnClickListener {
            InputMethodUtil.clearInput(currentInputConnection)
        }

        btnSend.setOnClickListener {
            InputMethodUtil.clickSendBtn(currentInputConnection)
        }
    }

    /**
     * 动态调用 Flutter 获取文本
     *
     * @param methodName 方法名
     * @param currentContent 当前输入连接
     */
    private fun sendDynamicTextRequest(methodName: String, currentContent: String) {
        mMethodChannel.invokeMethod(
            "sendDynamicTextRequest",
            mapOf("method" to methodName, "currentContent" to currentContent),
            object : MethodChannel.Result {
                override fun success(result: Any?) {
                    LogUtil.d("sendDynamicTextRequest 请求已发送")
                }

                override fun error(errorCode: String, errorMessage: String?, errorDetails: Any?) {
                    LogUtil.d("获取动态文本失败: $errorMessage")
                }

                override fun notImplemented() {
                    LogUtil.d("Flutter 端未实现 sendDynamicTextRequest 方法")
                }
            })
    }
}