package com.ponzischeme89.memby.ui.player

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.RectF
import android.util.AttributeSet
import android.util.TypedValue
import android.view.View
import kotlin.math.min

/**
 * Compact TV-safe countdown that does not depend on a continuously running animator.
 * PlayerActivity advances it only while video is actually playing, keeping the ring and
 * the pre-roll gate on the same clock.
 */
class PrerollCountdownView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0,
) : View(context, attrs, defStyleAttr) {

    private val density = resources.displayMetrics.density
    private val ringBounds = RectF()
    private val trackPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        color = Color.argb(72, 255, 255, 255)
        style = Paint.Style.STROKE
        strokeCap = Paint.Cap.ROUND
        strokeWidth = 5f * density
    }
    private val progressPaint = Paint(trackPaint).apply {
        color = Color.rgb(82, 190, 75)
    }
    private val numberPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        color = Color.WHITE
        textAlign = Paint.Align.CENTER
        textSize = TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_SP,
            30f,
            resources.displayMetrics,
        )
        typeface = android.graphics.Typeface.create("sans-serif", android.graphics.Typeface.BOLD)
    }

    private var seconds = 7
    private var progress = 1f

    fun setCountdown(seconds: Int, progress: Float, description: String) {
        this.seconds = seconds.coerceAtLeast(0)
        this.progress = progress.coerceIn(0f, 1f)
        contentDescription = description
        invalidate()
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        val strokeInset = trackPaint.strokeWidth / 2f
        val diameter = min(width, height).toFloat()
        val left = (width - diameter) / 2f + strokeInset
        val top = (height - diameter) / 2f + strokeInset
        ringBounds.set(
            left,
            top,
            left + diameter - trackPaint.strokeWidth,
            top + diameter - trackPaint.strokeWidth,
        )
        canvas.drawOval(ringBounds, trackPaint)
        if (progress > 0f) {
            canvas.drawArc(ringBounds, -90f, 360f * progress, false, progressPaint)
        }
        val baseline = height / 2f - (numberPaint.ascent() + numberPaint.descent()) / 2f
        canvas.drawText(seconds.toString(), width / 2f, baseline, numberPaint)
    }
}
