package com.adealink.weparty.module.account.comp

import android.text.Editable
import android.text.TextWatcher
import android.view.KeyEvent
import androidx.appcompat.widget.AppCompatEditText
import androidx.lifecycle.LifecycleOwner
import com.adealink.frame.mvvm.view.ViewComponent
import com.adealink.weparty.util.QMUIKeyboardHelper

class VerifyCodeComp(
    lifecycleOwner: LifecycleOwner,
    private val inputBoxes: List<AppCompatEditText>,
    private val onCodeCompleted: (code: String) -> Unit,
) : ViewComponent(lifecycleOwner) {
    override fun onCreate() {
        super.onCreate()
        initView()
    }

    private fun initView() {
        setupCodeInput()
        inputBoxes.firstOrNull()?.let { input ->
            QMUIKeyboardHelper.showKeyboard(input, true)
            input.requestFocus()
        }
    }

    private fun setupCodeInput() {
        for (i in inputBoxes.indices) {
            inputBoxes[i].addTextChangedListener(object : TextWatcher {
                override fun afterTextChanged(s: Editable?) {
                    if (s?.length == 1) {
                        // 移动到下一个
                        if (i < inputBoxes.size - 1) {
                            inputBoxes[i + 1].requestFocus()
                        }
                        // 如果是最后一个且都填完，触发回调
                        if (i == inputBoxes.size - 1 && inputBoxes.all { it.text?.length == 1 }) {
                            val code = inputBoxes.joinToString("") { it.text.toString() }
                            onCodeCompleted(code)
                        }
                    } else if (s?.isEmpty() == true && i > 0) {
                        // 删除时回退焦点
                        inputBoxes[i - 1].requestFocus()
                    }

                    // ✅ 新增逻辑：只要有一个被清空，就触发未完成状态
                    if (inputBoxes.any { it.text.isNullOrEmpty() }) {
                        onCodeNoneCompleted()
                    }
                }

                override fun beforeTextChanged(
                    s: CharSequence?,
                    start: Int,
                    count: Int,
                    after: Int
                ) {
                }

                override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
            })
            inputBoxes[i].setOnKeyListener { v, keyCode, event ->
                if (event.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_DEL) {
                    if (inputBoxes[i].text.toString().isEmpty()) {
                        // 如果当前输入框为空，且不是第一个输入框，则回退到上一个输入框
                        if (i > 0) {
                            inputBoxes[i - 1].requestFocus()
                        }
                    }
                    false
                } else {
                    false
                }
            }
        }
    }

    private fun clearCodeInput() {
        for (box in inputBoxes) {
            box.setText(null)
        }
        inputBoxes.firstOrNull()?.requestFocus()
    }

    fun onCodeCompleted(code: String) {
        onCodeCompleted.invoke(code)
    }

    fun onCodeNoneCompleted() {
    }
}