package de.oaa.xxx.app.ui.screens.session

import androidx.compose.foundation.layout.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import de.oaa.xxx.app.data.model.User
import de.oaa.xxx.app.ui.viewmodel.SessionViewModel

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SessionSetupScreen(
    viewModel: SessionViewModel,
    currentUser: User,
    onNavigateBack: () -> Unit,
    onSessionCreated: (String) -> Unit
) {
    val session by viewModel.session.collectAsState()
    val isLoading by viewModel.isLoading.collectAsState()
    val error by viewModel.error.collectAsState()

    var aufgabenProLevel by remember { mutableIntStateOf(5) }
    var wahrscheinlichkeitSperre by remember { mutableIntStateOf(10) }
    var wahrscheinlichkeitStrafe by remember { mutableIntStateOf(10) }
    var zeitfaktor by remember { mutableStateOf(1.0) }

    LaunchedEffect(currentUser.userId) {
        currentUser.userId?.let { viewModel.loadSession(it) }
    }

    LaunchedEffect(session) {
        session?.sessionId?.let { onSessionCreated(it) }
    }

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("BDSM Session") },
                navigationIcon = {
                    IconButton(onClick = onNavigateBack) {
                        Icon(Icons.Default.ArrowBack, contentDescription = "Zurück")
                    }
                }
            )
        }
    ) { padding ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(padding)
                .padding(24.dp),
            verticalArrangement = Arrangement.spacedBy(20.dp)
        ) {
            Text("Session konfigurieren", fontSize = 20.sp, fontWeight = FontWeight.Bold)

            SliderSetting(
                label = "Aufgaben pro Level",
                value = aufgabenProLevel.toFloat(),
                onValueChange = { aufgabenProLevel = it.toInt() },
                valueRange = 1f..20f,
                steps = 18,
                displayValue = "$aufgabenProLevel"
            )

            SliderSetting(
                label = "Wahrscheinlichkeit Sperre",
                value = wahrscheinlichkeitSperre.toFloat(),
                onValueChange = { wahrscheinlichkeitSperre = it.toInt() },
                valueRange = 0f..100f,
                steps = 99,
                displayValue = "$wahrscheinlichkeitSperre%"
            )

            SliderSetting(
                label = "Wahrscheinlichkeit Strafe",
                value = wahrscheinlichkeitStrafe.toFloat(),
                onValueChange = { wahrscheinlichkeitStrafe = it.toInt() },
                valueRange = 0f..100f,
                steps = 99,
                displayValue = "$wahrscheinlichkeitStrafe%"
            )

            SliderSetting(
                label = "Zeitfaktor Strafen",
                value = zeitfaktor.toFloat(),
                onValueChange = { zeitfaktor = it.toDouble() },
                valueRange = 0.1f..5f,
                steps = 48,
                displayValue = String.format("%.1fx", zeitfaktor)
            )

            error?.let {
                Text(text = it, color = MaterialTheme.colorScheme.error)
            }

            Spacer(modifier = Modifier.weight(1f))

            Button(
                onClick = {
                    viewModel.createSession(
                        aufgabenProLevel,
                        wahrscheinlichkeitSperre,
                        wahrscheinlichkeitStrafe,
                        zeitfaktor
                    ) {}
                    currentUser.userId?.let { viewModel.loadSession(it) }
                },
                modifier = Modifier.fillMaxWidth().height(52.dp),
                enabled = !isLoading
            ) {
                if (isLoading) CircularProgressIndicator(modifier = Modifier.size(24.dp))
                else Text("Session starten", fontSize = 16.sp)
            }
        }
    }
}

@Composable
fun SliderSetting(
    label: String,
    value: Float,
    onValueChange: (Float) -> Unit,
    valueRange: ClosedFloatingPointRange<Float>,
    steps: Int,
    displayValue: String
) {
    Column {
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween
        ) {
            Text(label, fontSize = 14.sp)
            Text(displayValue, fontSize = 14.sp, color = MaterialTheme.colorScheme.primary, fontWeight = FontWeight.Bold)
        }
        Slider(
            value = value,
            onValueChange = onValueChange,
            valueRange = valueRange,
            steps = steps,
            modifier = Modifier.fillMaxWidth()
        )
    }
}
