package com.jishisongfu.duobibi.ui.records

import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.PathEffect
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.unit.dp
import com.jishisongfu.duobibi.data.db.PriceRecord
import com.jishisongfu.duobibi.ui.theme.DbbColors

/** 价格趋势折线图(蓝青风)。横轴时间,纵轴价格,最低点红色高亮。 */
@Composable
fun PriceTrendChart(records: List<PriceRecord>, modifier: Modifier = Modifier) {
    if (records.size < 2) return
    val sorted = records.sortedBy { it.createdAt }
    val minTs = sorted.first().createdAt
    val tsSpan = (sorted.last().createdAt - minTs).coerceAtLeast(1L).toFloat()
    val minPrice = sorted.minOf { it.price }
    val priceSpan = (sorted.maxOf { it.price } - minPrice).coerceAtLeast(0.01).toFloat()

    Box(modifier.fillMaxWidth().height(150.dp)) {
        Canvas(Modifier.fillMaxWidth().height(150.dp)) {
            val padL = 8.dp.toPx(); val padR = 8.dp.toPx(); val padT = 16.dp.toPx(); val padB = 16.dp.toPx()
            val w = size.width - padL - padR
            val h = size.height - padT - padB
            for (i in 0..2) {
                val y = padT + h * (i / 2f)
                drawLine(DbbColors.Border, Offset(padL, y), Offset(padL + w, y), 1f,
                    pathEffect = PathEffect.dashPathEffect(floatArrayOf(8f, 6f)))
            }
            val points = sorted.map { r ->
                val x = padL + ((r.createdAt - minTs).toFloat() / tsSpan) * w
                val y = padT + h - ((r.price - minPrice).toFloat() / priceSpan) * h
                Offset(x, y) to r
            }
            val path = Path()
            points.forEachIndexed { idx, (p, _) -> if (idx == 0) path.moveTo(p.x, p.y) else path.lineTo(p.x, p.y) }
            drawPath(path, DbbColors.Teal, style = Stroke(width = 4f))
            points.forEach { (p, r) ->
                val isMin = r.price == minPrice
                drawCircle(if (isMin) DbbColors.Up else DbbColors.Teal, if (isMin) 7f else 5f, p)
                if (isMin) drawCircle(Color.White, 3f, p)
            }
        }
    }
}
