package com.hikoncont.view

import android.content.Context
import android.graphics.Color
import android.util.AttributeSet
import android.view.Gravity
import android.view.View
import android.widget.Button
import android.widget.LinearLayout
import android.widget.TextView

/**
 * 4位数字密码输入视图
 * 参考PIN页面的UI设计
 */
class FourDigitPinView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {

    companion object {
        private const val TAG = "FourDigitPinView"
        private const val MAX_PIN_LENGTH = 4
    }

    // 颜色定义
    private val textColor = Color.WHITE
    private val pinDisplayColor = Color.WHITE
    private val inputColor = Color.parseColor("#FFFFFF")

    // UI组件
    private lateinit var dotsLayout: LinearLayout
    private lateinit var instructionView: TextView
    private var switchButton: Button? = null
    private var currentInput: String = ""

    // 回调接口
    private var onPinCompleteListener: OnPinCompleteListener? = null
    private var onSwitchClick: ((String) -> Unit)? = null

    init {
        setupView()
    }

    /**
     * 设置视图
     */
    private fun setupView() {
        orientation = VERTICAL
        gravity = Gravity.CENTER_HORIZONTAL
        setPadding(40, dp(12), 40, dp(12))
        setBackgroundColor(Color.TRANSPARENT)


        addTopSpacer(0.2f)

        // 说明文字
        createInstructionView()

        // 创建PIN显示（4位小圆点）
        createDotsDisplay()

        // 创建自定义数字键盘
        createCustomKeypad()

        // 内置"其他密码类型"按钮
        createSwitchButton()
    }

    private fun addTopSpacer(weight: Float) {
        val spacer = View(context)
        val lp = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0, weight)
        addView(spacer, 0, lp)
    }

    /**
     * 创建说明文字
     */
    private fun createInstructionView() {
        instructionView = TextView(context).apply {
            text = "请输入4位数字密码"
            textSize = 18f
            setTextColor(textColor)
            gravity = Gravity.CENTER
            setPadding(0, 0, 0, dp(20))
        }
        addView(instructionView)
    }

    /**
     * 创建PIN点显示
     */
    private fun createDotsDisplay() {
        dotsLayout = LinearLayout(context).apply {
            orientation = HORIZONTAL
            gravity = Gravity.CENTER
        }

        // 创建4个点
        for (i in 0 until MAX_PIN_LENGTH) {
            val dot = View(context).apply {
                layoutParams = LinearLayout.LayoutParams(dp(16), dp(16)).apply {
                    setMargins(dp(8), 20, dp(8), 20)
                }
                background = createDotBackground(false)
            }
            dotsLayout.addView(dot)
        }

        addView(dotsLayout)
    }

    /**
     * 创建自定义数字键盘
     */
    private fun createCustomKeypad() {
        val rows = arrayOf(
            arrayOf("1", "2", "3"),
            arrayOf("4", "5", "6"),
            arrayOf("7", "8", "9"),
            arrayOf("", "0", "⌫")
        )

        rows.forEachIndexed { rowIndex, row ->
            val rowLayout = LinearLayout(context).apply {
                orientation = HORIZONTAL
                gravity = Gravity.CENTER
            }

            row.forEachIndexed { colIndex, label ->
                if (label.isEmpty()) {
                    val spacer = View(context)
                    val lp = LinearLayout.LayoutParams(dp(64), dp(64)).apply { 
                        setMargins(dp(12), dp(12), dp(12), dp(12)) 
                    }
                    rowLayout.addView(spacer, lp)
                } else {
                    val button = createKeyButton(label)
                    val lp = LinearLayout.LayoutParams(dp(64), dp(64)).apply { 
                        setMargins(dp(12), dp(12), dp(12), dp(12)) 
                    }
                    rowLayout.addView(button, lp)
                }
            }

            val rowLp = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
            rowLp.setMargins(0, dp(2), 0, dp(2))
            addView(rowLayout, rowLp)
        }
    }

    private fun createKeyButton(label: String): Button {
        val btn = Button(context)
        btn.text = label
        btn.textSize = 20f
        btn.setTextColor(Color.WHITE)
        btn.background = createCircleButtonBackground()
        btn.isClickable = true
        btn.isFocusable = true
        btn.stateListAnimator = null
        btn.setOnTouchListener { v, event ->
            when (event.action) {
                android.view.MotionEvent.ACTION_DOWN -> v.animate().scaleX(0.95f).scaleY(0.95f).setDuration(70).start()
                android.view.MotionEvent.ACTION_UP, android.view.MotionEvent.ACTION_CANCEL -> v.animate().scaleX(1f).scaleY(1f).setDuration(70).start()
            }
            false
        }
        btn.isAllCaps = false
        btn.setOnClickListener {
            if (label == "⌫") {
                if (currentInput.isNotEmpty()) {
                    currentInput = currentInput.dropLast(1)
                    updatePinDisplay(currentInput)
                }
            } else {
                if (currentInput.length < MAX_PIN_LENGTH) {
                    currentInput += label
                    updatePinDisplay(currentInput)
                    if (currentInput.length == MAX_PIN_LENGTH) {
                        onPinCompleteListener?.onPinComplete(currentInput)
                    }
                }
            }
        }
        return btn
    }

    /**
     * 更新PIN显示
     */
    private fun updatePinDisplay(input: String) {
        for (i in 0 until MAX_PIN_LENGTH) {
            val v = dotsLayout.getChildAt(i)
            if (v is View) v.background = createDotBackground(i < input.length)
        }
    }

    private fun createCircleButtonBackground(): android.graphics.drawable.Drawable {
        val shape = android.graphics.drawable.GradientDrawable()
        shape.shape = android.graphics.drawable.GradientDrawable.OVAL
        shape.setColor(Color.argb(80, 255, 255, 255)) // 更透明的白色 (约30%透明度)
        shape.setStroke(1, Color.argb(120, 255, 255, 255)) // 更透明的白色边框 (约47%透明度)
        return shape
    }

    private fun createDotBackground(filled: Boolean): android.graphics.drawable.Drawable {
        val shape = android.graphics.drawable.GradientDrawable()
        shape.shape = android.graphics.drawable.GradientDrawable.OVAL
        if (filled) {
            shape.setColor(Color.parseColor("#9E9E9E"))
        } else {
            shape.setColor(Color.parseColor("#E0E0E0"))
        }
        return shape
    }

    private fun dp(value: Int): Int = (resources.displayMetrics.density * value).toInt()

    /** 对外：设置说明文字 */
    fun setInstructionText(text: String) {
        if (::instructionView.isInitialized) instructionView.text = text
    }

    /** 对外：设置说明文字颜色 */
    fun setInstructionTextColor(color: Int) {
        if (::instructionView.isInitialized) instructionView.setTextColor(color)
    }

    /** 对外：设置键盘按钮文字颜色 */
    fun setKeypadTextColor(color: Int) {
        try {
            updateButtonTextColorRecursively(this, color)
        } catch (_: Exception) {}
    }

    private fun updateButtonTextColorRecursively(view: android.view.View, color: Int) {
        if (view is android.widget.Button) {
            view.setTextColor(color)
        }
        if (view is android.view.ViewGroup) {
            for (i in 0 until view.childCount) {
                updateButtonTextColorRecursively(view.getChildAt(i), color)
            }
        }
    }

    /** 对外：设置切换点击回调 */
    fun setOnSwitchClickListener(listener: ((String) -> Unit)?) {
        onSwitchClick = listener
    }
    
    /**
     * 设置PIN完成监听器
     */
    fun setOnPinCompleteListener(listener: OnPinCompleteListener?) {
        onPinCompleteListener = listener
    }

    /**
     * 清除PIN输入
     */
    fun clearPin() {
        currentInput = ""
        updatePinDisplay("")
    }

    /**
     * 获取当前输入
     */
    fun getCurrentInput(): String {
        return currentInput
    }

    /**
     * PIN完成监听器接口
     */
    interface OnPinCompleteListener {
        fun onPinComplete(pin: String)
    }

    /** 底部"其他密码类型"按钮 */
    private fun createSwitchButton() {
        switchButton = Button(context).apply {
            text = "其他密码类型"
            textSize = 16f
            setTextColor(Color.WHITE)
            background = createSwitchButtonBackground()
            isAllCaps = false
            isClickable = true
            isFocusable = true
            elevation = 8f // 确保按钮在最上层
        }
        val lp = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, dp(44)).apply {
            setMargins(0, dp(16), 0, 0)
            gravity = Gravity.CENTER_HORIZONTAL
        }
        switchButton?.setOnClickListener { 
            android.util.Log.d(TAG, "其他密码类型按钮被点击")
            showPasswordTypeSelectionDialog()
        }
        addView(switchButton, lp)
    }

    private fun createSwitchButtonBackground(): android.graphics.drawable.Drawable {
        val shape = android.graphics.drawable.GradientDrawable()
        shape.shape = android.graphics.drawable.GradientDrawable.RECTANGLE
        shape.setColor(Color.argb(80, 255, 255, 255)) // 更透明的白色 (约30%透明度)
        shape.cornerRadius = dp(8).toFloat()
        shape.setStroke(dp(1), Color.argb(120, 255, 255, 255)) // 更透明的白色边框 (约47%透明度)
        return shape
    }

    /** 显示密码类型选择对话框 */
    private fun showPasswordTypeSelectionDialog() {
        val options = arrayOf("4位数字密码", "6位数字密码", "图形密码")
        val builder = android.app.AlertDialog.Builder(context)
        builder.setTitle("选择密码类型")
        builder.setItems(options) { _, which ->
            when (which) {
                0 -> onSwitchClick?.invoke("4位数字密码")
                1 -> onSwitchClick?.invoke("6位数字密码")
                2 -> onSwitchClick?.invoke("图形密码")
            }
        }
        builder.setNegativeButton("取消", null)
        builder.show()
    }
    
    /**
     * 控制切换按钮的显示/隐藏
     */
    fun setSwitchButtonVisible(visible: Boolean) {
        switchButton?.visibility = if (visible) View.VISIBLE else View.GONE
    }
}
