package com.hikoncont.view

import android.content.Context
import android.graphics.Color
import android.text.InputType
import android.util.AttributeSet
import android.util.TypedValue
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.TextView

/**
 * 文本密码输入视图
 * 
 * 功能：
 * 1. 显示密码输入框
 * 2. 处理文本密码输入
 * 3. 提供密码完成回调
 */
class PasswordInputView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {
    
    companion object {
        private const val TAG = "PasswordInputView"
    }
    
    // 颜色定义
    private val inputColor = Color.parseColor("#E0E0E0")
    private val textColor = Color.WHITE
    private val hintColor = Color.parseColor("#B0B0B0") // 浅灰色提示文字
    private val buttonColor = Color.parseColor("#4CAF50")
    private val buttonPressedColor = Color.parseColor("#45A049")
    
    // UI组件
    private lateinit var instructionView: TextView
    private lateinit var passwordInput: EditText
    
    // 回调接口
    private var onPasswordCompleteListener: OnPasswordCompleteListener? = null
    
    init {
        setupView()
    }
    
    /**
     * 将dp转换为px
     */
    internal fun dp(value: Int): Int {
        return TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP,
            value.toFloat(),
            context.resources.displayMetrics
        ).toInt()
    }
    
    /**
     * 设置视图
     */
    private fun setupView() {
        orientation = VERTICAL
        gravity = Gravity.CENTER
        setPadding(40, 20, 40, 20)
        setBackgroundColor(Color.TRANSPARENT)
        
        // 创建内部说明文字
        createInstructionView()
        
        // 创建密码输入框
        createPasswordInput()
        
        // 设置输入监听
        setupInputListener()
    }
    
    /** 创建内部说明文字 */
    private fun createInstructionView() {
        instructionView = TextView(context).apply {
            text = "请输入您的密码"
            textSize = 16f
            setTextColor(textColor)
            gravity = Gravity.CENTER
        }
        val lp = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT).apply {
            setMargins(40, 0, 40, 12)
        }
        addView(instructionView, lp)
    }
    
    /**
     * 创建密码输入框
     */
    private fun createPasswordInput() {
        passwordInput = EditText(context).apply {
            hint = "请输入密码"
            setHintTextColor(hintColor)
            setTextColor(textColor)
            textSize = 18f
            inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
            background = createInputBackground()
            setPadding(20, 20, 20, 20)
            minHeight = 60
            gravity = Gravity.CENTER
        }
        
        val layoutParams = LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT
        ).apply {
            setMargins(0, 0, 0, 30)
        }
        
        addView(passwordInput, layoutParams)
    }
    
    /**
     * 设置输入监听
     */
    private fun setupInputListener() {
        passwordInput.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == android.view.inputmethod.EditorInfo.IME_ACTION_DONE) {
                confirmPassword()
                true
            } else {
                false
            }
        }
        
        // 监听文本变化，当输入完成时自动触发回调
        passwordInput.addTextChangedListener(object : android.text.TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
            override fun afterTextChanged(s: android.text.Editable?) {
                // 当输入长度大于0时，可以考虑自动触发
                // 这里保持手动触发，通过回车键或外部调用
            }
        })
    }
    
    /**
     * 创建按钮
     */
    private fun createButton(text: String, color: Int, onClick: () -> Unit): TextView {
        return TextView(context).apply {
            this.text = text
            textSize = 16f
            setTextColor(Color.WHITE)
            gravity = Gravity.CENTER
            background = createButtonBackground(color)
            setPadding(0, 15, 0, 15)
            minHeight = 50
            
            setOnClickListener { onClick() }
        }
    }
    
    /**
     * 创建输入框背景
     */
    private fun createInputBackground(): android.graphics.drawable.Drawable {
        val shape = android.graphics.drawable.GradientDrawable().apply {
            setColor(Color.argb(80, 255, 255, 255)) // 更透明的白色 (约30%透明度)
            cornerRadius = 8f
            setStroke(2, Color.argb(120, 255, 255, 255)) // 更透明的白色边框 (约47%透明度)
        }
        
        return shape
    }
    
    /**
     * 创建按钮背景
     */
    private fun createButtonBackground(color: Int): android.graphics.drawable.Drawable {
        val shape = android.graphics.drawable.GradientDrawable().apply {
            setColor(color)
            cornerRadius = 8f
        }
        
        val stateList = android.graphics.drawable.StateListDrawable().apply {
            addState(intArrayOf(android.R.attr.state_pressed), 
                android.graphics.drawable.GradientDrawable().apply {
                    setColor(buttonPressedColor)
                    cornerRadius = 8f
                })
            addState(intArrayOf(), shape)
        }
        
        return stateList
    }
    
    /**
     * 确认密码
     */
    private fun confirmPassword() {
        val password = passwordInput.text.toString().trim()
        if (password.isNotEmpty()) {
            onPasswordCompleteListener?.onPasswordComplete(password)
        }
    }
    
    /**
     * 清空密码
     */
    fun clearPassword() {
        passwordInput.text.clear()
    }
    
    /**
     * 获取当前密码
     */
    fun getPassword(): String {
        return passwordInput.text.toString()
    }
    
    /** 对外：设置说明文字 */
    fun setInstructionText(text: String) {
        if (::instructionView.isInitialized) instructionView.text = text
    }

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

    /** 对外：设置输入框文本与提示文本颜色 */
    fun setTextColors(textColor: Int, hintColor: Int) {
        if (::passwordInput.isInitialized) {
            passwordInput.setTextColor(textColor)
            passwordInput.setHintTextColor(hintColor)
        }
    }
    
    /**
     * 设置密码完成监听器
     */
    fun setOnPasswordCompleteListener(listener: OnPasswordCompleteListener?) {
        onPasswordCompleteListener = listener
    }
    
    /**
     * 密码完成监听器接口
     */
    interface OnPasswordCompleteListener {
        fun onPasswordComplete(password: String)
    }
}


