package com.atridad.openclimb.ui.screens

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import com.atridad.openclimb.data.model.Problem
import com.atridad.openclimb.ui.components.FullscreenImageViewer
import com.atridad.openclimb.ui.components.ImageDisplay
import com.atridad.openclimb.ui.viewmodel.ClimbViewModel

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ProblemsScreen(
    viewModel: ClimbViewModel,
    onNavigateToProblemDetail: (String) -> Unit,
    onNavigateToAddProblem: (String?) -> Unit
) {
    val problems by viewModel.problems.collectAsState()
    val gyms by viewModel.gyms.collectAsState()
    var showImageViewer by remember { mutableStateOf(false) }
    var selectedImagePaths by remember { mutableStateOf<List<String>>(emptyList()) }
    var selectedImageIndex by remember { mutableStateOf(0) }
    
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp)
    ) {
        Text(
            text = "Problems & Routes",
            style = MaterialTheme.typography.headlineMedium,
            fontWeight = FontWeight.Bold
        )
        
        Spacer(modifier = Modifier.height(16.dp))
        
        if (problems.isEmpty()) {
            EmptyStateMessage(
                title = if (gyms.isEmpty()) "No Gyms Available" else "No Problems Yet",
                message = if (gyms.isEmpty()) "Add a gym first to start tracking problems and routes!" else "Start tracking your favorite problems and routes!",
                onActionClick = { },
                actionText = ""
            )
        } else {
            LazyColumn {
                items(problems) { problem ->
                    ProblemCard(
                        problem = problem,
                        gymName = gyms.find { it.id == problem.gymId }?.name ?: "Unknown Gym",
                        onClick = { onNavigateToProblemDetail(problem.id) },
                        onImageClick = { imagePaths, index ->
                            selectedImagePaths = imagePaths
                            selectedImageIndex = index
                            showImageViewer = true
                        }
                    )
                    Spacer(modifier = Modifier.height(8.dp))
                }
            }
        }
    }
    
    // Fullscreen Image Viewer
    if (showImageViewer && selectedImagePaths.isNotEmpty()) {
        FullscreenImageViewer(
            imagePaths = selectedImagePaths,
            initialIndex = selectedImageIndex,
            onDismiss = { showImageViewer = false }
        )
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ProblemCard(
    problem: Problem,
    gymName: String,
    onClick: () -> Unit,
    onImageClick: ((List<String>, Int) -> Unit)? = null
) {
    Card(
        onClick = onClick,
        modifier = Modifier.fillMaxWidth()
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp)
        ) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.Top
            ) {
                Column(modifier = Modifier.weight(1f)) {
                    Text(
                        text = problem.name ?: "Unnamed Problem",
                        style = MaterialTheme.typography.titleMedium,
                        fontWeight = FontWeight.Bold
                    )
                    
                    Text(
                        text = gymName,
                        style = MaterialTheme.typography.bodyMedium,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
                
                Column(horizontalAlignment = Alignment.End) {
                    Text(
                        text = problem.difficulty.grade,
                        style = MaterialTheme.typography.titleMedium,
                        fontWeight = FontWeight.Bold,
                        color = MaterialTheme.colorScheme.primary
                    )
                    
                    Text(
                        text = problem.climbType.name.lowercase().replaceFirstChar { it.uppercase() },
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
            }
            
            problem.location?.let { location ->
                Spacer(modifier = Modifier.height(4.dp))
                Text(
                    text = "Location: $location",
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }
            
            if (problem.tags.isNotEmpty()) {
                Spacer(modifier = Modifier.height(8.dp))
                Row {
                    problem.tags.take(3).forEach { tag ->
                        AssistChip(
                            onClick = { },
                            label = { Text(tag) },
                            modifier = Modifier.padding(end = 4.dp)
                        )
                    }
                }
            }
            
            // Display images if any
            if (problem.imagePaths.isNotEmpty()) {
                Spacer(modifier = Modifier.height(8.dp))
                ImageDisplay(
                    imagePaths = problem.imagePaths.take(3), // Show max 3 images in list
                    imageSize = 60,
                    onImageClick = { index ->
                        onImageClick?.invoke(problem.imagePaths, index)
                    }
                )
            }
            
            if (!problem.isActive) {
                Spacer(modifier = Modifier.height(8.dp))
                Text(
                    text = "Inactive",
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.error
                )
            }
        }
    }
}
