package theorycrafter.ui.widgets

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.material.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import compose.utils.VerticallyCenteredRow
import compose.widgets.IconButton
import compose.widgets.SingleLineText
import theorycrafter.ui.Icons
import theorycrafter.ui.TheorycrafterTheme
import theorycrafter.utils.rememberLocalFontMetrics


/**
 * A small row with text and a close icon, similar to a Material input chip.
 */
@Composable
fun CloseableChip(
    text: String,
    onClose: () -> Unit,
    closeIconModifier: Modifier = Modifier,
    modifier: Modifier = Modifier,
) {
    VerticallyCenteredRow(
        horizontalArrangement = Arrangement.spacedBy(TheorycrafterTheme.spacing.xxxsmall),
        modifier = modifier
            .background(
                color = TheorycrafterTheme.colors.interactiveBackground(),
                shape = MaterialTheme.shapes.small
            )
            .padding(
                horizontal = TheorycrafterTheme.spacing.small,
                vertical = TheorycrafterTheme.spacing.xxsmall
            )
            .height(IntrinsicSize.Min)
    ) {
        val keyFontMetrics = rememberLocalFontMetrics()

        SingleLineText(
            text = text,
            modifier = Modifier
                .absoluteOffset {
                    val verticalOffset = -0.2f * keyFontMetrics.xHeight
                    IntOffset(x = 0, y = verticalOffset.toInt())
                }
        )
        IconButton(onClick = onClose, modifier = closeIconModifier) {
            Icons.Close(Modifier.size(16.dp))
        }
    }
}