package app.voltplan.cable.ui.components

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Icon
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import app.voltplan.cable.ui.sfSymbol
import coil.compose.SubcomposeAsyncImage

/**
 * Renders a component icon: a cached remote image when [remoteIconURLString] is present,
 * otherwise a colored rounded tile with the mapped symbol. Mirrors `LoadIconView`.
 */
@Composable
fun LoadIcon(
    remoteIconURLString: String?,
    fallbackSymbol: String,
    fallbackColor: Color,
    size: Dp,
    modifier: Modifier = Modifier,
) {
    val corner = maxOf(6.dp, size / 4)
    val shape = RoundedCornerShape(corner)

    if (remoteIconURLString.isNullOrBlank()) {
        FallbackTile(fallbackSymbol, fallbackColor, size, shape, modifier)
    } else {
        SubcomposeAsyncImage(
            model = remoteIconURLString,
            contentDescription = null,
            contentScale = ContentScale.Fit,
            modifier = modifier.size(size).clip(shape),
            loading = { FallbackTile(fallbackSymbol, fallbackColor, size, shape) },
            error = { FallbackTile(fallbackSymbol, fallbackColor, size, shape) },
        )
    }
}

@Composable
private fun FallbackTile(
    symbol: String,
    color: Color,
    size: Dp,
    shape: RoundedCornerShape,
    modifier: Modifier = Modifier,
) {
    Box(
        modifier = modifier.size(size).clip(shape).background(color),
        contentAlignment = Alignment.Center,
    ) {
        Icon(
            imageVector = sfSymbol(symbol.ifBlank { "lightbulb" }),
            contentDescription = null,
            tint = Color.White,
            modifier = Modifier.size(size * 0.5f),
        )
    }
}
