package com.atridad.openclimb.ui.screens

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.selection.selectableGroup
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import com.atridad.openclimb.data.model.*
import com.atridad.openclimb.ui.components.ImagePicker
import com.atridad.openclimb.ui.viewmodel.ClimbViewModel
import kotlinx.coroutines.flow.first
import java.time.LocalDateTime

// Data class for attempt input
data class AttemptInput(
    val problemId: String,
    val result: AttemptResult,
    val highestHold: String = "",
    val notes: String = ""
)

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AddEditGymScreen(
    gymId: String?,
    viewModel: ClimbViewModel,
    onNavigateBack: () -> Unit
) {
    var name by remember { mutableStateOf("") }
    var location by remember { mutableStateOf("") }
    var notes by remember { mutableStateOf("") }
    var selectedClimbTypes by remember { mutableStateOf(setOf<ClimbType>()) }
    var selectedDifficultySystems by remember { mutableStateOf(setOf<DifficultySystem>()) }
    
    val isEditing = gymId != null
    
    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text(if (isEditing) "Edit Gym" else "Add Gym") },
                navigationIcon = {
                    IconButton(onClick = onNavigateBack) {
                        Icon(Icons.Default.ArrowBack, contentDescription = "Back")
                    }
                },
                actions = {
                    TextButton(
                        onClick = {
                            val gym = if (isEditing) {
                                Gym.create(name, location, selectedClimbTypes.toList(), selectedDifficultySystems.toList(), notes = notes)
                            } else {
                                Gym.create(name, location, selectedClimbTypes.toList(), selectedDifficultySystems.toList(), notes = notes)
                            }
                            
                            if (isEditing) {
                                viewModel.updateGym(gym)
                            } else {
                                viewModel.addGym(gym)
                            }
                            onNavigateBack()
                        },
                        enabled = name.isNotBlank() && selectedClimbTypes.isNotEmpty()
                    ) {
                        Text("Save")
                    }
                }
            )
        }
    ) { paddingValues ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
                .padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            // Name field
            OutlinedTextField(
                value = name,
                onValueChange = { name = it },
                label = { Text("Gym Name") },
                modifier = Modifier.fillMaxWidth(),
                singleLine = true
            )
            
            // Location field
            OutlinedTextField(
                value = location,
                onValueChange = { location = it },
                label = { Text("Location (Optional)") },
                modifier = Modifier.fillMaxWidth(),
                singleLine = true
            )
            
            // Climb Types
            Card(
                modifier = Modifier.fillMaxWidth()
            ) {
                Column(
                    modifier = Modifier.padding(16.dp)
                ) {
                    Text(
                        text = "Supported Climb Types",
                        style = MaterialTheme.typography.titleMedium,
                        fontWeight = FontWeight.Bold
                    )
                    
                    Spacer(modifier = Modifier.height(8.dp))
                    
                    ClimbType.entries.forEach { climbType ->
                        Row(
                            verticalAlignment = Alignment.CenterVertically,
                            modifier = Modifier
                                .fillMaxWidth()
                                .selectable(
                                    selected = climbType in selectedClimbTypes,
                                    onClick = {
                                        selectedClimbTypes = if (climbType in selectedClimbTypes) {
                                            selectedClimbTypes - climbType
                                        } else {
                                            selectedClimbTypes + climbType
                                        }
                                    },
                                    role = Role.Checkbox
                                )
                        ) {
                            Checkbox(
                                checked = climbType in selectedClimbTypes,
                                onCheckedChange = null
                            )
                            Spacer(modifier = Modifier.width(8.dp))
                            Text(climbType.name.lowercase().replaceFirstChar { it.uppercase() })
                        }
                    }
                }
            }
            
            // Difficulty Systems
            Card(
                modifier = Modifier.fillMaxWidth()
            ) {
                Column(
                    modifier = Modifier.padding(16.dp)
                ) {
                    Text(
                        text = "Difficulty Systems",
                        style = MaterialTheme.typography.titleMedium,
                        fontWeight = FontWeight.Bold
                    )
                    
                    Spacer(modifier = Modifier.height(8.dp))
                    
                    DifficultySystem.entries.forEach { system ->
                        Row(
                            verticalAlignment = Alignment.CenterVertically,
                            modifier = Modifier
                                .fillMaxWidth()
                                .selectable(
                                    selected = system in selectedDifficultySystems,
                                    onClick = {
                                        selectedDifficultySystems = if (system in selectedDifficultySystems) {
                                            selectedDifficultySystems - system
                                        } else {
                                            selectedDifficultySystems + system
                                        }
                                    },
                                    role = Role.Checkbox
                                )
                        ) {
                            Checkbox(
                                checked = system in selectedDifficultySystems,
                                onCheckedChange = null
                            )
                            Spacer(modifier = Modifier.width(8.dp))
                            Text(system.name)
                        }
                    }
                }
            }
            
            // Notes field
            OutlinedTextField(
                value = notes,
                onValueChange = { notes = it },
                label = { Text("Notes (Optional)") },
                modifier = Modifier.fillMaxWidth(),
                minLines = 3
            )
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AddEditProblemScreen(
    problemId: String?,
    gymId: String?,
    viewModel: ClimbViewModel,
    onNavigateBack: () -> Unit
) {
    val isEditing = problemId != null
    val gyms by viewModel.gyms.collectAsState()
    
    // Problem form state
    var selectedGym by remember { mutableStateOf<Gym?>(gymId?.let { id -> gyms.find { it.id == id } }) }
    var problemName by remember { mutableStateOf("") }
    var description by remember { mutableStateOf("") }
    var selectedClimbType by remember { mutableStateOf(ClimbType.BOULDER) }
    var selectedDifficultySystem by remember { mutableStateOf(DifficultySystem.V_SCALE) }
    var difficultyGrade by remember { mutableStateOf("") }
    var setter by remember { mutableStateOf("") }
    var location by remember { mutableStateOf("") }
    var tags by remember { mutableStateOf("") }
    var notes by remember { mutableStateOf("") }
    var isActive by remember { mutableStateOf(true) }
    var imagePaths by remember { mutableStateOf<List<String>>(emptyList()) }
    
    // Load existing problem data for editing
    LaunchedEffect(problemId) {
        if (problemId != null) {
            val existingProblem = viewModel.getProblemById(problemId).first()
            existingProblem?.let { p ->
                problemName = p.name ?: ""
                description = p.description ?: ""
                selectedClimbType = p.climbType
                selectedDifficultySystem = p.difficulty.system
                difficultyGrade = p.difficulty.grade
                setter = p.setter ?: ""
                location = p.location ?: ""
                tags = p.tags.joinToString(", ")
                notes = p.notes ?: ""
                isActive = p.isActive
                imagePaths = p.imagePaths
            }
        }
    }
    
    LaunchedEffect(gymId, gyms) {
        if (gymId != null && selectedGym == null) {
            selectedGym = gyms.find { it.id == gymId }
        }
    }
    
    val availableDifficultySystems = selectedGym?.difficultySystems ?: DifficultySystem.entries.toList()
    val availableClimbTypes = selectedGym?.supportedClimbTypes ?: ClimbType.entries.toList()
    
    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text(if (isEditing) "Edit Problem" else "Add Problem") },
                navigationIcon = {
                    IconButton(onClick = onNavigateBack) {
                        Icon(Icons.Default.ArrowBack, contentDescription = "Back")
                    }
                },
                actions = {
                    TextButton(
                        onClick = {
                            selectedGym?.let { gym ->
                                val difficulty = DifficultyGrade(
                                    system = selectedDifficultySystem,
                                    grade = difficultyGrade,
                                    numericValue = when (selectedDifficultySystem) {
                                        DifficultySystem.V_SCALE -> difficultyGrade.removePrefix("V").toIntOrNull() ?: 0
                                        else -> difficultyGrade.hashCode() % 100 // Simple mapping for other systems
                                    }
                                )
                                
                                val problem = Problem.create(
                                    gymId = gym.id,
                                    name = problemName.ifBlank { null },
                                    description = description.ifBlank { null },
                                    climbType = selectedClimbType,
                                    difficulty = difficulty,
                                    setter = setter.ifBlank { null },
                                    tags = tags.split(",").map { it.trim() }.filter { it.isNotBlank() },
                                    location = location.ifBlank { null },
                                    imagePaths = imagePaths,
                                    notes = notes.ifBlank { null }
                                )
                                
                                if (isEditing) {
                                    viewModel.updateProblem(problem.copy(id = problemId!!))
                                } else {
                                    viewModel.addProblem(problem)
                                }
                                onNavigateBack()
                            }
                        },
                        enabled = selectedGym != null && difficultyGrade.isNotBlank()
                    ) {
                        Text("Save")
                    }
                }
            )
        }
    ) { paddingValues ->
        LazyColumn(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
                .padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            // Gym Selection
            item {
                Card(
                    modifier = Modifier.fillMaxWidth()
                ) {
                    Column(
                        modifier = Modifier.padding(16.dp)
                    ) {
                        Text(
                            text = "Select Gym",
                            style = MaterialTheme.typography.titleMedium,
                            fontWeight = FontWeight.Bold
                        )
                        
                        Spacer(modifier = Modifier.height(8.dp))
                        
                        if (gyms.isEmpty()) {
                            Text(
                                text = "No gyms available. Add a gym first.",
                                style = MaterialTheme.typography.bodyMedium,
                                color = MaterialTheme.colorScheme.error
                            )
                        } else {
                            LazyRow(
                                horizontalArrangement = Arrangement.spacedBy(8.dp)
                            ) {
                                items(gyms) { gym ->
                                    FilterChip(
                                        onClick = { selectedGym = gym },
                                        label = { Text(gym.name) },
                                        selected = selectedGym?.id == gym.id
                                    )
                                }
                            }
                        }
                    }
                }
            }
            
            // Basic Problem Info
            item {
                Card(
                    modifier = Modifier.fillMaxWidth()
                ) {
                    Column(
                        modifier = Modifier.padding(16.dp)
                    ) {
                        Text(
                            text = "Problem Details",
                            style = MaterialTheme.typography.titleMedium,
                            fontWeight = FontWeight.Bold
                        )
                        
                        Spacer(modifier = Modifier.height(16.dp))
                        
                        OutlinedTextField(
                            value = problemName,
                            onValueChange = { problemName = it },
                            label = { Text("Problem Name (Optional)") },
                            modifier = Modifier.fillMaxWidth(),
                            singleLine = true,
                            placeholder = { Text("e.g., 'The Overhang Monster', 'Yellow V4'") }
                        )
                        
                        Spacer(modifier = Modifier.height(8.dp))
                        
                        OutlinedTextField(
                            value = description,
                            onValueChange = { description = it },
                            label = { Text("Description (Optional)") },
                            modifier = Modifier.fillMaxWidth(),
                            minLines = 2,
                            placeholder = { Text("Describe the problem, holds, style, etc.") }
                        )
                        
                        Spacer(modifier = Modifier.height(8.dp))
                        
                        OutlinedTextField(
                            value = setter,
                            onValueChange = { setter = it },
                            label = { Text("Route Setter (Optional)") },
                            modifier = Modifier.fillMaxWidth(),
                            singleLine = true
                        )
                        
                        Spacer(modifier = Modifier.height(8.dp))
                        
                        OutlinedTextField(
                            value = location,
                            onValueChange = { location = it },
                            label = { Text("Location (Optional)") },
                            modifier = Modifier.fillMaxWidth(),
                            singleLine = true,
                            placeholder = { Text("e.g., 'Cave area', 'Wall 3', 'Right side'") }
                        )
                    }
                }
            }
            
            // Climb Type
            if (selectedGym != null) {
                item {
                    Card(
                        modifier = Modifier.fillMaxWidth()
                    ) {
                        Column(
                            modifier = Modifier.padding(16.dp)
                        ) {
                            Text(
                                text = "Climb Type",
                                style = MaterialTheme.typography.titleMedium,
                                fontWeight = FontWeight.Bold
                            )
                            
                            Spacer(modifier = Modifier.height(8.dp))
                            
                            Row(
                                horizontalArrangement = Arrangement.spacedBy(8.dp)
                            ) {
                                availableClimbTypes.forEach { climbType ->
                                    FilterChip(
                                        onClick = { selectedClimbType = climbType },
                                        label = { Text(climbType.name.lowercase().replaceFirstChar { it.uppercase() }) },
                                        selected = selectedClimbType == climbType
                                    )
                                }
                            }
                        }
                    }
                }
            }
            
            // Difficulty
            if (selectedGym != null) {
                item {
                    Card(
                        modifier = Modifier.fillMaxWidth()
                    ) {
                        Column(
                            modifier = Modifier.padding(16.dp)
                        ) {
                            Text(
                                text = "Difficulty",
                                style = MaterialTheme.typography.titleMedium,
                                fontWeight = FontWeight.Bold
                            )
                            
                            Spacer(modifier = Modifier.height(8.dp))
                            
                            Text(
                                text = "Difficulty System",
                                style = MaterialTheme.typography.bodyMedium,
                                fontWeight = FontWeight.Medium
                            )
                            
                            LazyRow(
                                horizontalArrangement = Arrangement.spacedBy(8.dp)
                            ) {
                                items(availableDifficultySystems) { system ->
                                    FilterChip(
                                        onClick = { selectedDifficultySystem = system },
                                        label = { Text(system.name) },
                                        selected = selectedDifficultySystem == system
                                    )
                                }
                            }
                            
                            Spacer(modifier = Modifier.height(8.dp))
                            
                            OutlinedTextField(
                                value = difficultyGrade,
                                onValueChange = { difficultyGrade = it },
                                label = { Text("Grade *") },
                                modifier = Modifier.fillMaxWidth(),
                                singleLine = true,
                                placeholder = { 
                                    Text(when (selectedDifficultySystem) {
                                        DifficultySystem.V_SCALE -> "e.g., V0, V4, V10"
                                        DifficultySystem.FONT -> "e.g., 3, 6A+, 8B"
                                        DifficultySystem.YDS -> "e.g., 5.8, 5.12a"
                                        DifficultySystem.FRENCH -> "e.g., 6a, 7c+"
                                        DifficultySystem.CUSTOM -> "Custom grade"
                                        else -> "Enter grade"
                                    }) 
                                }
                            )
                        }
                    }
                }
            }
            
            // Images Section
            item {
                Card(
                    modifier = Modifier.fillMaxWidth()
                ) {
                    Column(
                        modifier = Modifier.padding(16.dp)
                    ) {
                        Text(
                            text = "Photos",
                            style = MaterialTheme.typography.titleMedium,
                            fontWeight = FontWeight.Bold
                        )
                        
                        Spacer(modifier = Modifier.height(16.dp))
                        
                        ImagePicker(
                            imageUris = imagePaths,
                            onImagesChanged = { imagePaths = it },
                            maxImages = 5
                        )
                    }
                }
            }

            item {
                Card(
                    modifier = Modifier.fillMaxWidth()
                ) {
                    Column(
                        modifier = Modifier.padding(16.dp)
                    ) {
                        Text(
                            text = "Additional Info",
                            style = MaterialTheme.typography.titleMedium,
                            fontWeight = FontWeight.Bold
                        )
                        
                        Spacer(modifier = Modifier.height(16.dp))
                        
                        OutlinedTextField(
                            value = tags,
                            onValueChange = { tags = it },
                            label = { Text("Tags (Optional)") },
                            modifier = Modifier.fillMaxWidth(),
                            singleLine = true,
                            placeholder = { Text("e.g., overhang, crimpy, dynamic (comma-separated)") }
                        )
                        
                        Spacer(modifier = Modifier.height(8.dp))
                        
                        OutlinedTextField(
                            value = notes,
                            onValueChange = { notes = it },
                            label = { Text("Notes (Optional)") },
                            modifier = Modifier.fillMaxWidth(),
                            minLines = 3,
                            placeholder = { Text("Any additional notes about this problem") }
                        )
                        
                        Spacer(modifier = Modifier.height(16.dp))
                        
                        Row(
                            verticalAlignment = Alignment.CenterVertically,
                            modifier = Modifier
                                .fillMaxWidth()
                                .selectable(
                                    selected = isActive,
                                    onClick = { isActive = !isActive },
                                    role = Role.Checkbox
                                )
                        ) {
                            Checkbox(
                                checked = isActive,
                                onCheckedChange = null
                            )
                            Spacer(modifier = Modifier.width(8.dp))
                            Text(
                                text = "Problem is currently active",
                                style = MaterialTheme.typography.bodyMedium
                            )
                        }
                    }
                }
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AddEditSessionScreen(
    sessionId: String?,
    gymId: String?,
    viewModel: ClimbViewModel,
    onNavigateBack: () -> Unit
) {
    val isEditing = sessionId != null
    val gyms by viewModel.gyms.collectAsState()
    val problems by viewModel.problems.collectAsState()
    
    // Session form state
    var selectedGym by remember { mutableStateOf<Gym?>(gymId?.let { id -> gyms.find { it.id == id } }) }
    var sessionDate by remember { mutableStateOf(LocalDateTime.now().toLocalDate().toString()) }
    var duration by remember { mutableStateOf("") }
    var sessionNotes by remember { mutableStateOf("") }
    
    // Attempt tracking state
    var attempts by remember { mutableStateOf(listOf<AttemptInput>()) }
    var showAddAttemptDialog by remember { mutableStateOf(false) }
    
    LaunchedEffect(gymId, gyms) {
        if (gymId != null && selectedGym == null) {
            selectedGym = gyms.find { it.id == gymId }
        }
    }
    
    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text(if (isEditing) "Edit Session" else "Add Session") },
                navigationIcon = {
                    IconButton(onClick = onNavigateBack) {
                        Icon(Icons.Default.ArrowBack, contentDescription = "Back")
                    }
                },
                actions = {
                    TextButton(
                        onClick = {
                            selectedGym?.let { gym ->
                                val session = ClimbSession.create(
                                    gymId = gym.id,
                                    notes = sessionNotes.ifBlank { null }
                                )
                                
                                if (isEditing) {
                                    viewModel.updateSession(session.copy(id = sessionId!!))
                                } else {
                                    viewModel.addSession(session)
                                    
                                    attempts.forEach { attemptInput ->
                                        val attempt = Attempt.create(
                                            sessionId = session.id,
                                            problemId = attemptInput.problemId,
                                            result = attemptInput.result,
                                            highestHold = attemptInput.highestHold.ifBlank { null },
                                            notes = attemptInput.notes.ifBlank { null }
                                        )
                                        viewModel.addAttempt(attempt)
                                    }
                                }
                                onNavigateBack()
                            }
                        },
                        enabled = selectedGym != null
                    ) {
                        Text("Save")
                    }
                }
            )
        },
        floatingActionButton = {
            if (selectedGym != null) {
                FloatingActionButton(
                    onClick = { showAddAttemptDialog = true }
                ) {
                    Icon(Icons.Default.Add, contentDescription = "Add Attempt")
                }
            }
        }
    ) { paddingValues ->
        LazyColumn(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
                .padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            // Gym Selection
            item {
                Card(
                    modifier = Modifier.fillMaxWidth()
                ) {
                    Column(
                        modifier = Modifier.padding(16.dp)
                    ) {
                        Text(
                            text = "Select Gym",
                            style = MaterialTheme.typography.titleMedium,
                            fontWeight = FontWeight.Bold
                        )
                        
                        Spacer(modifier = Modifier.height(8.dp))
                        
                        if (gyms.isEmpty()) {
                            Text(
                                text = "No gyms available. Add a gym first.",
                                style = MaterialTheme.typography.bodyMedium,
                                color = MaterialTheme.colorScheme.error
                            )
                        } else {
                            LazyRow(
                                horizontalArrangement = Arrangement.spacedBy(8.dp)
                            ) {
                                items(gyms) { gym ->
                                    FilterChip(
                                        onClick = { selectedGym = gym },
                                        label = { Text(gym.name) },
                                        selected = selectedGym?.id == gym.id
                                    )
                                }
                            }
                        }
                    }
                }
            }
            
            // Session Details
            item {
                Card(
                    modifier = Modifier.fillMaxWidth()
                ) {
                    Column(
                        modifier = Modifier.padding(16.dp)
                    ) {
                        Text(
                            text = "Session Details",
                            style = MaterialTheme.typography.titleMedium,
                            fontWeight = FontWeight.Bold
                        )
                        
                        Spacer(modifier = Modifier.height(16.dp))
                        
                        OutlinedTextField(
                            value = sessionDate,
                            onValueChange = { sessionDate = it },
                            label = { Text("Date (YYYY-MM-DD)") },
                            modifier = Modifier.fillMaxWidth(),
                            singleLine = true
                        )
                        
                        Spacer(modifier = Modifier.height(8.dp))
                        
                        OutlinedTextField(
                            value = duration,
                            onValueChange = { duration = it },
                            label = { Text("Duration (minutes)") },
                            modifier = Modifier.fillMaxWidth(),
                            singleLine = true,
                            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
                        )
                        
                        Spacer(modifier = Modifier.height(8.dp))
                        
                        OutlinedTextField(
                            value = sessionNotes,
                            onValueChange = { sessionNotes = it },
                            label = { Text("Session Notes (Optional)") },
                            modifier = Modifier.fillMaxWidth(),
                            minLines = 3
                        )
                    }
                }
            }
            
            // Attempts Section
            item {
                Card(
                    modifier = Modifier.fillMaxWidth()
                ) {
                    Column(
                        modifier = Modifier.padding(16.dp)
                    ) {
                        Row(
                            modifier = Modifier.fillMaxWidth(),
                            horizontalArrangement = Arrangement.SpaceBetween,
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Text(
                                text = "Attempts (${attempts.size})",
                                style = MaterialTheme.typography.titleMedium,
                                fontWeight = FontWeight.Bold
                            )
                            

                        }
                        
                        if (attempts.isEmpty()) {
                            Spacer(modifier = Modifier.height(8.dp))
                            Text(
                                text = "No attempts recorded yet. Add an attempt to track your progress.",
                                style = MaterialTheme.typography.bodyMedium,
                                color = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                        }
                    }
                }
            }
            
            // Attempts List
            items(attempts.size) { index ->
                val attempt = attempts[index]
                val problem = problems.find { it.id == attempt.problemId }
                
                Card(
                    modifier = Modifier.fillMaxWidth()
                ) {
                    Column(
                        modifier = Modifier.padding(16.dp)
                    ) {
                        Row(
                            modifier = Modifier.fillMaxWidth(),
                            horizontalArrangement = Arrangement.SpaceBetween,
                            verticalAlignment = Alignment.Top
                        ) {
                            Column(modifier = Modifier.weight(1f)) {
                                Text(
                                    text = problem?.name ?: "Unknown Problem",
                                    style = MaterialTheme.typography.titleSmall,
                                    fontWeight = FontWeight.Bold
                                )
                                
                                problem?.difficulty?.let { difficulty ->
                                    Text(
                                        text = "${difficulty.system.name}: ${difficulty.grade}",
                                        style = MaterialTheme.typography.bodySmall,
                                        color = MaterialTheme.colorScheme.primary
                                    )
                                }
                                
                                Text(
                                    text = "Result: ${attempt.result.name.lowercase().replaceFirstChar { it.uppercase() }}",
                                    style = MaterialTheme.typography.bodyMedium,
                                    color = when (attempt.result) {
                                        AttemptResult.SUCCESS, AttemptResult.FLASH, 
                                        AttemptResult.REDPOINT, AttemptResult.ONSIGHT -> MaterialTheme.colorScheme.primary
                                        else -> MaterialTheme.colorScheme.onSurfaceVariant
                                    }
                                )
                                
                                if (attempt.highestHold.isNotBlank()) {
                                    Text(
                                        text = "Highest hold: ${attempt.highestHold}",
                                        style = MaterialTheme.typography.bodySmall,
                                        color = MaterialTheme.colorScheme.onSurfaceVariant
                                    )
                                }
                                
                                if (attempt.notes.isNotBlank()) {
                                    Text(
                                        text = attempt.notes,
                                        style = MaterialTheme.typography.bodySmall,
                                        color = MaterialTheme.colorScheme.onSurfaceVariant
                                    )
                                }
                            }
                            
                            IconButton(
                                onClick = {
                                    attempts = attempts.toMutableList().apply { removeAt(index) }
                                }
                            ) {
                                Icon(Icons.Default.Delete, contentDescription = "Remove attempt")
                            }
                        }
                    }
                }
            }
        }
    }
    
    if (showAddAttemptDialog && selectedGym != null) {
        AddAttemptDialog(
            problems = problems.filter { it.gymId == selectedGym!!.id && it.isActive },
            onDismiss = { showAddAttemptDialog = false },
            onAddAttempt = { attemptInput ->
                attempts = attempts + attemptInput
                showAddAttemptDialog = false
            }
        )
    }
}



@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AddAttemptDialog(
    problems: List<Problem>,
    onDismiss: () -> Unit,
    onAddAttempt: (AttemptInput) -> Unit
) {
    var selectedProblem by remember { mutableStateOf<Problem?>(null) }
    var selectedResult by remember { mutableStateOf(AttemptResult.FALL) }
    var highestHold by remember { mutableStateOf("") }
    var notes by remember { mutableStateOf("") }
    
    Dialog(onDismissRequest = onDismiss) {
        Card(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp)
        ) {
            Column(
                modifier = Modifier.padding(24.dp),
                verticalArrangement = Arrangement.spacedBy(16.dp)
            ) {
                Text(
                    text = "Add Attempt",
                    style = MaterialTheme.typography.headlineSmall,
                    fontWeight = FontWeight.Bold
                )
                
                // Problem Selection
                Text(
                    text = "Problem",
                    style = MaterialTheme.typography.titleMedium,
                    fontWeight = FontWeight.Medium
                )
                
                if (problems.isEmpty()) {
                    Text(
                        text = "No active problems in this gym. Add some problems first.",
                        style = MaterialTheme.typography.bodyMedium,
                        color = MaterialTheme.colorScheme.error
                    )
                } else {
                    LazyColumn(
                        modifier = Modifier.height(120.dp),
                        verticalArrangement = Arrangement.spacedBy(4.dp)
                    ) {
                        items(problems) { problem ->
                            Card(
                                onClick = { selectedProblem = problem },
                                colors = CardDefaults.cardColors(
                                    containerColor = if (selectedProblem?.id == problem.id) 
                                        MaterialTheme.colorScheme.primaryContainer 
                                    else MaterialTheme.colorScheme.surface
                                ),
                                modifier = Modifier.fillMaxWidth()
                            ) {
                                Column(
                                    modifier = Modifier.padding(12.dp)
                                ) {
                                    Text(
                                        text = problem.name ?: "Unnamed Problem",
                                        style = MaterialTheme.typography.bodyMedium,
                                        fontWeight = FontWeight.Medium
                                    )
                                    Text(
                                        text = "${problem.difficulty.system.name}: ${problem.difficulty.grade}",
                                        style = MaterialTheme.typography.bodySmall,
                                        color = MaterialTheme.colorScheme.primary
                                    )
                                }
                            }
                        }
                    }
                }
                
                // Result Selection
                Text(
                    text = "Result",
                    style = MaterialTheme.typography.titleMedium,
                    fontWeight = FontWeight.Medium
                )
                
                Column(modifier = Modifier.selectableGroup()) {
                    AttemptResult.entries.forEach { result ->
                        Row(
                            verticalAlignment = Alignment.CenterVertically,
                            modifier = Modifier
                                .fillMaxWidth()
                                .selectable(
                                    selected = selectedResult == result,
                                    onClick = { selectedResult = result },
                                    role = Role.RadioButton
                                )
                        ) {
                            RadioButton(
                                selected = selectedResult == result,
                                onClick = null
                            )
                            Spacer(modifier = Modifier.width(8.dp))
                            Text(
                                text = result.name.lowercase().replaceFirstChar { it.uppercase() },
                                style = MaterialTheme.typography.bodyMedium
                            )
                        }
                    }
                }
                
                // Highest Hold
                OutlinedTextField(
                    value = highestHold,
                    onValueChange = { highestHold = it },
                    label = { Text("Highest Hold (Optional)") },
                    modifier = Modifier.fillMaxWidth(),
                    singleLine = true,
                    placeholder = { Text("e.g., 'jugs near the top', 'crux move'") }
                )
                
                // Notes
                OutlinedTextField(
                    value = notes,
                    onValueChange = { notes = it },
                    label = { Text("Notes (Optional)") },
                    modifier = Modifier.fillMaxWidth(),
                    minLines = 2,
                    placeholder = { Text("e.g., 'need to work on heel hooks', 'pumped out'") }
                )
                
                // Buttons
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    TextButton(
                        onClick = onDismiss,
                        modifier = Modifier.weight(1f)
                    ) {
                        Text("Cancel")
                    }
                    
                    Button(
                        onClick = {
                            selectedProblem?.let { problem ->
                                onAddAttempt(
                                    AttemptInput(
                                        problemId = problem.id,
                                        result = selectedResult,
                                        highestHold = highestHold,
                                        notes = notes
                                    )
                                )
                            }
                        },
                        enabled = selectedProblem != null,
                        modifier = Modifier.weight(1f)
                    ) {
                        Text("Add Attempt")
                    }
                }
            }
        }
    }
}
