package com.hikoncont.view

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.Gravity
import android.view.MotionEvent
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import kotlin.math.*

/**
 * 图形密码锁视图
 * 
 * 功能：
 * 1. 显示3x3的图形密码网格
 * 2. 记录用户绘制轨迹
 * 3. 提供轨迹回调
 * 4. 内置说明文字
 */
class PatternLockView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {
    
    companion object {
        private const val TAG = "PatternLockView"
        private const val GRID_SIZE = 3
        private const val DOT_RADIUS = 15f
        private const val LINE_WIDTH = 4f
        private const val SELECTED_DOT_RADIUS = 20f
    }
    
    // UI组件
    private lateinit var instructionView: TextView
    private lateinit var patternView: PatternDrawView
    private var switchButton: android.widget.Button? = null
    private var onSwitchClick: ((String) -> Unit)? = null
    
    // 回调接口
    private var onPatternListener: OnPatternListener? = null
    
    // 网格点数据类
    data class Cell(val row: Int, val column: Int)
    
    init {
        setupView()
    }
    
    /**
     * 设置视图
     */
    private fun setupView() {
        orientation = VERTICAL
        gravity = Gravity.CENTER_HORIZONTAL
        setPadding(dp(40), dp(12), dp(40), dp(12))
        setBackgroundColor(Color.TRANSPARENT)

        addTopSpacer(0.2f)
        // 创建说明文字
        createInstructionView()
        
        // 创建图形密码绘制视图
        createPatternView()

        // 内置"其他密码类型"按钮
        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 = "请绘制您的图形密码"
            textSize = 16f
            setTextColor(Color.WHITE)
            gravity = Gravity.CENTER
        }
        val lp = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT).apply {
            setMargins(dp(20), 0, dp(20), dp(6))
        }
        addView(instructionView, lp)
    }

    /** 显示密码类型选择对话框 */
    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()
    }

    /** 底部"其他密码类型"按钮 */
    private fun createSwitchButton() {
        switchButton = android.widget.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, "PatternLockView切换按钮被点击")
            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(1, Color.argb(120, 255, 255, 255)) // 更透明的白色边框 (约47%透明度)
        return shape
    }

    /** 对外：设置切换点击回调 */
    fun setOnSwitchClickListener(listener: ((String) -> Unit)?) {
        android.util.Log.d(TAG, "设置PatternLockView切换按钮回调: ${listener != null}")
        onSwitchClick = listener
    }
    
    /**
     * 控制切换按钮的显示/隐藏
     */
    fun setSwitchButtonVisible(visible: Boolean) {
        switchButton?.visibility = if (visible) View.VISIBLE else View.GONE
    }
    
    /**
     * 创建图形密码绘制视图
     */
    private fun createPatternView() {
        patternView = PatternDrawView(context)
        val lp = LinearLayout.LayoutParams(dp(300), dp(300))
        lp.setMargins(0, dp(4), 0, dp(6))
        addView(patternView, lp)
        
        // 设置回调
        patternView.setOnPatternListener(object : PatternDrawView.OnPatternListener {
            override fun onPatternStart() {
                onPatternListener?.onPatternStart()
            }
            
            override fun onPatternProgress(pattern: List<Cell>) {
                onPatternListener?.onPatternProgress(pattern)
            }
            
            override fun onPatternComplete(pattern: List<Cell>) {
                onPatternListener?.onPatternComplete(pattern)
            }
        })
    }
    
    /**
     * 设置说明文字
     */
    fun setInstructionText(text: String) {
        if (::instructionView.isInitialized) {
            instructionView.text = text
        }
    }

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

    /** 对外：设置底部切换按钮文字颜色 */
    fun setSwitchButtonTextColor(color: Int) {
        switchButton?.setTextColor(color)
    }
    
    /**
     * 设置图形密码监听器
     */
    fun setOnPatternListener(listener: OnPatternListener?) {
        onPatternListener = listener
    }
    
    /**
     * 清除图形密码
     */
    fun clearPattern() {
        if (::patternView.isInitialized) {
            patternView.clearPattern()
        }
    }
    
    private fun dp(value: Int): Int = (resources.displayMetrics.density * value).toInt()
    
    /**
     * 图形密码监听器接口
     */
    interface OnPatternListener {
        fun onPatternStart()
        fun onPatternProgress(pattern: List<Cell>)
        fun onPatternComplete(pattern: List<Cell>)
    }
}

/**
 * 图形密码绘制视图
 */
class PatternDrawView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
    
    companion object {
        private const val GRID_SIZE = 3
        private const val DOT_RADIUS = 15f
        private const val LINE_WIDTH = 4f
        private const val SELECTED_DOT_RADIUS = 20f
    }
    
    // 颜色定义
    private val normalDotColor = Color.DKGRAY
    private val selectedDotColor = Color.BLACK
    private val lineColor = Color.BLACK
    private val backgroundColor = Color.TRANSPARENT
    
    // 绘制相关
    private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
    private val path = Path()
    
    // 网格数据
    private val dots = mutableListOf<Dot>()
    private val selectedDots = mutableListOf<Dot>()
    private var currentTouchPoint: PointF? = null
    
    // 状态
    private var isDrawing = false
    private var currentDot: Dot? = null
    
    // 回调接口
    private var onPatternListener: OnPatternListener? = null
    
    // 网格点数据类
    data class Dot(val cell: PatternLockView.Cell, val centerX: Float, val centerY: Float, var isSelected: Boolean = false)
    
    init {
        setupPaint()
    }
    
    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        initializeDots()
    }
    
    /**
     * 设置画笔
     */
    private fun setupPaint() {
        paint.style = Paint.Style.FILL
        paint.strokeWidth = LINE_WIDTH
        paint.strokeCap = Paint.Cap.ROUND
        paint.strokeJoin = Paint.Join.ROUND
    }
    
    /**
     * 初始化网格点
     */
    private fun initializeDots() {
        dots.clear()
        val cellSize = min(width, height) / (GRID_SIZE + 1)
        val startX = (width - cellSize * (GRID_SIZE - 1)) / 2f
        val startY = (height - cellSize * (GRID_SIZE - 1)) / 2f
        
        for (row in 0 until GRID_SIZE) {
            for (col in 0 until GRID_SIZE) {
                val centerX = startX + col * cellSize
                val centerY = startY + row * cellSize
                val dot = Dot(PatternLockView.Cell(row, col), centerX, centerY)
                dots.add(dot)
            }
        }
    }
    
    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        
        // 绘制背景
        canvas.drawColor(backgroundColor)
        
        // 绘制网格点
        drawDots(canvas)
        
        // 绘制连接线
        drawLines(canvas)
        
        // 绘制当前触摸点
        drawCurrentTouch(canvas)
    }
    
    /**
     * 绘制网格点
     */
    private fun drawDots(canvas: Canvas) {
        dots.forEach { dot ->
            paint.color = if (dot.isSelected) selectedDotColor else normalDotColor
            paint.style = Paint.Style.FILL
            
            // 绘制外圆
            canvas.drawCircle(dot.centerX, dot.centerY, DOT_RADIUS, paint)
            
            // 绘制内圆（选中状态）
            if (dot.isSelected) {
                paint.color = selectedDotColor
                canvas.drawCircle(dot.centerX, dot.centerY, DOT_RADIUS * 0.6f, paint)
            }
        }
    }
    
    /**
     * 绘制连接线
     */
    private fun drawLines(canvas: Canvas) {
        if (selectedDots.size < 2) return
        
        paint.color = lineColor
        paint.style = Paint.Style.STROKE
        paint.strokeWidth = LINE_WIDTH
        
        path.reset()
        path.moveTo(selectedDots[0].centerX, selectedDots[0].centerY)
        
        for (i in 1 until selectedDots.size) {
            path.lineTo(selectedDots[i].centerX, selectedDots[i].centerY)
        }
        
        // 绘制到当前触摸点
        currentTouchPoint?.let { point ->
            path.lineTo(point.x, point.y)
        }
        
        canvas.drawPath(path, paint)
    }
    
    /**
     * 绘制当前触摸点
     */
    private fun drawCurrentTouch(canvas: Canvas) {
        currentTouchPoint?.let { point ->
            paint.color = lineColor
            paint.style = Paint.Style.FILL
            canvas.drawCircle(point.x, point.y, DOT_RADIUS * 0.3f, paint)
        }
    }
    
    override fun onTouchEvent(event: MotionEvent): Boolean {
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                handleTouchDown(event.x, event.y)
                return true
            }
            MotionEvent.ACTION_MOVE -> {
                handleTouchMove(event.x, event.y)
                return true
            }
            MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                handleTouchUp()
                return true
            }
        }
        return super.onTouchEvent(event)
    }
    
    /**
     * 处理触摸按下
     */
    private fun handleTouchDown(x: Float, y: Float) {
        val dot = findNearestDot(x, y)
        if (dot != null && !dot.isSelected) {
            dot.isSelected = true
            selectedDots.add(dot)
            currentDot = dot
            isDrawing = true
            
            onPatternListener?.onPatternStart()
            invalidate()
        }
    }
    
    /**
     * 处理触摸移动
     */
    private fun handleTouchMove(x: Float, y: Float) {
        if (!isDrawing) return
        
        currentTouchPoint = PointF(x, y)
        
        val dot = findNearestDot(x, y)
        if (dot != null && !dot.isSelected) {
            dot.isSelected = true
            selectedDots.add(dot)
            currentDot = dot
        }
        
        onPatternListener?.onPatternProgress(selectedDots.map { it.cell })
        invalidate()
    }
    
    /**
     * 处理触摸抬起
     */
    private fun handleTouchUp() {
        if (!isDrawing) return
        
        isDrawing = false
        currentTouchPoint = null
        
        onPatternListener?.onPatternComplete(selectedDots.map { it.cell })
        invalidate()
    }
    
    /**
     * 查找最近的网格点
     */
    private fun findNearestDot(x: Float, y: Float): Dot? {
        val threshold = DOT_RADIUS * 2
        return dots.find { dot ->
            val distance = sqrt((x - dot.centerX).pow(2) + (y - dot.centerY).pow(2))
            distance <= threshold
        }
    }
    
    /**
     * 清除图形密码
     */
    fun clearPattern() {
        selectedDots.forEach { it.isSelected = false }
        selectedDots.clear()
        currentTouchPoint = null
        isDrawing = false
        currentDot = null
        invalidate()
    }
    
    /**
     * 设置图形密码监听器
     */
    fun setOnPatternListener(listener: OnPatternListener?) {
        onPatternListener = listener
    }
    
    /**
     * 图形密码监听器接口
     */
    interface OnPatternListener {
        fun onPatternStart()
        fun onPatternProgress(pattern: List<PatternLockView.Cell>)
        fun onPatternComplete(pattern: List<PatternLockView.Cell>)
    }

}