package app.voltplan.cable.ui.components

import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.Slider
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import app.voltplan.cable.util.Fmt
import kotlin.math.abs

/**
 * Slider with snap-to-common-values and a tappable title/value that opens an editable dialog.
 * Reproduces the iOS `SliderSection` + alert-based editing pattern.
 */
@Composable
fun SnapSlider(
    title: String,
    value: Double,
    range: ClosedFloatingPointRange<Double>,
    valueText: String,
    onValueChange: (Double) -> Unit,
    modifier: Modifier = Modifier,
    snapValues: List<Double> = emptyList(),
    snapTolerance: Double = 0.0,
    round: (Double) -> Double = { it },
    onEditRequest: (() -> Unit)? = null,
    trailing: @Composable (() -> Unit)? = null,
) {
    Column(modifier = modifier.fillMaxWidth().padding(vertical = 6.dp)) {
        Row(
            verticalAlignment = Alignment.CenterVertically,
            modifier = Modifier.fillMaxWidth(),
        ) {
            Text(
                title.uppercase(),
                style = MaterialTheme.typography.labelMedium,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
                modifier = if (onEditRequest != null) Modifier.clickable { onEditRequest() } else Modifier,
            )
            Text(
                valueText,
                style = MaterialTheme.typography.titleMedium,
                fontWeight = FontWeight.SemiBold,
                modifier = Modifier
                    .padding(start = 8.dp)
                    .then(if (onEditRequest != null) Modifier.clickable { onEditRequest() } else Modifier),
            )
            androidx.compose.foundation.layout.Spacer(Modifier.weight(1f))
            trailing?.invoke()
        }
        Slider(
            value = value.coerceIn(range.start, range.endInclusive).toFloat(),
            onValueChange = { raw ->
                onValueChange(applySnap(raw.toDouble(), snapValues, snapTolerance, round))
            },
            valueRange = range.start.toFloat()..range.endInclusive.toFloat(),
        )
    }
}

private fun applySnap(
    raw: Double,
    snapValues: List<Double>,
    tolerance: Double,
    round: (Double) -> Double,
): Double {
    val rounded = round(raw)
    if (snapValues.isEmpty() || tolerance <= 0) return rounded
    val nearest = snapValues.minByOrNull { abs(it - rounded) } ?: return rounded
    return if (abs(nearest - rounded) <= tolerance) nearest else rounded
}

/** Numeric edit dialog matching the iOS per-field alert. */
@Composable
fun ValueEditDialog(
    title: String,
    message: String?,
    initialValue: Double,
    onConfirm: (Double) -> Unit,
    onDismiss: () -> Unit,
) {
    var text by remember { mutableStateOf(Fmt.number(initialValue)) }
    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text(title) },
        text = {
            Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
                if (message != null) Text(message, style = MaterialTheme.typography.bodyMedium)
                OutlinedTextField(
                    value = text,
                    onValueChange = { text = it },
                    singleLine = true,
                    keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
                )
            }
        },
        confirmButton = {
            TextButton(onClick = { Fmt.parseInput(text)?.let(onConfirm); onDismiss() }) { Text("Save") }
        },
        dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },
    )
}
