package com.atridad.openclimb.ui.screens

import androidx.compose.foundation.BorderStroke
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.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material.icons.filled.Share
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.unit.dp
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.window.Dialog
import com.atridad.openclimb.ui.components.FullscreenImageViewer
import com.atridad.openclimb.ui.components.ImageDisplaySection
import com.atridad.openclimb.ui.viewmodel.ClimbViewModel
import com.atridad.openclimb.data.model.*
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import androidx.lifecycle.viewModelScope
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SessionDetailScreen(
    sessionId: String,
    viewModel: ClimbViewModel,
    onNavigateBack: () -> Unit,
    onNavigateToEdit: (String) -> Unit
) {
    val context = LocalContext.current
    val attempts by viewModel.getAttemptsBySession(sessionId).collectAsState(initial = emptyList())
    val sessions by viewModel.sessions.collectAsState()
    val problems by viewModel.problems.collectAsState()
    val gyms by viewModel.gyms.collectAsState()
    
    var isGeneratingShare by remember { mutableStateOf(false) }
    var showDeleteDialog by remember { mutableStateOf(false) }
    var showAddAttemptDialog by remember { mutableStateOf(false) }
    
    // Get session details
    val session = sessions.find { it.id == sessionId }
    val gym = session?.let { s -> gyms.find { it.id == s.gymId } }
    
    // Calculate stats
    val successfulAttempts = attempts.filter { 
        it.result in listOf(AttemptResult.SUCCESS, AttemptResult.FLASH, AttemptResult.REDPOINT, AttemptResult.ONSIGHT) 
    }
    val uniqueProblems = attempts.map { it.problemId }.distinct()
    val attemptedProblems = problems.filter { it.id in uniqueProblems }
    val completedProblems = successfulAttempts.map { it.problemId }.distinct()
    
    val attemptsWithProblems = attempts.mapNotNull { attempt ->
        val problem = problems.find { it.id == attempt.problemId }
        if (problem != null) attempt to problem else null
    }.sortedByDescending { attempt -> 
        // Sort by result priority, then by timestamp
        when (attempt.first.result) {
            AttemptResult.ONSIGHT -> 5
            AttemptResult.FLASH -> 4
            AttemptResult.REDPOINT -> 3
            AttemptResult.SUCCESS -> 2
            AttemptResult.FALL -> 1
            else -> 0
        }
    }
    
    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("Session Details") },
                navigationIcon = {
                    IconButton(onClick = onNavigateBack) {
                        Icon(Icons.Default.ArrowBack, contentDescription = "Back")
                    }
                },
                actions = {
                    // Share button
                    if (session?.duration != null) { // Only show for completed sessions
                        IconButton(
                            onClick = {
                                isGeneratingShare = true
                                viewModel.viewModelScope.launch {
                                    val shareFile = viewModel.generateSessionShareCard(context, sessionId)
                                    isGeneratingShare = false
                                    shareFile?.let { file ->
                                        viewModel.shareSessionCard(context, file)
                                    }
                                }
                            },
                            enabled = !isGeneratingShare
                        ) {
                            if (isGeneratingShare) {
                                CircularProgressIndicator(
                                    modifier = Modifier.size(20.dp),
                                    strokeWidth = 2.dp
                                )
                            } else {
                                Icon(
                                    imageVector = Icons.Default.Share,
                                    contentDescription = "Share Session"
                                )
                            }
                        }
                    }
                    
                    IconButton(onClick = { showDeleteDialog = true }) {
                        Icon(Icons.Default.Delete, contentDescription = "Delete")
                    }
                    
                    IconButton(onClick = { onNavigateToEdit(sessionId) }) {
                        Icon(Icons.Default.Edit, contentDescription = "Edit")
                    }
                }
            )
        },
        floatingActionButton = {
            // Show FAB only for active sessions (those without duration)
            if (session?.duration == 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)
        ) {
            // Session Header
            item {
                Card(
                    modifier = Modifier.fillMaxWidth()
                ) {
                    Column(
                        modifier = Modifier.padding(20.dp)
                    ) {
                        Text(
                            text = gym?.name ?: "Unknown Gym",
                            style = MaterialTheme.typography.headlineMedium,
                            fontWeight = FontWeight.Bold
                        )
                        
                        Spacer(modifier = Modifier.height(8.dp))
                        
                        Text(
                            text = formatDate(session?.date ?: ""),
                            style = MaterialTheme.typography.titleLarge,
                            color = MaterialTheme.colorScheme.primary
                        )
                        
                        session?.let { s ->
                            if (s.duration != null) {
                                Spacer(modifier = Modifier.height(8.dp))
                                
                                val timeText = "Duration: ${s.duration} minutes"
                                
                                Text(
                                    text = timeText,
                                    style = MaterialTheme.typography.bodyMedium,
                                    color = MaterialTheme.colorScheme.onSurfaceVariant
                                )
                            }
                        }
                        
                        session?.notes?.let { notes ->
                            Spacer(modifier = Modifier.height(12.dp))
                            Text(
                                text = notes,
                                style = MaterialTheme.typography.bodyMedium
                            )
                        }
                        
                        // Session status indicator
                        Spacer(modifier = Modifier.height(12.dp))
                        
                        Surface(
                            color = if (session?.duration != null) 
                                MaterialTheme.colorScheme.primaryContainer 
                            else 
                                MaterialTheme.colorScheme.secondaryContainer,
                            shape = RoundedCornerShape(12.dp)
                        ) {
                            Text(
                                text = if (session?.duration != null) "Completed" else "In Progress",
                                modifier = Modifier.padding(horizontal = 12.dp, vertical = 6.dp),
                                style = MaterialTheme.typography.labelMedium,
                                color = if (session?.duration != null) 
                                    MaterialTheme.colorScheme.onPrimaryContainer 
                                else 
                                    MaterialTheme.colorScheme.onSecondaryContainer,
                                fontWeight = FontWeight.Medium
                            )
                        }
                    }
                }
            }
            
            // Stats Summary
            item {
                Card(
                    modifier = Modifier.fillMaxWidth()
                ) {
                    Column(
                        modifier = Modifier.padding(20.dp)
                    ) {
                        Text(
                            text = "Session Stats",
                            style = MaterialTheme.typography.titleLarge,
                            fontWeight = FontWeight.Bold
                        )
                        
                        Spacer(modifier = Modifier.height(16.dp))
                        
                        if (attempts.isEmpty()) {
                            Text(
                                text = "No attempts recorded yet",
                                style = MaterialTheme.typography.bodyMedium,
                                color = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                        } else {
                            Row(
                                modifier = Modifier.fillMaxWidth(),
                                horizontalArrangement = Arrangement.SpaceEvenly
                            ) {
                                StatItem(
                                    label = "Total Attempts",
                                    value = attempts.size.toString()
                                )
                                StatItem(
                                    label = "Problems",
                                    value = uniqueProblems.size.toString()
                                )
                                StatItem(
                                    label = "Successful",
                                    value = successfulAttempts.size.toString()
                                )
                            }
                            
                            Spacer(modifier = Modifier.height(16.dp))
                            
                            Row(
                                modifier = Modifier.fillMaxWidth(),
                                horizontalArrangement = Arrangement.SpaceEvenly
                            ) {
                                StatItem(
                                    label = "Completed",
                                    value = completedProblems.size.toString()
                                )
                                StatItem(
                                    label = "Success Rate",
                                    value = "${((successfulAttempts.size.toDouble() / attempts.size) * 100).toInt()}%"
                                )
                                
                                // Show grade range if available
                                val grades = attemptedProblems.map { it.difficulty.grade }
                                if (grades.isNotEmpty()) {
                                    StatItem(
                                        label = "Grade Range",
                                        value = "${grades.minOrNull()} - ${grades.maxOrNull()}"
                                    )
                                } else {
                                    StatItem(
                                        label = "Grade Range",
                                        value = "N/A"
                                    )
                                }
                            }
                        }
                    }
                }
            }
            
            // Attempts List
            item {
                Text(
                    text = "Attempts (${attempts.size})",
                    style = MaterialTheme.typography.titleLarge,
                    fontWeight = FontWeight.Bold
                )
            }
            
            if (attemptsWithProblems.isEmpty()) {
                item {
                    Card(
                        modifier = Modifier.fillMaxWidth()
                    ) {
                        Column(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(20.dp),
                            horizontalAlignment = Alignment.CenterHorizontally
                        ) {
                            Text(
                                text = "No attempts yet",
                                style = MaterialTheme.typography.titleMedium,
                                color = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                            Spacer(modifier = Modifier.height(8.dp))
                            Text(
                                text = "Start attempting problems to see your progress!",
                                style = MaterialTheme.typography.bodyMedium,
                                color = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                        }
                    }
                }
            } else {
                items(attemptsWithProblems.size) { index ->
                    val (attempt, problem) = attemptsWithProblems[index]
                    SessionAttemptCard(
                        attempt = attempt,
                        problem = problem
                    )
                }
            }
        }
    }
    
    // Delete confirmation dialog
    if (showDeleteDialog) {
        AlertDialog(
            onDismissRequest = { showDeleteDialog = false },
            title = { Text("Delete Session") },
            text = {
                Column {
                    Text("Are you sure you want to delete this session?")
                    Spacer(modifier = Modifier.height(8.dp))
                    Text(
                        text = "This will also delete all attempts associated with this session.",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.error
                    )
                }
            },
                                confirmButton = {
                        TextButton(
                            onClick = {
                                session?.let { s ->
                                    viewModel.deleteSession(s)
                                    onNavigateBack()
                                }
                                showDeleteDialog = false
                            }
                        ) {
                            Text("Delete", color = MaterialTheme.colorScheme.error)
                        }
                    },
                    dismissButton = {
                        TextButton(onClick = { showDeleteDialog = false }) {
                            Text("Cancel")
                        }
                    }
                )
            }
            
            if (showAddAttemptDialog && session != null && gym != null) {
                EnhancedAddAttemptDialog(
                    session = session,
                    gym = gym,
                    problems = problems.filter { it.gymId == gym.id && it.isActive },
                    onDismiss = { showAddAttemptDialog = false },
                    onAttemptAdded = { attempt ->
                        viewModel.addAttempt(attempt)
                        showAddAttemptDialog = false
                    },
                    onProblemCreated = { problem ->
                        viewModel.addProblem(problem)
                    }
                )
            }
        }

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ProblemDetailScreen(
    problemId: String,
    viewModel: ClimbViewModel,
    onNavigateBack: () -> Unit,
    onNavigateToEdit: (String) -> Unit
) {
    val context = LocalContext.current
    var showDeleteDialog by remember { mutableStateOf(false) }
    var showImageViewer by remember { mutableStateOf(false) }
    var selectedImageIndex by remember { mutableStateOf(0) }
    val attempts by viewModel.getAttemptsByProblem(problemId).collectAsState(initial = emptyList())
    val sessions by viewModel.sessions.collectAsState()
    val gyms by viewModel.gyms.collectAsState()
    
    // Get problem details
    var problem by remember { mutableStateOf<Problem?>(null) }
    
    LaunchedEffect(problemId) {
        problem = viewModel.getProblemById(problemId).first()
    }
    
    val gym = problem?.let { p -> gyms.find { it.id == p.gymId } }
    
    // Calculate stats
    val successfulAttempts = attempts.filter { 
        it.result in listOf(AttemptResult.SUCCESS, AttemptResult.FLASH, AttemptResult.REDPOINT, AttemptResult.ONSIGHT) 
    }
    val successRate = if (attempts.isNotEmpty()) {
        (successfulAttempts.size.toDouble() / attempts.size * 100).toInt()
    } else 0
    
    val attemptsWithSessions = attempts.mapNotNull { attempt ->
        val session = sessions.find { it.id == attempt.sessionId }
        if (session != null) attempt to session else null
    }.sortedByDescending { it.second.date }
    
    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("Problem Details") },
                navigationIcon = {
                    IconButton(onClick = onNavigateBack) {
                        Icon(Icons.Default.ArrowBack, contentDescription = "Back")
                    }
                },
                actions = {
                    IconButton(onClick = { showDeleteDialog = true }) {
                        Icon(Icons.Default.Delete, contentDescription = "Delete")
                    }
                    IconButton(onClick = { onNavigateToEdit(problemId) }) {
                        Icon(Icons.Default.Edit, contentDescription = "Edit")
                    }
                }
            )
        }
    ) { paddingValues ->
        LazyColumn(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
                .padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            // Problem Header
            item {
                Card(
                    modifier = Modifier.fillMaxWidth()
                ) {
                    Column(
                        modifier = Modifier.padding(20.dp)
                    ) {
                        Text(
                            text = problem?.name ?: "Unknown Problem",
                            style = MaterialTheme.typography.headlineMedium,
                            fontWeight = FontWeight.Bold
                        )
                        
                        Spacer(modifier = Modifier.height(8.dp))
                        
                        Row(
                            modifier = Modifier.fillMaxWidth(),
                            horizontalArrangement = Arrangement.SpaceBetween,
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Column {
                                problem?.let { p ->
                                    Text(
                                        text = "${p.difficulty.system.name}: ${p.difficulty.grade}",
                                        style = MaterialTheme.typography.titleLarge,
                                        color = MaterialTheme.colorScheme.primary,
                                        fontWeight = FontWeight.Bold
                                    )
                                }
                                
                                problem?.let { p ->
                                    Text(
                                        text = p.climbType.name.lowercase().replaceFirstChar { it.uppercase() },
                                        style = MaterialTheme.typography.bodyMedium,
                                        color = MaterialTheme.colorScheme.onSurfaceVariant
                                    )
                                }
                            }
                            
                            gym?.let { g ->
                                Column(horizontalAlignment = Alignment.End) {
                                    Text(
                                        text = g.name,
                                        style = MaterialTheme.typography.titleMedium,
                                        fontWeight = FontWeight.Medium
                                    )
                                    
                                    problem?.location?.let { location ->
                                        Text(
                                            text = location,
                                            style = MaterialTheme.typography.bodySmall,
                                            color = MaterialTheme.colorScheme.onSurfaceVariant
                                        )
                                    }
                                }
                            }
                        }
                        
                        problem?.description?.let { description ->
                            Spacer(modifier = Modifier.height(12.dp))
                            Text(
                                text = description,
                                style = MaterialTheme.typography.bodyMedium
                            )
                        }
                        
                        // Display images if any
                        problem?.let { p ->
                            if (p.imagePaths.isNotEmpty()) {
                                Spacer(modifier = Modifier.height(16.dp))
                                ImageDisplaySection(
                                    imagePaths = p.imagePaths,
                                    title = "Photos",
                                    onImageClick = { index ->
                                        selectedImageIndex = index
                                        showImageViewer = true
                                    }
                                )
                            }
                        }
                        
                        problem?.setter?.let { setter ->
                            Spacer(modifier = Modifier.height(8.dp))
                            Text(
                                text = "Set by: $setter",
                                style = MaterialTheme.typography.bodySmall,
                                color = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                        }
                        
                        if (problem?.tags?.isNotEmpty() == true) {
                            Spacer(modifier = Modifier.height(12.dp))
                            LazyRow(
                                horizontalArrangement = Arrangement.spacedBy(8.dp)
                            ) {
                                items(problem?.tags ?: emptyList()) { tag ->
                                    AssistChip(
                                        onClick = { },
                                        label = { Text(tag) }
                                    )
                                }
                            }
                        }
                        
                        problem?.notes?.let { notes ->
                            Spacer(modifier = Modifier.height(12.dp))
                            Text(
                                text = notes,
                                style = MaterialTheme.typography.bodySmall,
                                color = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                        }
                    }
                }
            }
            
            // Progress Summary
            item {
                Card(
                    modifier = Modifier.fillMaxWidth()
                ) {
                    Column(
                        modifier = Modifier.padding(20.dp)
                    ) {
                        Text(
                            text = "Progress Summary",
                            style = MaterialTheme.typography.titleLarge,
                            fontWeight = FontWeight.Bold
                        )
                        
                        Spacer(modifier = Modifier.height(16.dp))
                        
                        if (attempts.isEmpty()) {
                            Text(
                                text = "No attempts recorded yet",
                                style = MaterialTheme.typography.bodyMedium,
                                color = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                        } else {
                            Row(
                                modifier = Modifier.fillMaxWidth(),
                                horizontalArrangement = Arrangement.SpaceEvenly
                            ) {
                                StatItem(
                                    label = "Total Attempts",
                                    value = attempts.size.toString()
                                )
                                StatItem(
                                    label = "Successful",
                                    value = successfulAttempts.size.toString()
                                )
                                StatItem(
                                    label = "Success Rate",
                                    value = "$successRate%"
                                )
                            }
                            
                            Spacer(modifier = Modifier.height(12.dp))
                            
                            if (successfulAttempts.isNotEmpty()) {
                                val firstSuccess = successfulAttempts.minByOrNull { attempt ->
                                    sessions.find { it.id == attempt.sessionId }?.date ?: ""
                                }
                                firstSuccess?.let { attempt ->
                                    val session = sessions.find { it.id == attempt.sessionId }
                                    Text(
                                        text = "First success: ${formatDate(session?.date ?: "")} (${attempt.result.name.lowercase().replaceFirstChar { it.uppercase() }})",
                                        style = MaterialTheme.typography.bodyMedium,
                                        color = MaterialTheme.colorScheme.primary
                                    )
                                }
                            }
                        }
                    }
                }
            }
            
            // Attempt History
            item {
                Text(
                    text = "Attempt History (${attempts.size})",
                    style = MaterialTheme.typography.titleLarge,
                    fontWeight = FontWeight.Bold
                )
            }
            
            if (attemptsWithSessions.isEmpty()) {
                item {
                    Card(
                        modifier = Modifier.fillMaxWidth()
                    ) {
                        Column(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(20.dp),
                            horizontalAlignment = Alignment.CenterHorizontally
                        ) {
                            Text(
                                text = "No attempts yet",
                                style = MaterialTheme.typography.titleMedium,
                                color = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                            Spacer(modifier = Modifier.height(8.dp))
                            Text(
                                text = "Start a session and track your attempts on this problem!",
                                style = MaterialTheme.typography.bodyMedium,
                                color = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                        }
                    }
                }
            } else {
                items(attemptsWithSessions.size) { index ->
                    val (attempt, session) = attemptsWithSessions[index]
                    AttemptHistoryCard(
                        attempt = attempt,
                        session = session,
                        gym = gym
                    )
                }
            }
        }
    }
    
    // Delete confirmation dialog
    if (showDeleteDialog) {
        AlertDialog(
            onDismissRequest = { showDeleteDialog = false },
            title = { Text("Delete Problem") },
            text = {
                Column {
                    Text("Are you sure you want to delete this problem?")
                    Spacer(modifier = Modifier.height(8.dp))
                    Text(
                        text = "This will also delete all attempts associated with this problem.",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.error
                    )
                }
            },
            confirmButton = {
                TextButton(
                    onClick = {
                        problem?.let { p ->
                            viewModel.deleteProblem(p, context)
                            onNavigateBack()
                        }
                        showDeleteDialog = false
                    }
                ) {
                    Text("Delete", color = MaterialTheme.colorScheme.error)
                }
            },
            dismissButton = {
                TextButton(onClick = { showDeleteDialog = false }) {
                    Text("Cancel")
                }
            }
        )
    }
    
    // Fullscreen Image Viewer
    problem?.let { p ->
        if (showImageViewer && p.imagePaths.isNotEmpty()) {
            FullscreenImageViewer(
                imagePaths = p.imagePaths,
                initialIndex = selectedImageIndex,
                onDismiss = { showImageViewer = false }
            )
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun GymDetailScreen(
    gymId: String,
    viewModel: ClimbViewModel,
    onNavigateBack: () -> Unit,
    onNavigateToEdit: (String) -> Unit
) {
    val gyms by viewModel.gyms.collectAsState()
    val gym = gyms.find { it.id == gymId }
    val problems by viewModel.getProblemsByGym(gymId).collectAsState(initial = emptyList())
    val sessions by viewModel.getSessionsByGym(gymId).collectAsState(initial = emptyList())
    val allAttempts by viewModel.attempts.collectAsState()
    
    // Calculate statistics
    val gymAttempts = allAttempts.filter { attempt ->
        problems.any { problem -> problem.id == attempt.problemId }
    }
    
    val successfulAttempts = gymAttempts.filter { 
        it.result in listOf(AttemptResult.SUCCESS, AttemptResult.FLASH, AttemptResult.REDPOINT, AttemptResult.ONSIGHT) 
    }
    
    val successRate = if (gymAttempts.isNotEmpty()) {
        (successfulAttempts.size.toDouble() / gymAttempts.size * 100).toInt()
    } else 0
    
    val uniqueProblemsClimbed = gymAttempts.map { it.problemId }.toSet().size
    val totalSessions = sessions.size
    val activeSessions = sessions.count { it.status == SessionStatus.ACTIVE }
    
    var showDeleteDialog by remember { mutableStateOf(false) }
    
    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text(gym?.name ?: "Gym Details") },
                navigationIcon = {
                    IconButton(onClick = onNavigateBack) {
                        Icon(Icons.Default.ArrowBack, contentDescription = "Back")
                    }
                },
                actions = {
                    IconButton(onClick = { showDeleteDialog = true }) {
                        Icon(Icons.Default.Delete, contentDescription = "Delete")
                    }
                    IconButton(onClick = { onNavigateToEdit(gymId) }) {
                        Icon(Icons.Default.Edit, contentDescription = "Edit")
                    }
                }
            )
        }
    ) { paddingValues ->
        if (gym == null) {
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(paddingValues),
                contentAlignment = Alignment.Center
            ) {
                Text("Gym not found")
            }
        } else {
            LazyColumn(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(paddingValues)
                    .padding(16.dp),
                verticalArrangement = Arrangement.spacedBy(16.dp)
            ) {
                // Gym Information Card
                item {
                    Card(
                        modifier = Modifier.fillMaxWidth(),
                        shape = RoundedCornerShape(16.dp)
                    ) {
                        Column(
                            modifier = Modifier.padding(20.dp)
                        ) {
                            Text(
                                text = gym.name,
                                style = MaterialTheme.typography.headlineMedium,
                                fontWeight = FontWeight.Bold
                            )
                            
                            if (gym.location?.isNotBlank() == true) {
                                Spacer(modifier = Modifier.height(4.dp))
                                Text(
                                    text = gym.location,
                                    style = MaterialTheme.typography.bodyMedium,
                                    color = MaterialTheme.colorScheme.onSurfaceVariant
                                )
                            }
                            
                            if (gym.notes?.isNotBlank() == true) {
                                Spacer(modifier = Modifier.height(8.dp))
                                Text(
                                    text = gym.notes,
                                    style = MaterialTheme.typography.bodyMedium
                                )
                            }
                        }
                    }
                }
                
                // Statistics Card
                item {
                    Card(
                        modifier = Modifier.fillMaxWidth(),
                        shape = RoundedCornerShape(16.dp)
                    ) {
                        Column(
                            modifier = Modifier.padding(20.dp)
                        ) {
                            Text(
                                text = "Statistics",
                                style = MaterialTheme.typography.titleLarge,
                                fontWeight = FontWeight.Bold
                            )
                            
                            Spacer(modifier = Modifier.height(16.dp))
                            
                            // Statistics Grid
                            Row(
                                modifier = Modifier.fillMaxWidth(),
                                horizontalArrangement = Arrangement.SpaceEvenly
                            ) {
                                Column(
                                    horizontalAlignment = Alignment.CenterHorizontally
                                ) {
                                    Text(
                                        text = problems.size.toString(),
                                        style = MaterialTheme.typography.headlineSmall,
                                        fontWeight = FontWeight.Bold,
                                        color = MaterialTheme.colorScheme.primary
                                    )
                                    Text(
                                        text = "Problems",
                                        style = MaterialTheme.typography.bodySmall,
                                        color = MaterialTheme.colorScheme.onSurfaceVariant
                                    )
                                }
                                Column(
                                    horizontalAlignment = Alignment.CenterHorizontally
                                ) {
                                    Text(
                                        text = totalSessions.toString(),
                                        style = MaterialTheme.typography.headlineSmall,
                                        fontWeight = FontWeight.Bold,
                                        color = MaterialTheme.colorScheme.primary
                                    )
                                    Text(
                                        text = "Sessions",
                                        style = MaterialTheme.typography.bodySmall,
                                        color = MaterialTheme.colorScheme.onSurfaceVariant
                                    )
                                }
                                Column(
                                    horizontalAlignment = Alignment.CenterHorizontally
                                ) {
                                    Text(
                                        text = "$successRate%",
                                        style = MaterialTheme.typography.headlineSmall,
                                        fontWeight = FontWeight.Bold,
                                        color = MaterialTheme.colorScheme.primary
                                    )
                                    Text(
                                        text = "Success Rate",
                                        style = MaterialTheme.typography.bodySmall,
                                        color = MaterialTheme.colorScheme.onSurfaceVariant
                                    )
                                }
                            }
                            
                            Spacer(modifier = Modifier.height(12.dp))
                            
                            Row(
                                modifier = Modifier.fillMaxWidth(),
                                horizontalArrangement = Arrangement.SpaceEvenly
                            ) {
                                Column(
                                    horizontalAlignment = Alignment.CenterHorizontally
                                ) {
                                    Text(
                                        text = gymAttempts.size.toString(),
                                        style = MaterialTheme.typography.headlineSmall,
                                        fontWeight = FontWeight.Bold,
                                        color = MaterialTheme.colorScheme.primary
                                    )
                                    Text(
                                        text = "Total Attempts",
                                        style = MaterialTheme.typography.bodySmall,
                                        color = MaterialTheme.colorScheme.onSurfaceVariant
                                    )
                                }
                                Column(
                                    horizontalAlignment = Alignment.CenterHorizontally
                                ) {
                                    Text(
                                        text = uniqueProblemsClimbed.toString(),
                                        style = MaterialTheme.typography.headlineSmall,
                                        fontWeight = FontWeight.Bold,
                                        color = MaterialTheme.colorScheme.primary
                                    )
                                    Text(
                                        text = "Problems Climbed",
                                        style = MaterialTheme.typography.bodySmall,
                                        color = MaterialTheme.colorScheme.onSurfaceVariant
                                    )
                                }
                                if (activeSessions > 0) {
                                    Column(
                                        horizontalAlignment = Alignment.CenterHorizontally
                                    ) {
                                        Text(
                                            text = activeSessions.toString(),
                                            style = MaterialTheme.typography.headlineSmall,
                                            fontWeight = FontWeight.Bold,
                                            color = MaterialTheme.colorScheme.primary
                                        )
                                        Text(
                                            text = "Active Sessions",
                                            style = MaterialTheme.typography.bodySmall,
                                            color = MaterialTheme.colorScheme.onSurfaceVariant
                                        )
                                    }
                                }
                            }
                        }
                    }
                }
                
                // Recent Problems Card
                if (problems.isNotEmpty()) {
                    item {
                        Card(
                            modifier = Modifier.fillMaxWidth(),
                            shape = RoundedCornerShape(16.dp)
                        ) {
                            Column(
                                modifier = Modifier.padding(20.dp)
                            ) {
                                Text(
                                    text = "Problems (${problems.size})",
                                    style = MaterialTheme.typography.titleLarge,
                                    fontWeight = FontWeight.Bold
                                )
                                
                                Spacer(modifier = Modifier.height(12.dp))
                                
                                // Show recent problems (limit to 5)
                                problems.sortedByDescending { it.createdAt }.take(5).forEach { problem ->
                                    val problemAttempts = gymAttempts.filter { it.problemId == problem.id }
                                    val problemSuccessful = problemAttempts.any { 
                                        it.result in listOf(AttemptResult.SUCCESS, AttemptResult.FLASH, AttemptResult.REDPOINT, AttemptResult.ONSIGHT) 
                                    }
                                    
                                    Card(
                                        modifier = Modifier
                                            .fillMaxWidth()
                                            .padding(vertical = 4.dp),
                                        colors = CardDefaults.cardColors(
                                            containerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.3f)
                                        ),
                                        shape = RoundedCornerShape(12.dp)
                                    ) {
                                        ListItem(
                                            headlineContent = { 
                                                Text(
                                                    text = problem.name ?: "Unnamed Problem",
                                                    fontWeight = FontWeight.Medium
                                                )
                                            },
                                            supportingContent = { 
                                                Text("${problem.difficulty.grade} • ${problem.climbType} • ${problemAttempts.size} attempts")
                                            },
                                            trailingContent = {
                                                if (problemSuccessful) {
                                                    Icon(
                                                        Icons.Default.Check,
                                                        contentDescription = "Completed",
                                                        tint = MaterialTheme.colorScheme.primary
                                                    )
                                                }
                                            }
                                        )
                                    }
                                }
                                
                                if (problems.size > 5) {
                                    Spacer(modifier = Modifier.height(8.dp))
                                    Text(
                                        text = "... and ${problems.size - 5} more problems",
                                        style = MaterialTheme.typography.bodySmall,
                                        color = MaterialTheme.colorScheme.onSurfaceVariant
                                    )
                                }
                            }
                        }
                    }
                }
                
                // Recent Sessions Card
                if (sessions.isNotEmpty()) {
                    item {
                        Card(
                            modifier = Modifier.fillMaxWidth(),
                            shape = RoundedCornerShape(16.dp)
                        ) {
                            Column(
                                modifier = Modifier.padding(20.dp)
                            ) {
                                Text(
                                    text = "Recent Sessions (${sessions.size})",
                                    style = MaterialTheme.typography.titleLarge,
                                    fontWeight = FontWeight.Bold
                                )
                                
                                Spacer(modifier = Modifier.height(12.dp))
                                
                                // Show recent sessions (limit to 3)
                                sessions.sortedByDescending { it.date }.take(3).forEach { session ->
                                    val sessionAttempts = gymAttempts.filter { it.sessionId == session.id }
                                    
                                    Card(
                                        modifier = Modifier
                                            .fillMaxWidth()
                                            .padding(vertical = 4.dp),
                                        colors = CardDefaults.cardColors(
                                            containerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.3f)
                                        ),
                                        shape = RoundedCornerShape(12.dp)
                                    ) {
                                        ListItem(
                                            headlineContent = { 
                                                Row(
                                                    horizontalArrangement = Arrangement.spacedBy(8.dp),
                                                    verticalAlignment = Alignment.CenterVertically
                                                ) {
                                                    Text(
                                                        text = if (session.status == SessionStatus.ACTIVE) "Active Session" 
                                                               else "Session",
                                                        fontWeight = FontWeight.Medium
                                                    )
                                                    if (session.status == SessionStatus.ACTIVE) {
                                                        Badge(
                                                            containerColor = MaterialTheme.colorScheme.primary
                                                        ) {
                                                            Text("ACTIVE", style = MaterialTheme.typography.labelSmall)
                                                        }
                                                    }
                                                }
                                            },
                                            supportingContent = { 
                                                val dateTime = try {
                                                    LocalDateTime.parse(session.date)
                                                } catch (e: Exception) {
                                                    null
                                                }
                                                val formattedDate = dateTime?.format(
                                                    DateTimeFormatter.ofPattern("MMM dd, yyyy")
                                                ) ?: session.date
                                                
                                                Text("$formattedDate • ${sessionAttempts.size} attempts")
                                            },
                                            trailingContent = {
                                                session.duration?.let { duration ->
                                                    Text(
                                                        text = "${duration}min",
                                                        style = MaterialTheme.typography.bodySmall,
                                                        color = MaterialTheme.colorScheme.onSurfaceVariant
                                                    )
                                                }
                                            }
                                        )
                                    }
                                }
                                
                                if (sessions.size > 3) {
                                    Spacer(modifier = Modifier.height(8.dp))
                                    Text(
                                        text = "... and ${sessions.size - 3} more sessions",
                                        style = MaterialTheme.typography.bodySmall,
                                        color = MaterialTheme.colorScheme.onSurfaceVariant
                                    )
                                }
                            }
                        }
                    }
                }
                
                // Empty state if no data
                if (problems.isEmpty() && sessions.isEmpty()) {
                    item {
                        Card(
                            modifier = Modifier.fillMaxWidth(),
                            shape = RoundedCornerShape(16.dp)
                        ) {
                            Column(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(40.dp),
                                horizontalAlignment = Alignment.CenterHorizontally
                            ) {
                                Text(
                                    text = "No activity yet",
                                    style = MaterialTheme.typography.titleMedium,
                                    fontWeight = FontWeight.Medium
                                )
                                Spacer(modifier = Modifier.height(8.dp))
                                Text(
                                    text = "Start a session or add problems to see them here",
                                    style = MaterialTheme.typography.bodyMedium,
                                    color = MaterialTheme.colorScheme.onSurfaceVariant
                                )
                            }
                        }
                    }
                }
            }
        }
    }
    
    // Delete confirmation dialog
    if (showDeleteDialog) {
        AlertDialog(
            onDismissRequest = { showDeleteDialog = false },
            title = { Text("Delete Gym") },
            text = {
                Column {
                    Text("Are you sure you want to delete this gym?")
                    Spacer(modifier = Modifier.height(8.dp))
                    Text(
                        text = "This will also delete all problems and sessions associated with this gym.",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.error
                    )
                }
            },
            confirmButton = {
                TextButton(
                    onClick = {
                        gym?.let { g ->
                            viewModel.deleteGym(g)
                            onNavigateBack()
                        }
                        showDeleteDialog = false
                    }
                ) {
                    Text("Delete", color = MaterialTheme.colorScheme.error)
                }
            },
            dismissButton = {
                TextButton(onClick = { showDeleteDialog = false }) {
                    Text("Cancel")
                }
            }
        )
    }
}



@Composable
fun StatItem(
    label: String,
    value: String
) {
    Column(
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Text(
            text = value,
            style = MaterialTheme.typography.headlineSmall,
            fontWeight = FontWeight.Bold,
            color = MaterialTheme.colorScheme.primary
        )
        Text(
            text = label,
            style = MaterialTheme.typography.bodySmall,
            color = MaterialTheme.colorScheme.onSurfaceVariant
        )
    }
}

@Composable
fun AttemptHistoryCard(
    attempt: Attempt,
    session: ClimbSession,
    gym: Gym?
) {
    Card(
        modifier = Modifier.fillMaxWidth()
    ) {
        Column(
            modifier = Modifier.padding(16.dp)
        ) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Column {
                    Text(
                        text = formatDate(session.date),
                        style = MaterialTheme.typography.titleMedium,
                        fontWeight = FontWeight.Medium
                    )
                    gym?.let { g ->
                        Text(
                            text = g.name,
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    }
                }
                
                AttemptResultBadge(result = attempt.result)
            }
            
            attempt.notes?.let { notes ->
                Spacer(modifier = Modifier.height(8.dp))
                Text(
                    text = notes,
                    style = MaterialTheme.typography.bodyMedium
                )
            }
        }
    }
}

@Composable
fun AttemptResultBadge(result: AttemptResult) {
    val backgroundColor = when (result) {
        AttemptResult.SUCCESS, AttemptResult.FLASH, AttemptResult.REDPOINT, AttemptResult.ONSIGHT -> MaterialTheme.colorScheme.primaryContainer
        AttemptResult.FALL -> MaterialTheme.colorScheme.secondaryContainer
        else -> MaterialTheme.colorScheme.surfaceVariant
    }
    
    val textColor = when (result) {
        AttemptResult.SUCCESS, AttemptResult.FLASH, AttemptResult.REDPOINT, AttemptResult.ONSIGHT -> MaterialTheme.colorScheme.onPrimaryContainer
        AttemptResult.FALL -> MaterialTheme.colorScheme.onSecondaryContainer
        else -> MaterialTheme.colorScheme.onSurfaceVariant
    }
    
    Surface(
        color = backgroundColor,
        shape = RoundedCornerShape(12.dp)
    ) {
        Text(
            text = result.name.lowercase().replaceFirstChar { it.uppercase() },
            modifier = Modifier.padding(horizontal = 12.dp, vertical = 6.dp),
            style = MaterialTheme.typography.labelMedium,
            color = textColor,
            fontWeight = FontWeight.Medium
        )
    }
}

@Composable
fun SessionAttemptCard(
    attempt: Attempt,
    problem: Problem
) {
    Card(
        modifier = Modifier.fillMaxWidth()
    ) {
        Column(
            modifier = Modifier.padding(16.dp)
        ) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Column(modifier = Modifier.weight(1f)) {
                    Text(
                        text = problem.name ?: "Unknown Problem",
                        style = MaterialTheme.typography.titleMedium,
                        fontWeight = FontWeight.Medium
                    )
                    
                    Text(
                        text = "${problem.difficulty.system.name}: ${problem.difficulty.grade}",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.primary
                    )
                    
                    problem.location?.let { location ->
                        Text(
                            text = location,
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    }
                }
                
                AttemptResultBadge(result = attempt.result)
            }
            
            attempt.notes?.let { notes ->
                Spacer(modifier = Modifier.height(8.dp))
                Text(
                    text = notes,
                    style = MaterialTheme.typography.bodyMedium
                )
            }
        }
    }
}

private fun formatDate(dateString: String): String {
    return try {
        val formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME
        val date = LocalDateTime.parse(dateString, formatter)
        val displayFormatter = DateTimeFormatter.ofPattern("MMM dd, yyyy")
        date.format(displayFormatter)
    } catch (e: Exception) {
        dateString.take(10) // Fallback to just the date part
    }
}

private fun formatTime(timeString: String): String {
    return try {
        val formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME
        val time = LocalDateTime.parse(timeString, formatter)
        val displayFormatter = DateTimeFormatter.ofPattern("h:mm a")
        time.format(displayFormatter)
    } catch (e: Exception) {
        timeString.take(8) // Fallback to time part
    }
}

private fun calculateSessionDuration(startTime: String, endTime: String): String {
    return try {
        val formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME
        val start = LocalDateTime.parse(startTime, formatter)
        val end = LocalDateTime.parse(endTime, formatter)
        val duration = java.time.Duration.between(start, end)
        
        val hours = duration.toHours()
        val minutes = duration.toMinutes() % 60
        
        when {
            hours > 0 -> "${hours}h ${minutes}m"
            minutes > 0 -> "${minutes}m"
            else -> "< 1m"
        }
    } catch (e: Exception) {
        "Unknown"
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun EnhancedAddAttemptDialog(
    session: ClimbSession,
    gym: Gym,
    problems: List<Problem>,
    onDismiss: () -> Unit,
    onAttemptAdded: (Attempt) -> Unit,
    onProblemCreated: (Problem) -> 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("") }
    var showCreateProblem by remember { mutableStateOf(false) }
    
    // New problem creation state
    var newProblemName by remember { mutableStateOf("") }
    var newProblemGrade by remember { mutableStateOf("") }
    var selectedClimbType by remember { mutableStateOf(ClimbType.BOULDER) }
    var selectedDifficultySystem by remember { mutableStateOf(gym.difficultySystems.firstOrNull() ?: DifficultySystem.V_SCALE) }
    
    Dialog(onDismissRequest = onDismiss) {
        Card(
            modifier = Modifier
                .fillMaxWidth()
                .fillMaxHeight(0.9f)
                .padding(16.dp),
            colors = CardDefaults.cardColors(
                containerColor = MaterialTheme.colorScheme.surface
            )
        ) {
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(24.dp)
            ) {
                Text(
                    text = "Add Attempt",
                    style = MaterialTheme.typography.headlineSmall,
                    fontWeight = FontWeight.Bold,
                    modifier = Modifier.padding(bottom = 20.dp)
                )
                
                LazyColumn(
                    modifier = Modifier
                        .weight(1f)
                        .fillMaxWidth(),
                    verticalArrangement = Arrangement.spacedBy(20.dp)
                ) {
                    item {
                        if (!showCreateProblem) {
                    Column(
                        verticalArrangement = Arrangement.spacedBy(12.dp)
                    ) {
                        Text(
                            text = "Select Problem",
                            style = MaterialTheme.typography.titleMedium,
                            fontWeight = FontWeight.SemiBold,
                            color = MaterialTheme.colorScheme.onSurface
                        )
                        
                        if (problems.isEmpty()) {
                            Card(
                                colors = CardDefaults.cardColors(
                                    containerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f)
                                ),
                                modifier = Modifier.fillMaxWidth()
                            ) {
                                Column(
                                    modifier = Modifier
                                        .padding(16.dp)
                                        .fillMaxWidth(),
                                    horizontalAlignment = Alignment.CenterHorizontally
                                ) {
                                    Text(
                                        text = "No active problems in this gym",
                                        style = MaterialTheme.typography.bodyMedium,
                                        color = MaterialTheme.colorScheme.onSurfaceVariant
                                    )
                                    
                                    Spacer(modifier = Modifier.height(8.dp))
                                    
                                    Button(
                                        onClick = { showCreateProblem = true }
                                    ) {
                                        Text("Create New Problem")
                                    }
                                }
                            }
                        } else {
                            LazyColumn(
                                modifier = Modifier.height(140.dp),
                                verticalArrangement = Arrangement.spacedBy(8.dp)
                            ) {
                                items(problems) { problem ->
                                    val isSelected = selectedProblem?.id == problem.id
                                    Card(
                                        onClick = { selectedProblem = problem },
                                        colors = CardDefaults.cardColors(
                                            containerColor = if (isSelected) 
                                                MaterialTheme.colorScheme.primaryContainer 
                                            else MaterialTheme.colorScheme.surfaceVariant,
                                        ),
                                        border = if (isSelected) 
                                            BorderStroke(
                                                2.dp, 
                                                MaterialTheme.colorScheme.primary
                                            ) 
                                        else null,
                                        modifier = Modifier.fillMaxWidth()
                                    ) {
                                        Column(
                                            modifier = Modifier.padding(16.dp)
                                        ) {
                                            Text(
                                                text = problem.name ?: "Unnamed Problem",
                                                style = MaterialTheme.typography.bodyLarge,
                                                fontWeight = FontWeight.SemiBold,
                                                color = if (isSelected) 
                                                    MaterialTheme.colorScheme.onSurface 
                                                else MaterialTheme.colorScheme.onSurfaceVariant
                                            )
                                            Spacer(modifier = Modifier.height(4.dp))
                                            Text(
                                                text = "${problem.difficulty.system.name}: ${problem.difficulty.grade}",
                                                style = MaterialTheme.typography.bodyMedium,
                                                color = if (isSelected) 
                                                    MaterialTheme.colorScheme.onSurface.copy(alpha = 0.8f)
                                                else MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f),
                                                fontWeight = FontWeight.Medium
                                            )
                                        }
                                    }
                                }
                            }
                            
                            // Option to create new problem
                            OutlinedButton(
                                onClick = { showCreateProblem = true },
                                modifier = Modifier.fillMaxWidth()
                            ) {
                                Text("Create New Problem")
                            }
                        }
                    }
                        } else {
                    Column(
                        verticalArrangement = Arrangement.spacedBy(16.dp)
                    ) {
                        Row(
                            verticalAlignment = Alignment.CenterVertically,
                            horizontalArrangement = Arrangement.SpaceBetween,
                            modifier = Modifier.fillMaxWidth()
                        ) {
                            Text(
                                text = "Create New Problem",
                                style = MaterialTheme.typography.titleMedium,
                                fontWeight = FontWeight.SemiBold,
                                color = MaterialTheme.colorScheme.onSurface
                            )
                            
                            TextButton(
                                onClick = { showCreateProblem = false }
                            ) {
                                Text("← Back", color = MaterialTheme.colorScheme.primary)
                            }
                        }
                        
                        OutlinedTextField(
                            value = newProblemName,
                            onValueChange = { newProblemName = it },
                            label = { Text("Problem Name") },
                            placeholder = { Text("e.g., 'The Red Overhang'") },
                            modifier = Modifier.fillMaxWidth(),
                            singleLine = true,
                            colors = OutlinedTextFieldDefaults.colors(
                                focusedBorderColor = MaterialTheme.colorScheme.primary,
                                unfocusedBorderColor = MaterialTheme.colorScheme.outline
                            )
                        )
                        
                        // Climb Type Selection
                        Column(
                            verticalArrangement = Arrangement.spacedBy(8.dp)
                        ) {
                            Text(
                                text = "Climb Type",
                                style = MaterialTheme.typography.bodyLarge,
                                fontWeight = FontWeight.Medium,
                                color = MaterialTheme.colorScheme.onSurface
                            )
                            LazyRow(
                                horizontalArrangement = Arrangement.spacedBy(8.dp)
                            ) {
                                items(gym.supportedClimbTypes) { climbType ->
                                    FilterChip(
                                        onClick = { selectedClimbType = climbType },
                                        label = { 
                                            Text(
                                                climbType.name.lowercase().replaceFirstChar { it.uppercase() },
                                                fontWeight = FontWeight.Medium
                                            ) 
                                        },
                                        selected = selectedClimbType == climbType,
                                        colors = FilterChipDefaults.filterChipColors(
                                            selectedContainerColor = MaterialTheme.colorScheme.primaryContainer,
                                            selectedLabelColor = MaterialTheme.colorScheme.onPrimaryContainer
                                        )
                                    )
                                }
                            }
                        }
                        
                        // Difficulty System Selection
                        Column(
                            verticalArrangement = Arrangement.spacedBy(8.dp)
                        ) {
                            Text(
                                text = "Difficulty System",
                                style = MaterialTheme.typography.bodyLarge,
                                fontWeight = FontWeight.Medium,
                                color = MaterialTheme.colorScheme.onSurface
                            )
                            LazyRow(
                                horizontalArrangement = Arrangement.spacedBy(8.dp)
                            ) {
                                items(gym.difficultySystems) { system ->
                                    FilterChip(
                                        onClick = { selectedDifficultySystem = system },
                                        label = { 
                                            Text(
                                                system.name,
                                                fontWeight = FontWeight.Medium
                                            ) 
                                        },
                                        selected = selectedDifficultySystem == system,
                                        colors = FilterChipDefaults.filterChipColors(
                                            selectedContainerColor = MaterialTheme.colorScheme.primaryContainer,
                                            selectedLabelColor = MaterialTheme.colorScheme.onPrimaryContainer
                                        )
                                    )
                                }
                            }
                        }
                        
                        OutlinedTextField(
                            value = newProblemGrade,
                            onValueChange = { newProblemGrade = it },
                            label = { Text("Grade *") },
                            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"
                                }) 
                            },
                            modifier = Modifier.fillMaxWidth(),
                            singleLine = true,
                            colors = OutlinedTextFieldDefaults.colors(
                                focusedBorderColor = MaterialTheme.colorScheme.primary,
                                unfocusedBorderColor = MaterialTheme.colorScheme.outline
                            ),
                            isError = newProblemGrade.isBlank(),
                            supportingText = if (newProblemGrade.isBlank()) {
                                { Text("Grade is required", color = MaterialTheme.colorScheme.error) }
                            } else null
                        )
                    }
                        }
                    }
                    
                    // Result Selection (always shown)
                    item {
                Column(
                    verticalArrangement = Arrangement.spacedBy(12.dp)
                ) {
                    Text(
                        text = "Attempt Result",
                        style = MaterialTheme.typography.titleMedium,
                        fontWeight = FontWeight.SemiBold,
                        color = MaterialTheme.colorScheme.onSurface
                    )
                    
                    Card(
                        colors = CardDefaults.cardColors(
                            containerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.3f)
                        )
                    ) {
                        Column(
                            modifier = Modifier
                                .padding(12.dp)
                                .selectableGroup()
                        ) {
                            AttemptResult.entries.forEach { result ->
                                Row(
                                    verticalAlignment = Alignment.CenterVertically,
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .selectable(
                                            selected = selectedResult == result,
                                            onClick = { selectedResult = result },
                                            role = Role.RadioButton
                                        )
                                        .padding(vertical = 4.dp)
                                ) {
                                    RadioButton(
                                        selected = selectedResult == result,
                                        onClick = null,
                                        colors = RadioButtonDefaults.colors(
                                            selectedColor = MaterialTheme.colorScheme.primary
                                        )
                                    )
                                    Spacer(modifier = Modifier.width(12.dp))
                                    Text(
                                        text = result.name.lowercase().replaceFirstChar { it.uppercase() },
                                        style = MaterialTheme.typography.bodyMedium,
                                        fontWeight = if (selectedResult == result) FontWeight.Medium else FontWeight.Normal,
                                        color = MaterialTheme.colorScheme.onSurface
                                    )
                                }
                            }
                        }
                    }
                    
                    
                Column(
                    verticalArrangement = Arrangement.spacedBy(12.dp)
                ) {
                    Text(
                        text = "Additional Details",
                        style = MaterialTheme.typography.titleMedium,
                        fontWeight = FontWeight.SemiBold,
                        color = MaterialTheme.colorScheme.onSurface
                    )
                    
                    OutlinedTextField(
                        value = highestHold,
                        onValueChange = { highestHold = it },
                        label = { Text("Highest Hold") },
                        placeholder = { Text("e.g., 'jugs near the top', 'crux move'") },
                        modifier = Modifier.fillMaxWidth(),
                        singleLine = true,
                        colors = OutlinedTextFieldDefaults.colors(
                            focusedBorderColor = MaterialTheme.colorScheme.primary,
                            unfocusedBorderColor = MaterialTheme.colorScheme.outline
                        )
                    )
                    
                    OutlinedTextField(
                        value = notes,
                        onValueChange = { notes = it },
                        label = { Text("Notes") },
                        placeholder = { Text("e.g., 'need to work on heel hooks', 'pumped out'") },
                        modifier = Modifier.fillMaxWidth(),
                        minLines = 3,
                        maxLines = 4,
                        colors = OutlinedTextFieldDefaults.colors(
                            focusedBorderColor = MaterialTheme.colorScheme.primary,
                            unfocusedBorderColor = MaterialTheme.colorScheme.outline
                        )
                    )
                    }
                }
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(top = 8.dp),
                    horizontalArrangement = Arrangement.spacedBy(12.dp)
                ) {
                    OutlinedButton(
                        onClick = onDismiss,
                        modifier = Modifier.weight(1f),
                        colors = ButtonDefaults.outlinedButtonColors(
                            contentColor = MaterialTheme.colorScheme.onSurface
                        )
                    ) {
                        Text("Cancel", fontWeight = FontWeight.Medium)
                    }
                    
                    Button(
                        onClick = {
                            if (showCreateProblem) {
                                // Create new problem first
                                if (newProblemGrade.isNotBlank()) {
                                    val difficulty = DifficultyGrade(
                                        system = selectedDifficultySystem,
                                        grade = newProblemGrade,
                                        numericValue = when (selectedDifficultySystem) {
                                            DifficultySystem.V_SCALE -> newProblemGrade.removePrefix("V").toIntOrNull() ?: 0
                                            else -> newProblemGrade.hashCode() % 100
                                        }
                                    )
                                    
                                    val newProblem = Problem.create(
                                        gymId = gym.id,
                                        name = newProblemName.ifBlank { null },
                                        climbType = selectedClimbType,
                                        difficulty = difficulty
                                    )
                                    
                                    onProblemCreated(newProblem)
                                    
                                    // Create attempt for the new problem
                                    val attempt = Attempt.create(
                                        sessionId = session.id,
                                        problemId = newProblem.id,
                                        result = selectedResult,
                                        highestHold = highestHold.ifBlank { null },
                                        notes = notes.ifBlank { null }
                                    )
                                    onAttemptAdded(attempt)
                                }
                            } else {
                                // Create attempt for selected problem
                                selectedProblem?.let { problem ->
                                    val attempt = Attempt.create(
                                        sessionId = session.id,
                                        problemId = problem.id,
                                        result = selectedResult,
                                        highestHold = highestHold.ifBlank { null },
                                        notes = notes.ifBlank { null }
                                    )
                                    onAttemptAdded(attempt)
                                }
                            }
                        },
                        enabled = if (showCreateProblem) newProblemGrade.isNotBlank() else selectedProblem != null,
                        modifier = Modifier.weight(1f),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = MaterialTheme.colorScheme.primary,
                            disabledContainerColor = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.12f)
                        )
                    ) {
                        Text("Add", fontWeight = FontWeight.Medium)
                    }
                }
            }
        }
    }
}

@Composable
fun StatisticItem(
    label: String,
    value: String,
    valueColor: androidx.compose.ui.graphics.Color = MaterialTheme.colorScheme.primary
) {
    Column(
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Text(
            text = value,
            style = MaterialTheme.typography.headlineSmall,
            fontWeight = FontWeight.Bold,
            color = valueColor
        )
        Text(
            text = label,
            style = MaterialTheme.typography.bodySmall,
            color = MaterialTheme.colorScheme.onSurfaceVariant
        )
    }
}
}
}
