package com.example.studentfaceregistry.ui

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.RectF
import android.graphics.Typeface
import android.util.AttributeSet
import android.view.View
import com.example.studentfaceregistry.face.MatchType
import com.example.studentfaceregistry.face.RecognitionResult

/**
 * 识别叠加视图
 * 在摄像头预览上绘制识别框和标签
 */
class OverlayView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null
) : View(context, attrs) {

    // 识别框画笔
    private val boxPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        style = Paint.Style.STROKE
        strokeWidth = 6f
    }

    // 标签背景画笔
    private val labelBackgroundPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        style = Paint.Style.FILL
    }

    // 标签文字画笔
    private val labelPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        color = Color.WHITE
        textSize = 48f
        typeface = Typeface.DEFAULT_BOLD
    }

    // 置信度文字画笔
    private val confidencePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        color = Color.WHITE
        textSize = 32f
    }

    // 颜色定义
    private val colorMatch = Color.rgb(34, 197, 94)      // 绿色 - 匹配成功
    private val colorUnsure = Color.rgb(234, 179, 8)    // 黄色 - 不确定
    private val colorNoMatch = Color.rgb(239, 68, 68)   // 红色 - 未匹配
    private val colorUnknown = Color.rgb(59, 130, 246)  // 蓝色 - 识别中

    private var detections: List<DetectionUi> = emptyList()

    fun update(items: List<DetectionUi>) {
        detections = items
        invalidate()
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        detections.forEachIndexed { index, item ->
            drawDetection(canvas, item, index)
        }
    }

    private fun drawDetection(canvas: Canvas, item: DetectionUi, index: Int) {
        val rect = item.bounds

        // 根据识别结果设置颜色
        val boxColor = getBoxColor(item.result)
        boxPaint.color = boxColor

        // 绘制识别框
        canvas.drawRect(rect.left, rect.top, rect.right, rect.bottom, boxPaint)

        // 绘制标签背景
        val label = item.label
        val labelWidth = labelPaint.measureText(label)
        val labelHeight = 60f
        val padding = 12f

        // 标签在框上方
        val labelLeft = rect.left + padding
        val labelTop = (rect.top - labelHeight - padding).coerceAtLeast(padding)
        val labelRight = labelLeft + labelWidth + padding * 2
        val labelBottom = labelTop + labelHeight

        // 标签背景颜色与框颜色一致
        labelBackgroundPaint.color = boxColor
        canvas.drawRoundRect(labelLeft, labelTop, labelRight, labelBottom, 8f, 8f, labelBackgroundPaint)

        // 绘制标签文字
        canvas.drawText(label, labelLeft + padding, labelTop + 38f, labelPaint)

        // 如果有置信度信息，显示在标签右侧
        if (item.confidence != null) {
            val confidenceText = "${(item.confidence * 100).toInt()}%"
            val confidenceWidth = confidencePaint.measureText(confidenceText)
            val confLeft = labelRight + 8f
            val confTop = labelTop + 8f
            val confRight = confLeft + confidenceWidth + 16f
            val confBottom = confTop + 44f

            // 置信度背景（半透明黑色）
            labelBackgroundPaint.color = Color.argb(180, 0, 0, 0)
            canvas.drawRoundRect(confLeft, confTop, confRight, confBottom, 6f, 6f, labelBackgroundPaint)

            // 置信度文字
            canvas.drawText(confidenceText, confLeft + 8f, confTop + 30f, confidencePaint)
        }
    }

    private fun getBoxColor(result: RecognitionResult): Int {
        return when {
            result.isMatched -> colorMatch
            result.matchType == MatchType.UNSURE -> colorUnsure
            result.student == null && result.distance != Float.MAX_VALUE -> colorNoMatch
            else -> colorUnknown
        }
    }
}

/**
 * 识别 UI 数据
 */
data class DetectionUi(
    val bounds: RectF,
    val result: RecognitionResult,
    val confidence: Float? = null
) {
    val label: String
        get() {
            return when {
                result.isMatched -> "${result.student?.name} (${result.student?.studentNo})"
                result.matchType == MatchType.UNSURE -> "疑似：${result.student?.name}"
                result.student == null && result.distance != Float.MAX_VALUE -> "未匹配"
                else -> "识别中"
            }
        }
}
