package com.atridad.magiccounter.ui.screens

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.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.material.icons.Icons
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material3.Button
import androidx.compose.material3.Checkbox
import androidx.compose.material3.Icon
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Slider
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.atridad.magiccounter.ui.state.GameState
import com.atridad.magiccounter.ui.state.PlayerState
import com.atridad.magiccounter.ui.state.defaultPlayerName
import kotlin.math.roundToInt

@Composable
fun SetupScreen(
    modifier: Modifier = Modifier,
    onStart: (String, GameState) -> Unit
) {
    var playerCount by remember { mutableIntStateOf(4) }
    var startingLife by remember { mutableIntStateOf(40) }
    var trackPoison by remember { mutableStateOf(true) }
    var trackCommander by remember { mutableStateOf(true) }
    var matchName by remember { mutableStateOf("") }

    val names = remember { mutableStateListOf<String>() }
    LaunchedEffect(playerCount) {
        while (names.size < playerCount) names.add(defaultPlayerName(names.size))
        while (names.size > playerCount) names.removeAt(names.lastIndex)
    }

    Column(
        modifier = modifier
            .padding(24.dp)
            .verticalScroll(rememberScrollState()),
        verticalArrangement = Arrangement.spacedBy(24.dp)
    ) {
        // Game Settings Section
        Column(verticalArrangement = Arrangement.spacedBy(16.dp)) {
            Text(
                "Game Settings",
                style = androidx.compose.material3.MaterialTheme.typography.headlineSmall,
                color = androidx.compose.material3.MaterialTheme.colorScheme.primary
            )
            
            Column(verticalArrangement = Arrangement.spacedBy(16.dp)) {
                Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
                    Text(
                        "Starting life: $startingLife",
                        style = androidx.compose.material3.MaterialTheme.typography.titleMedium
                    )
                    Slider(
                        value = startingLife.toFloat(),
                        onValueChange = {
                            val snapped = ((it / 5f).roundToInt() * 5).coerceIn(10, 40)
                            startingLife = snapped
                        },
                        valueRange = 10f..40f,
                        steps = 5
                    )
                }
                
                Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
                    Text(
                        "Players: $playerCount",
                        style = androidx.compose.material3.MaterialTheme.typography.titleMedium
                    )
                    Slider(
                        value = playerCount.toFloat(), 
                        onValueChange = { playerCount = it.toInt() }, 
                        valueRange = 2f..8f, 
                        steps = 6
                    )
                }
            }
        }

        // Game Options Section
        Column(verticalArrangement = Arrangement.spacedBy(16.dp)) {
            Text(
                "Game Options",
                style = androidx.compose.material3.MaterialTheme.typography.headlineSmall,
                color = androidx.compose.material3.MaterialTheme.colorScheme.primary
            )
            
            Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
                Row(verticalAlignment = Alignment.CenterVertically) {
                    Checkbox(checked = trackCommander, onCheckedChange = { trackCommander = it })
                    Text(
                        "Track commander damage",
                        style = androidx.compose.material3.MaterialTheme.typography.bodyLarge
                    )
                }
                Row(verticalAlignment = Alignment.CenterVertically) {
                    Checkbox(checked = trackPoison, onCheckedChange = { trackPoison = it })
                    Text(
                        "Track poison",
                        style = androidx.compose.material3.MaterialTheme.typography.bodyLarge
                    )
                }
            }
        }

        // Match Details Section
        Column(verticalArrangement = Arrangement.spacedBy(16.dp)) {
            Text(
                "Match Details",
                style = androidx.compose.material3.MaterialTheme.typography.headlineSmall,
                color = androidx.compose.material3.MaterialTheme.colorScheme.primary
            )
            
            OutlinedTextField(
                modifier = Modifier.fillMaxWidth(),
                value = matchName,
                onValueChange = { matchName = it },
                label = { Text("Match name") },
                singleLine = true
            )

            Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
                names.forEachIndexed { index, value ->
                    OutlinedTextField(
                        modifier = Modifier.fillMaxWidth(),
                        value = value,
                        onValueChange = { names[index] = it },
                        label = { Text("Player ${index + 1} name") },
                        singleLine = true
                    )
                }
            }
        }

        Spacer(modifier = Modifier.height(16.dp))
        
        // Note: The actual start button is now handled by a FAB in the parent Scaffold
        // This button is kept for accessibility and as a fallback
        val canStart = matchName.isNotBlank()
        Button(
            onClick = {
                val players = names.mapIndexed { index, name ->
                    PlayerState(
                        id = index,
                        name = name.ifBlank { defaultPlayerName(index) },
                        life = startingLife,
                        poison = 0,
                        commanderDamages = emptyMap()
                    )
                }
                onStart(
                    matchName,
                    GameState(
                        players = players,
                        startingLife = startingLife,
                        trackPoison = trackPoison,
                        trackCommanderDamage = trackCommander
                    )
                )
            }, 
            enabled = canStart,
            modifier = Modifier.fillMaxWidth(),
            contentPadding = androidx.compose.foundation.layout.PaddingValues(16.dp)
        ) {
            Icon(Icons.Default.PlayArrow, contentDescription = null)
            Spacer(modifier = Modifier.padding(8.dp))
            Text("Start Game", style = androidx.compose.material3.MaterialTheme.typography.titleMedium)
        }
    }
}


