package com.audio.record.screen.test.view

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import java.lang.Math.abs

class RangeSliderView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null
) : View(context, attrs) {

    private var leftThumbX = 100f
    private var rightThumbX = 600f
    private val thumbRadius = 30f

    private val trackHeight = 20f

    private val trackPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        color = Color.RED
    }

    private val thumbPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        color = Color.RED
    }

    private val linePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        color = Color.WHITE
        strokeWidth = 6f
    }

    private var activeThumb: Thumb? = null

    enum class Thumb { LEFT, RIGHT }

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

        // Draw selected range (red track)
        val centerY = height / 2f
        canvas.drawRect(leftThumbX, centerY - trackHeight / 2, rightThumbX, centerY + trackHeight / 2, trackPaint)

        // Draw thumbs
        canvas.drawRect(leftThumbX - thumbRadius, centerY - 2 * thumbRadius,
            leftThumbX + thumbRadius, centerY + 2 * thumbRadius, thumbPaint)
        canvas.drawRect(rightThumbX - thumbRadius, centerY - 2 * thumbRadius,
            rightThumbX + thumbRadius, centerY + 2 * thumbRadius, thumbPaint)

        // Draw white lines on thumbs
        val lineHeight = 40f
        canvas.drawLine(leftThumbX, centerY - lineHeight, leftThumbX, centerY + lineHeight, linePaint)
        canvas.drawLine(rightThumbX, centerY - lineHeight, rightThumbX, centerY + lineHeight, linePaint)
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        val x = event.x
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                activeThumb = when {
                    isInsideThumb(x, leftThumbX) -> Thumb.LEFT
                    isInsideThumb(x, rightThumbX) -> Thumb.RIGHT
                    else -> null
                }
            }
            MotionEvent.ACTION_MOVE -> {
                activeThumb?.let {
                    when (it) {
                        Thumb.LEFT -> {
                            leftThumbX = x.coerceIn(0f, rightThumbX - 100f)
                        }
                        Thumb.RIGHT -> {
                            rightThumbX = x.coerceIn(leftThumbX + 100f, width.toFloat())
                        }
                    }
                    invalidate()
                }
            }
            MotionEvent.ACTION_UP -> {
                activeThumb = null
            }
        }
        return true
    }

    private fun isInsideThumb(touchX: Float, thumbX: Float): Boolean {
        return abs(touchX - thumbX) <= thumbRadius * 2
    }
}
