package ui

import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.Stroke
import model.CandleData

@Composable
fun CandleChart(data: List<CandleData>, modifier: Modifier = Modifier) {
    if (data.isEmpty()) return

    Canvas(modifier = modifier.fillMaxSize()) {
        val width = size.width
        val height = size.height

        // 데이터가 적을 때도 일정한 너비를 유지하도록 개선
        val maxDisplayCount = 50
        val candleWidth = width / maxOf(data.size, maxDisplayCount)
        val spacing = candleWidth * 0.2f

        // 가격 범위 계산 (여백 추가)
        val maxPrice = data.maxOf { it.stck_hgpr.toDoubleOrNull() ?: 0.0 }
        val minPrice = data.minOf { it.stck_lwpr.toDoubleOrNull() ?: 0.0 }
        val priceRange = (maxPrice - minPrice).let { if (it == 0.0) 1.0 else it * 1.1 }
        val basePrice = minPrice - (priceRange * 0.05) // 아래쪽 여백

        fun getY(price: Double): Float = (height - ((price - basePrice) / priceRange * height)).toFloat()

        data.forEachIndexed { index, candle ->
            val open = candle.stck_oprc.toDoubleOrNull() ?: 0.0
            val close = candle.stck_prpr.toDoubleOrNull() ?: 0.0
            val high = candle.stck_hgpr.toDoubleOrNull() ?: 0.0
            val low = candle.stck_lwpr.toDoubleOrNull() ?: 0.0

            val isRising = close >= open
            val color = if (isRising) Color(0xFFE03E2D) else Color(0xFF0E62CF)

            val x = index * candleWidth + spacing / 2
            val currentCandleWidth = candleWidth - spacing

            // 2. 꼬리 그리기 (High-Low Line)
            drawLine(
                color = color,
                start = Offset(x + currentCandleWidth / 2, getY(high)),
                end = Offset(x + currentCandleWidth / 2, getY(low)),
                strokeWidth = 2f
            )

            // 3. 몸통 그리기 (Open-Close Rect)
            val bodyTop = getY(maxOf(open, close))
            val bodyBottom = getY(minOf(open, close))
            val bodyHeight = maxOf(bodyBottom - bodyTop, 1f) // 최소 1픽셀 보장

            drawRect(
                color = color,
                topLeft = Offset(x, bodyTop),
                size = Size(currentCandleWidth, bodyHeight)
            )
        }
    }
}