package solutions.tretter.mindmachine.session

import androidx.compose.foundation.background
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.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Slider
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import kotlin.math.roundToInt

private const val MIN_DURATION_SEC = 60
private const val MAX_DURATION_SEC = 60 * 60

@Composable
fun DurationSliderCard(
    durationSec: Int,
    onDurationSecChanged: (Int) -> Unit,
    modifier: Modifier = Modifier,
) {
    val clamped = remember(durationSec) { durationSec.coerceIn(MIN_DURATION_SEC, MAX_DURATION_SEC) }

    Column(
        modifier
            .fillMaxWidth()
            .background(MaterialTheme.colorScheme.surface, RoundedCornerShape(12.dp))
            .padding(12.dp),
        verticalArrangement = Arrangement.spacedBy(10.dp),
    ) {
        Row(
            Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically,
        ) {
            Text("Duration", color = MaterialTheme.colorScheme.onSurface)
            Text(
                formatDuration(clamped),
                style = MaterialTheme.typography.titleMedium,
                color = MaterialTheme.colorScheme.onSurface,
            )
        }

        Slider(
            value = clamped.toFloat(),
            onValueChange = {
                val snapped = (it / 60f).roundToInt().coerceIn(1, 60) * 60
                onDurationSecChanged(snapped)
            },
            valueRange = MIN_DURATION_SEC.toFloat()..MAX_DURATION_SEC.toFloat(),
            steps = 58,
        )

        Text(
            "Range: 1 minute to 60 minutes",
            style = MaterialTheme.typography.bodySmall,
            color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.7f),
        )
    }
}
