package com.atridad.ascently.ui.screens

import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.clickable
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.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Add
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.KeyboardArrowDown
import androidx.compose.material.icons.filled.KeyboardArrowUp
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
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.ascently.data.model.*
import com.atridad.ascently.ui.components.FullscreenImageViewer
import com.atridad.ascently.ui.components.ImageDisplaySection
import com.atridad.ascently.ui.components.ImagePicker
import com.atridad.ascently.ui.theme.CustomIcons
import com.atridad.ascently.ui.viewmodel.ClimbViewModel
import com.atridad.ascently.utils.DateFormatUtils
import kotlinx.coroutines.flow.first

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun EditAttemptDialog(
    attempt: Attempt,
    problems: List<Problem>,
    onDismiss: () -> Unit,
    onAttemptUpdated: (Attempt) -> Unit,
) {
    var selectedProblem by remember { mutableStateOf(problems.find { it.id == attempt.problemId }) }
    var selectedResult by remember { mutableStateOf(attempt.result) }
    var highestHold by remember { mutableStateOf(attempt.highestHold ?: "") }
    var notes by remember { mutableStateOf(attempt.notes ?: "") }

    Dialog(onDismissRequest = onDismiss) {
        Card(modifier = Modifier.fillMaxWidth().padding(16.dp)) {
            Column(
                modifier = Modifier.fillMaxSize().padding(24.dp),
                verticalArrangement = Arrangement.spacedBy(20.dp),
            ) {
                Text(
                    text = "Edit 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 problems available.",
                        style = MaterialTheme.typography.bodyMedium,
                        color = MaterialTheme.colorScheme.error,
                    )
                } else {
                    var expanded by remember { mutableStateOf(false) }

                    Box(modifier = Modifier.fillMaxWidth()) {
                        OutlinedTextField(
                            value = selectedProblem?.name ?: "Unknown Problem",
                            onValueChange = {},
                            readOnly = true,
                            label = { Text("Problem") },
                            trailingIcon = {
                                Icon(
                                    if (expanded) {
                                        Icons.Default.KeyboardArrowUp
                                    } else {
                                        Icons.Default.KeyboardArrowDown
                                    },
                                    contentDescription = "Toggle dropdown",
                                )
                            },
                            modifier = Modifier.fillMaxWidth().clickable { expanded = true },
                        )

                        DropdownMenu(
                            expanded = expanded,
                            onDismissRequest = { expanded = false },
                            modifier = Modifier.fillMaxWidth(0.9f),
                        ) {
                            problems.forEach { problem ->
                                DropdownMenuItem(
                                    text = { Text(problem.name ?: "Unknown Problem") },
                                    onClick = {
                                        selectedProblem = problem
                                        expanded = false
                                    },
                                )
                            }
                        }
                    }
                }

                // Result Selection
                Text(
                    text = "Result",
                    style = MaterialTheme.typography.titleMedium,
                    fontWeight = FontWeight.Medium,
                )

                Column(
                    modifier = Modifier.fillMaxWidth(),
                    verticalArrangement = Arrangement.spacedBy(8.dp),
                ) {
                    AttemptResult.entries.forEach { result ->
                        Row(
                            modifier =
                            Modifier.fillMaxWidth()
                                .selectable(
                                    selected = selectedResult == result,
                                    onClick = { selectedResult = result },
                                    role = Role.RadioButton,
                                )
                                .padding(8.dp),
                            verticalAlignment = Alignment.CenterVertically,
                        ) {
                            RadioButton(selected = selectedResult == result, onClick = null)
                            Spacer(modifier = Modifier.width(8.dp))
                            Text(
                                text =
                                when (result) {
                                    AttemptResult.NO_PROGRESS -> "No Progress"
                                    else ->
                                        result.name.lowercase().replaceFirstChar {
                                            it.uppercase()
                                        }
                                },
                                style = MaterialTheme.typography.bodyMedium,
                            )
                        }
                    }
                }

                // Highest Hold
                OutlinedTextField(
                    value = highestHold,
                    onValueChange = { highestHold = it },
                    label = { Text("Highest Hold (Optional)") },
                    placeholder = { Text("e.g., 'jug on the left'") },
                    modifier = Modifier.fillMaxWidth(),
                    singleLine = true,
                )

                // 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 ->
                                val updatedAttempt =
                                    attempt.copy(
                                        problemId = problem.id,
                                        result = selectedResult,
                                        highestHold = highestHold.ifBlank { null },
                                        notes = notes.ifBlank { null },
                                    )
                                onAttemptUpdated(updatedAttempt)
                            }
                        },
                        enabled = selectedProblem != null,
                        modifier = Modifier.weight(1f),
                    ) { Text("Update") }
                }
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SessionDetailScreen(
    sessionId: String,
    viewModel: ClimbViewModel,
    onNavigateBack: () -> Unit,
    onNavigateToProblemDetail: (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 showDeleteDialog by remember { mutableStateOf(false) }
    var showAddAttemptDialog by remember { mutableStateOf(false) }
    var showEditAttemptDialog by remember { mutableStateOf<Attempt?>(null) }

    // Get session details
    val session = remember(sessions, sessionId) { sessions.find { it.id == sessionId } }
    val gym = remember(session, gyms) { session?.let { s -> gyms.find { it.id == s.gymId } } }

    // Calculate stats
    val successfulAttempts = remember(attempts) {
        attempts.filter { it.result in listOf(AttemptResult.SUCCESS, AttemptResult.FLASH) }
    }
    val uniqueProblems = remember(attempts) { attempts.map { it.problemId }.distinct() }
    val completedProblems = remember(successfulAttempts) { successfulAttempts.map { it.problemId }.distinct() }

    val attemptsWithProblems = remember(attempts, problems) {
        attempts
            .mapNotNull { attempt ->
                val problem = problems.find { it.id == attempt.problemId }
                if (problem != null) attempt to problem else null
            }
            .sortedBy { it.first.timestamp }
    }

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("Session Details") },
                navigationIcon = {
                    IconButton(onClick = onNavigateBack) {
                        Icon(
                            Icons.AutoMirrored.Filled.ArrowBack,
                            contentDescription = "Back",
                        )
                    }
                },
                actions = {
                    // No manual actions needed - Health Connect syncs automatically when
                    // sessions complete

                    // Show stop icon for active sessions, delete icon for completed
                    // sessions
                    if (session?.status == SessionStatus.ACTIVE) {
                        IconButton(
                            onClick = {
                                session?.let { s ->
                                    viewModel.endSession(context, s.id)
                                    onNavigateBack()
                                }
                            },
                        ) {
                            Icon(
                                imageVector =
                                CustomIcons.Stop(
                                    MaterialTheme.colorScheme.onSurface,
                                ),
                                contentDescription = "Stop Session",
                            )
                        }
                    } else {
                        IconButton(onClick = { showDeleteDialog = true }) {
                            Icon(Icons.Default.Delete, contentDescription = "Delete")
                        }
                    }
                },
            )
        },
        floatingActionButton = {
            if (session?.status == SessionStatus.ACTIVE) {
                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))

                        val formattedDate = remember(session?.date) {
                            DateFormatUtils.formatDateForDisplay(session?.date ?: "")
                        }
                        Text(
                            text = formattedDate,
                            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(),
                                )
                            }
                        }
                    }
                }
            }

            // 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,
                        onEditAttempt = { attemptToEdit ->
                            showEditAttemptDialog = attemptToEdit
                        },
                        onDeleteAttempt = { attemptToDelete ->
                            viewModel.deleteAttempt(attemptToDelete)
                        },
                        onAttemptClick = { onNavigateToProblemDetail(problem.id) },
                    )
                }
            }
        }
    }

    // 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") }
            },
        )
    }

    val currentSession = session
    val currentGym = gym
    if (showAddAttemptDialog && currentSession != null && currentGym != null) {
        EnhancedAddAttemptDialog(
            session = currentSession,
            gym = currentGym,
            problems = problems.filter { it.gymId == currentGym.id && it.isActive },
            onDismiss = { showAddAttemptDialog = false },
            onAttemptAdded = { attempt ->
                viewModel.addAttempt(attempt)
                showAddAttemptDialog = false
            },
            onProblemCreated = { problem -> viewModel.addProblem(problem) },
        )
    }

    // Edit attempt dialog
    showEditAttemptDialog?.let { attempt ->
        EditAttemptDialog(
            attempt = attempt,
            problems = problems.filter { it.isActive },
            onDismiss = { showEditAttemptDialog = null },
            onAttemptUpdated = { updatedAttempt ->
                viewModel.updateAttempt(updatedAttempt)
                showEditAttemptDialog = null
            },
        )
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ProblemDetailScreen(
    problemId: String,
    viewModel: ClimbViewModel,
    onNavigateBack: () -> Unit,
    onNavigateToEdit: (String) -> Unit,
) {
    var showDeleteDialog by remember { mutableStateOf(false) }
    var showImageViewer by remember { mutableStateOf(false) }
    var selectedImageIndex by remember { mutableIntStateOf(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) }

    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.AutoMirrored.Filled.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.displayName}: ${p.difficulty.grade}",
                                        style = MaterialTheme.typography.titleLarge,
                                        color = MaterialTheme.colorScheme.primary,
                                        fontWeight = FontWeight.Bold,
                                    )
                                }

                                problem?.let { p ->
                                    Text(
                                        text = p.climbType.displayName,
                                        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
                                    },
                                )
                            }
                        }

                        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(),
                                )
                            }

                            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 }
                                    val firstSuccessDate = remember(session?.date) {
                                        DateFormatUtils.formatDateForDisplay(session?.date ?: "")
                                    }
                                    Text(
                                        text =
                                        "First success: $firstSuccessDate (${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)
                            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,
    onNavigateToSessionDetail: (String) -> Unit = {},
    onNavigateToProblemDetail: (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 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.AutoMirrored.Filled.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,
                                    )
                                }
                            }

                            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,
                                                )
                                        }

                                    Card(
                                        modifier =
                                        Modifier.fillMaxWidth()
                                            .padding(vertical = 4.dp)
                                            .clickable {
                                                onNavigateToProblemDetail(
                                                    problem.id,
                                                )
                                            },
                                        colors =
                                        CardDefaults.cardColors(
                                            containerColor =
                                            MaterialTheme.colorScheme
                                                .surface,
                                        ),
                                        shape = RoundedCornerShape(12.dp),
                                        elevation =
                                        CardDefaults.cardElevation(
                                            defaultElevation = 4.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)
                                            .clickable {
                                                onNavigateToSessionDetail(
                                                    session.id,
                                                )
                                            },
                                        colors =
                                        CardDefaults.cardColors(
                                            containerColor =
                                            MaterialTheme.colorScheme
                                                .surface,
                                        ),
                                        shape = RoundedCornerShape(12.dp),
                                        elevation =
                                        CardDefaults.cardElevation(
                                            defaultElevation = 4.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 formattedDate =
                                                    DateFormatUtils.formatDateForDisplay(
                                                        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?) {
    val formattedDate = remember(session.date) {
        DateFormatUtils.formatDateForDisplay(session.date)
    }

    Card(modifier = Modifier.fillMaxWidth()) {
        Column(modifier = Modifier.padding(16.dp)) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically,
            ) {
                Column {
                    Text(
                        text = formattedDate,
                        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 ->
                MaterialTheme.colorScheme.primaryContainer
            AttemptResult.FALL -> MaterialTheme.colorScheme.secondaryContainer
            else -> MaterialTheme.colorScheme.surfaceVariant
        }

    val textColor =
        when (result) {
            AttemptResult.SUCCESS, AttemptResult.FLASH ->
                MaterialTheme.colorScheme.onPrimaryContainer
            AttemptResult.FALL -> MaterialTheme.colorScheme.onSecondaryContainer
            else -> MaterialTheme.colorScheme.onSurfaceVariant
        }

    Surface(color = backgroundColor, shape = RoundedCornerShape(12.dp)) {
        Text(
            text =
            when (result) {
                AttemptResult.NO_PROGRESS -> "No Progress"
                else -> 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,
    onEditAttempt: (Attempt) -> Unit = {},
    onDeleteAttempt: (Attempt) -> Unit = {},
    onAttemptClick: () -> Unit = {},
) {
    var showDeleteDialog by remember { mutableStateOf(false) }

    Card(
        modifier = Modifier.fillMaxWidth().clickable { onAttemptClick() },
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
    ) {
        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.displayName}: ${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,
                        )
                    }
                }

                Row(
                    horizontalArrangement = Arrangement.spacedBy(8.dp),
                    verticalAlignment = Alignment.CenterVertically,
                ) {
                    AttemptResultBadge(result = attempt.result)

                    // Edit button
                    IconButton(
                        onClick = { onEditAttempt(attempt) },
                        modifier = Modifier.size(32.dp),
                    ) {
                        Icon(
                            Icons.Default.Edit,
                            contentDescription = "Edit attempt",
                            modifier = Modifier.size(16.dp),
                        )
                    }

                    // Delete button
                    IconButton(
                        onClick = { showDeleteDialog = true },
                        modifier = Modifier.size(32.dp),
                    ) {
                        Icon(
                            Icons.Default.Delete,
                            contentDescription = "Delete attempt",
                            modifier = Modifier.size(16.dp),
                        )
                    }
                }
            }

            attempt.notes?.let { notes ->
                Spacer(modifier = Modifier.height(8.dp))
                Text(text = notes, style = MaterialTheme.typography.bodyMedium)
            }
        }
    }

    // Delete confirmation dialog
    if (showDeleteDialog) {
        AlertDialog(
            onDismissRequest = { showDeleteDialog = false },
            title = { Text("Delete Attempt") },
            text = { Text("Are you sure you want to delete this attempt?") },
            confirmButton = {
                TextButton(
                    onClick = {
                        onDeleteAttempt(attempt)
                        showDeleteDialog = false
                    },
                ) { Text("Delete", color = MaterialTheme.colorScheme.error) }
            },
            dismissButton = {
                TextButton(onClick = { showDeleteDialog = false }) { Text("Cancel") }
            },
        )
    }
}



@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 newProblemImagePaths by remember { mutableStateOf<List<String>>(emptyList()) }
    var selectedClimbType by remember { mutableStateOf(ClimbType.BOULDER) }
    var selectedDifficultySystem by remember {
        mutableStateOf(gym.difficultySystems.firstOrNull() ?: DifficultySystem.V_SCALE)
    }

    // Auto-select climb type if there's only one available
    LaunchedEffect(gym.supportedClimbTypes) {
        if (gym.supportedClimbTypes.size == 1 &&
            selectedClimbType != gym.supportedClimbTypes.first()
        ) {
            selectedClimbType = gym.supportedClimbTypes.first()
        }
    }

    // Auto-select difficulty system if there's only one available for the selected climb type
    LaunchedEffect(selectedClimbType, gym.difficultySystems) {
        val availableSystems =
            DifficultySystem.systemsForClimbType(selectedClimbType).filter { system ->
                gym.difficultySystems.contains(system)
            }

        when {
            // If current system is not compatible, select the first available one
            selectedDifficultySystem !in availableSystems -> {
                selectedDifficultySystem =
                    availableSystems.firstOrNull()
                        ?: gym.difficultySystems.firstOrNull() ?: DifficultySystem.CUSTOM
            }
            // If there's only one available system, auto-select it
            availableSystems.size == 1 && selectedDifficultySystem != availableSystems.first() -> {
                selectedDifficultySystem = availableSystems.first()
            }
        }
    }

    // Reset grade when difficulty system changes
    LaunchedEffect(selectedDifficultySystem) {
        val availableGrades = selectedDifficultySystem.availableGrades
        if (availableGrades.isNotEmpty() && newProblemGrade !in availableGrades) {
            newProblemGrade = ""
        }
    }

    Dialog(onDismissRequest = onDismiss) {
        Card(modifier = Modifier.fillMaxWidth(0.95f).fillMaxHeight(0.9f).padding(16.dp)) {
            Column(
                modifier = Modifier.fillMaxSize().padding(24.dp),
                verticalArrangement = Arrangement.spacedBy(20.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.displayName}: ${problem.difficulty.grade}",
                                                        style =
                                                        MaterialTheme.typography
                                                            .bodyMedium,
                                                        color =
                                                        if (isSelected) {
                                                            MaterialTheme
                                                                .colorScheme
                                                                .onSurface.copy(
                                                                    alpha = 0.9f,
                                                                )
                                                        } 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,
                                    )

                                    IconButton(
                                        onClick = {
                                            showCreateProblem = false
                                            newProblemName = ""
                                            newProblemGrade = ""
                                            newProblemImagePaths = emptyList()
                                        },
                                    ) {
                                        Icon(
                                            Icons.AutoMirrored.Filled.ArrowBack,
                                            contentDescription = "Back",
                                            tint = MaterialTheme.colorScheme.onSurfaceVariant,
                                        )
                                    }
                                }

                                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.displayName,
                                                        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)) {
                                        val availableSystems =
                                            DifficultySystem.systemsForClimbType(
                                                selectedClimbType,
                                            )
                                                .filter { system ->
                                                    gym.difficultySystems.contains(system)
                                                }
                                        items(availableSystems) { system ->
                                            FilterChip(
                                                onClick = { selectedDifficultySystem = system },
                                                label = {
                                                    Text(
                                                        system.displayName,
                                                        fontWeight = FontWeight.Medium,
                                                    )
                                                },
                                                selected = selectedDifficultySystem == system,
                                                colors =
                                                FilterChipDefaults.filterChipColors(
                                                    selectedContainerColor =
                                                    MaterialTheme
                                                        .colorScheme
                                                        .primaryContainer,
                                                    selectedLabelColor =
                                                    MaterialTheme
                                                        .colorScheme
                                                        .onPrimaryContainer,
                                                ),
                                            )
                                        }
                                    }
                                }

                                if (selectedDifficultySystem == DifficultySystem.CUSTOM) {
                                    OutlinedTextField(
                                        value = newProblemGrade,
                                        onValueChange = { newValue ->
                                            // Only allow integers for custom scales
                                            if (newValue.isEmpty() ||
                                                newValue.all { it.isDigit() }
                                            ) {
                                                newProblemGrade = newValue
                                            }
                                        },
                                        label = { Text("Grade *") },
                                        placeholder = {
                                            Text("Enter numeric grade (e.g. 5, 10, 15)")
                                        },
                                        modifier = Modifier.fillMaxWidth(),
                                        singleLine = true,
                                        colors =
                                        OutlinedTextFieldDefaults.colors(
                                            focusedBorderColor =
                                            MaterialTheme.colorScheme
                                                .primary,
                                            unfocusedBorderColor =
                                            MaterialTheme.colorScheme
                                                .outline,
                                        ),
                                        isError = newProblemGrade.isBlank(),
                                        keyboardOptions =
                                        KeyboardOptions(
                                            keyboardType = KeyboardType.Number,
                                        ),
                                        supportingText =
                                        if (newProblemGrade.isBlank()) {
                                            {
                                                Text(
                                                    "Grade is required",
                                                    color =
                                                    MaterialTheme
                                                        .colorScheme
                                                        .error,
                                                )
                                            }
                                        } else {
                                            {
                                                Text(
                                                    "Custom grades must be whole numbers",
                                                    color =
                                                    MaterialTheme
                                                        .colorScheme
                                                        .onSurfaceVariant,
                                                )
                                            }
                                        },
                                    )
                                } else {
                                    var expanded by remember { mutableStateOf(false) }
                                    val availableGrades = selectedDifficultySystem.availableGrades

                                    ExposedDropdownMenuBox(
                                        expanded = expanded,
                                        onExpandedChange = { expanded = !expanded },
                                        modifier = Modifier.fillMaxWidth(),
                                    ) {
                                        OutlinedTextField(
                                            value = newProblemGrade,
                                            onValueChange = {},
                                            readOnly = true,
                                            label = { Text("Grade *") },
                                            trailingIcon = {
                                                ExposedDropdownMenuDefaults.TrailingIcon(
                                                    expanded = expanded,
                                                )
                                            },
                                            colors =
                                            ExposedDropdownMenuDefaults
                                                .outlinedTextFieldColors(),
                                            modifier =
                                            Modifier.menuAnchor(
                                                ExposedDropdownMenuAnchorType
                                                    .PrimaryNotEditable,
                                                enabled = true,
                                            )
                                                .fillMaxWidth(),
                                            isError = newProblemGrade.isBlank(),
                                            supportingText =
                                            if (newProblemGrade.isBlank()) {
                                                {
                                                    Text(
                                                        "Grade is required",
                                                        color =
                                                        MaterialTheme
                                                            .colorScheme
                                                            .error,
                                                    )
                                                }
                                            } else {
                                                null
                                            },
                                        )
                                        ExposedDropdownMenu(
                                            expanded = expanded,
                                            onDismissRequest = { expanded = false },
                                        ) {
                                            availableGrades.forEach { grade ->
                                                DropdownMenuItem(
                                                    text = { Text(grade) },
                                                    onClick = {
                                                        newProblemGrade = grade
                                                        expanded = false
                                                    },
                                                )
                                            }
                                        }
                                    }
                                }

                                // Photos Section
                                Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
                                    Text(
                                        text = "Photos (Optional)",
                                        style = MaterialTheme.typography.bodyLarge,
                                        fontWeight = FontWeight.Medium,
                                        color = MaterialTheme.colorScheme.onSurface,
                                    )
                                    ImagePicker(
                                        imageUris = newProblemImagePaths,
                                        onImagesChanged = { newProblemImagePaths = it },
                                        maxImages = 5,
                                    )
                                }
                            }
                        }
                    }

                    // 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,
                                                        imagePaths =
                                                        newProblemImagePaths,
                                                    )

                                                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)

                                                // Reset form
                                                newProblemName = ""
                                                newProblemGrade = ""
                                                newProblemImagePaths = emptyList()
                                                showCreateProblem = false
                                            }
                                        } 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) }
                            }
                        }
                    }
                }
            }
        }
    }
}
