package com.onthelevel.feature.tools

import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.SegmentedButton
import androidx.compose.material3.SegmentedButtonDefaults
import androidx.compose.material3.SingleChoiceSegmentedButtonRow
import androidx.compose.material3.Switch
import androidx.compose.material3.SwitchDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.onthelevel.AppContainer
import com.onthelevel.core.design.LevelColors
import com.onthelevel.core.settings.MeasurementUnits
import kotlinx.coroutines.launch

/**
 * App settings, reached from the Level header gear. Calibration is a plain doorway
 * here (its own screen owns status and controls); the measurement preferences live
 * directly on this list. Done is pinned to the bottom so it stays put as the list grows.
 */
@Composable
fun SettingsScreen(
    container: AppContainer,
    onOpenSurfaceCalibration: () -> Unit,
    onBack: () -> Unit,
) {
    // A preferences list should time out normally — no KeepScreenOn here (calibration
    // and the live tool screens keep the screen awake themselves).
    val units by container.settings.measurementUnits
        .collectAsStateWithLifecycle(initialValue = MeasurementUnits.METRIC)
    val reducedMotion by container.settings.reducedMotion
        .collectAsStateWithLifecycle(initialValue = false)
    val hapticsEnabled by container.settings.hapticsEnabled
        .collectAsStateWithLifecycle(initialValue = true)

    Column(modifier = Modifier.fillMaxSize().padding(horizontal = 24.dp, vertical = 16.dp)) {
        Column(
            modifier = Modifier.weight(1f).fillMaxWidth().verticalScroll(rememberScrollState()),
            verticalArrangement = Arrangement.spacedBy(20.dp),
        ) {
            Text("SETTINGS", style = MaterialTheme.typography.labelSmall, color = LevelColors.TextDim)

            SettingsSection("Calibration") {
                Button(
                    onClick = onOpenSurfaceCalibration,
                    modifier = Modifier.fillMaxWidth(),
                    colors = ButtonDefaults.buttonColors(
                        containerColor = LevelColors.ReadoutPanel,
                        contentColor = LevelColors.Amber,
                    ),
                ) { Text("Calibration Utility") }
            }

            SettingsSection("Units") {
                SingleChoiceSegmentedButtonRow(modifier = Modifier.fillMaxWidth()) {
                    MeasurementUnits.entries.forEachIndexed { index, entry ->
                        SegmentedButton(
                            selected = units == entry,
                            onClick = { container.applicationScope.launch { container.settings.setMeasurementUnits(entry) } },
                            shape = SegmentedButtonDefaults.itemShape(index, MeasurementUnits.entries.size),
                        ) {
                            Text(if (entry == MeasurementUnits.METRIC) "Metric" else "Imperial")
                        }
                    }
                }
            }

            SettingsSection("Feedback & motion") {
                ToggleRow(
                    label = "Haptic feedback",
                    description = "A gentle buzz when the level locks.",
                    checked = hapticsEnabled,
                    onCheckedChange = { container.applicationScope.launch { container.settings.setHapticsEnabled(it) } },
                )
                Spacer(Modifier.height(12.dp))
                ToggleRow(
                    label = "Reduce motion",
                    description = "Snap the bubble instead of springing it.",
                    checked = reducedMotion,
                    onCheckedChange = { container.applicationScope.launch { container.settings.setReducedMotion(it) } },
                )
            }
        }

        Spacer(Modifier.height(12.dp))
        OutlinedButton(
            onClick = onBack,
            modifier = Modifier.fillMaxWidth(),
            border = BorderStroke(1.5.dp, LevelColors.Amber.copy(alpha = .65f)),
            colors = ButtonDefaults.outlinedButtonColors(contentColor = LevelColors.Amber),
        ) { Text("Done") }
    }
}

@Composable
private fun SettingsSection(title: String, content: @Composable () -> Unit) {
    Column(modifier = Modifier.fillMaxWidth()) {
        Text(
            title,
            style = MaterialTheme.typography.titleMedium,
            color = LevelColors.TextPrimary,
            modifier = Modifier.padding(bottom = 10.dp),
        )
        content()
    }
}

@Composable
private fun ToggleRow(
    label: String,
    description: String,
    checked: Boolean,
    onCheckedChange: (Boolean) -> Unit,
) {
    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.CenterVertically,
    ) {
        Column(modifier = Modifier.weight(1f).padding(end = 12.dp)) {
            Text(label, style = MaterialTheme.typography.bodyLarge, color = LevelColors.TextPrimary)
            Text(description, style = MaterialTheme.typography.labelSmall, color = LevelColors.TextDim)
        }
        Switch(
            checked = checked,
            onCheckedChange = onCheckedChange,
            colors = SwitchDefaults.colors(
                checkedThumbColor = LevelColors.Graphite,
                checkedTrackColor = LevelColors.Amber,
            ),
        )
    }
}
