package theorycrafter.ui.widgets

import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
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 eve.data.fractionAsPercentage
import theorycrafter.ui.TheorycrafterTheme
import theorycrafter.utils.ColoredTextBox
import theorycrafter.utils.darker
import theorycrafter.utils.rememberColoredTextBoxBackgroundBrush


/**
 * A box displaying a percentage value and a partially filled background proportional to the percentage.
 */
@Composable
fun PercentageView(


    /**
     * The value to display; a number between 0 and 1, inclusive.
     */
    value: Float,


    /**
     * The number of decimal digits to display.
     */
    decimals: Int,


    /**
     * Whether to animate value changes.
     */
    animate: Boolean = true,


    /**
     * The widget colors.
     */
    colors: PercentageViewColors,


    /**
     * A modifier to apply to the top-level element.
     */
    modifier: Modifier = Modifier,


) {
    if (value.isNaN() || value.isInfinite())
        throw IllegalArgumentException("Illegal value: $value")

    val displayedValue = if (animate)
        animateFloatAsState(
            targetValue = value,
            animationSpec = tween()
        ).value
    else
        value

    val filledBrush = rememberColoredTextBoxBackgroundBrush(colors.filled)
    ColoredTextBox(
        text = displayedValue.toDouble().let {
            if (it > 9.99)
                ">999%"
            else
                it.fractionAsPercentage(decimals)
        },
        drawBackground = {
            drawRect(color = colors.unfilled)
            drawRect(
                brush = filledBrush,
                topLeft = Offset.Zero,
                size = Size(
                    width = (size.width * displayedValue).coerceAtMost(size.width),
                    height = size.height
                )
            )
        },
        textStyle = TheorycrafterTheme.textStyles.percentageView,
        textColor = colors.textColor,
        textShadowColor = colors.textShadowColor,
        modifier = modifier,
        textModifier = Modifier
            .padding(TheorycrafterTheme.spacing.xxsmall)
            .fillMaxWidth(),
    )
}


/**
 * Encapsulates the colors used for [PercentageView]
 */
data class PercentageViewColors(
    val textColor: Color,
    val textShadowColor: Color,
    val filled: Color,
    val unfilled: Color = filled.darker(0.3f),
)
