package com.adealink.weparty.commonui.recycleview.itemdecoration

import android.graphics.Canvas
import android.graphics.LinearGradient
import android.graphics.Paint
import android.graphics.RectF
import android.graphics.Shader
import android.view.View
import androidx.annotation.ColorInt
import androidx.annotation.Px
import androidx.recyclerview.widget.RecyclerView


data class AnchorConfig(
    val position: Int = Int.MAX_VALUE, // 位置
    @Px val extLineLength: Int = 0, // 锚点后面的延长线
)

class TimeLineItemDecoration(
    @Px private val lineOffset: Int,       // 竖直模式下是 X 偏移（LTR：从左边，RTL：从右边）；水平模式下是 Y 偏移
    @Px private val lineThickness: Int,    // 线宽（纵线宽度，横线高度）
    @ColorInt private val startColor: Int,
    @ColorInt private val endColor: Int,
    private val orientation: Int = RecyclerView.VERTICAL,
    private val anchorPosition: Int = Int.MAX_VALUE,
    @Px private val anchorExtLine: Int = 0  // 锚点之后的延展线长度
) : RecyclerView.ItemDecoration() {

    private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        style = Paint.Style.STROKE
        strokeWidth = lineThickness.toFloat()
        strokeCap = Paint.Cap.ROUND
    }

    override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
        super.onDraw(c, parent, state)
        val adapter = parent.adapter ?: return
        val count = adapter.itemCount
        if (count == 0) return

        // clamp 锚点
        val realAnchor = anchorPosition.coerceIn(0, count - 1)

        when (orientation) {
            RecyclerView.VERTICAL   -> drawVertical(c, parent, realAnchor)
            RecyclerView.HORIZONTAL -> drawHorizontal(c, parent, realAnchor)
        }
    }

    private fun drawVertical(c: Canvas, parent: RecyclerView, realAnchor: Int) {
        // --- 1. 根据 layoutDirection 计算实际的 X 坐标 ---
        val isRtl = parent.layoutDirection == View.LAYOUT_DIRECTION_RTL
        // 如果是 RTL，就要从右边开始偏移
        val xPos = if (isRtl) {
            (parent.width - lineOffset).toFloat()
        } else {
            lineOffset.toFloat()
        }

        // --- 2. 找 startY/endY ---
        var startY: Float? = null
        var endY: Float? = null
        val firstVisible = parent.getChildAdapterPosition(parent.getChildAt(0))
        for (i in 0 until parent.childCount) {
            val child = parent.getChildAt(i)
            val pos = parent.getChildAdapterPosition(child)
            val cy = (child.top + child.bottom) * 0.5f
            if (pos == 0) startY = cy
            if (pos == realAnchor) endY = cy
        }
        val topBound    = parent.paddingTop.toFloat()
        val bottomBound = (parent.height - parent.paddingBottom).toFloat()
        if (startY == null) startY = topBound
        if (endY   == null) endY   = if (realAnchor < firstVisible) topBound else bottomBound

        // --- 3. 延展线 ---
        if (realAnchor < parent.childCount - 1 && anchorExtLine > 0) {
            endY = endY + anchorExtLine
        }

        // --- 4. 渐变 Shader ---
        paint.shader = LinearGradient(
            xPos, startY,
            xPos, endY,
            startColor, endColor,
            Shader.TileMode.CLAMP
        )

        // --- 5. 绘制圆角矩形线条 ---
        val half = lineThickness / 2f
        val rect = RectF(
            xPos - half, startY,
            xPos + half, endY
        )
        c.drawRoundRect(rect, 40f, 40f, paint)
    }

    private fun drawHorizontal(c: Canvas, parent: RecyclerView, realAnchor: Int) {
        val isRtl = parent.layoutDirection == View.LAYOUT_DIRECTION_RTL

        // 1. 收集子项中 pos = 0 和 pos = realAnchor 的中心 X
        var startX: Float? = null
        var endX: Float? = null
        val firstVisiblePos = parent.getChildAdapterPosition(parent.getChildAt(0))

        for (i in 0 until parent.childCount) {
            val child = parent.getChildAt(i)
            val pos = parent.getChildAdapterPosition(child)
            val cx = (child.left + child.right) * 0.5f
            if (pos == 0) startX = cx
            if (pos == realAnchor) endX = cx
        }

        // 2. 边界
        val leftBound  = parent.paddingLeft.toFloat()
        val rightBound = (parent.width - parent.paddingRight).toFloat()

        // 3. 缺失时 clamp 到边界 (考虑 RTL)
        if (startX == null) {
            startX = if (isRtl) rightBound else leftBound
        }
        if (endX == null) {
            endX = if (realAnchor < firstVisiblePos) {
                if (isRtl) rightBound else leftBound
            } else {
                if (isRtl) leftBound  else rightBound
            }
        }

        // 4. 延展线（沿与 startX→endX 相同方向延伸）
        if (anchorExtLine > 0) {
            endX += if (isRtl) -anchorExtLine else anchorExtLine
        }

        // 5. 渐变 Shader
        paint.shader = LinearGradient(
            startX, lineOffset.toFloat(),
            endX,   lineOffset.toFloat(),
            startColor, endColor,
            Shader.TileMode.CLAMP
        )

        // 6. 绘制
        val half = lineThickness / 2f
        val rect = RectF(
            startX,              lineOffset - half,
            endX,                lineOffset + half
        )
        c.drawRoundRect(rect, 40f, 40f, paint)
    }

}
