package com.atridad.openclimb.ui.screens

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
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.unit.dp
import com.atridad.openclimb.ui.viewmodel.ClimbViewModel

@Composable
fun AnalyticsScreen(
    viewModel: ClimbViewModel
) {
    val sessions by viewModel.sessions.collectAsState()
    val problems by viewModel.problems.collectAsState()
    val attempts by viewModel.attempts.collectAsState()
    val gyms by viewModel.gyms.collectAsState()
    
    LazyColumn(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp),
        verticalArrangement = Arrangement.spacedBy(16.dp)
    ) {
        item {
            Text(
                text = "Analytics",
                style = MaterialTheme.typography.headlineMedium,
                fontWeight = FontWeight.Bold
            )
        }
        
        // Overall Stats
        item {
            OverallStatsCard(
                totalSessions = sessions.size,
                totalProblems = problems.size,
                totalAttempts = attempts.size,
                totalGyms = gyms.size
            )
        }
        
        // Success Rate
        item {
            val successfulAttempts = attempts.count { 
                it.result.name in listOf("SUCCESS", "FLASH", "REDPOINT", "ONSIGHT") 
            }
            val successRate = if (attempts.isNotEmpty()) {
                (successfulAttempts.toDouble() / attempts.size * 100).toInt()
            } else 0
            
            SuccessRateCard(
                successRate = successRate,
                successfulAttempts = successfulAttempts,
                totalAttempts = attempts.size
            )
        }
        
        // Favorite Gym
        item {
            val favoriteGym = sessions
                .groupBy { it.gymId }
                .maxByOrNull { it.value.size }
                ?.let { (gymId, sessions) ->
                    gyms.find { it.id == gymId }?.name to sessions.size
                }
            
            FavoriteGymCard(
                gymName = favoriteGym?.first ?: "No sessions yet",
                sessionCount = favoriteGym?.second ?: 0
            )
        }
        
        // Recent Activity
        item {
            val recentSessions = sessions.take(5)
            RecentActivityCard(recentSessions = recentSessions.size)
        }
        

        item {
            Card(
                modifier = Modifier.fillMaxWidth()
            ) {
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(16.dp),
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    Text(
                        text = "Progress Charts",
                        style = MaterialTheme.typography.titleMedium,
                        fontWeight = FontWeight.Bold
                    )
                    
                    Spacer(modifier = Modifier.height(8.dp))
                    
                    Text(
                        text = "Detailed charts and analytics coming soon!",
                        style = MaterialTheme.typography.bodyMedium,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                    
                    Spacer(modifier = Modifier.height(16.dp))
                    
                    Text(
                        text = "📊",
                        style = MaterialTheme.typography.displaySmall
                    )
                }
            }
        }
    }
}

@Composable
fun OverallStatsCard(
    totalSessions: Int,
    totalProblems: Int,
    totalAttempts: Int,
    totalGyms: Int
) {
    Card(
        modifier = Modifier.fillMaxWidth()
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp)
        ) {
            Text(
                text = "Overall Stats",
                style = MaterialTheme.typography.titleMedium,
                fontWeight = FontWeight.Bold
            )
            
            Spacer(modifier = Modifier.height(12.dp))
            
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceEvenly
            ) {
                StatItem(label = "Sessions", value = totalSessions.toString())
                StatItem(label = "Problems", value = totalProblems.toString())
                StatItem(label = "Attempts", value = totalAttempts.toString())
                StatItem(label = "Gyms", value = totalGyms.toString())
            }
        }
    }
}



@Composable
fun SuccessRateCard(
    successRate: Int,
    successfulAttempts: Int,
    totalAttempts: Int
) {
    Card(
        modifier = Modifier.fillMaxWidth()
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp)
        ) {
            Text(
                text = "Success Rate",
                style = MaterialTheme.typography.titleMedium,
                fontWeight = FontWeight.Bold
            )
            
            Spacer(modifier = Modifier.height(8.dp))
            
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = "$successRate%",
                    style = MaterialTheme.typography.displaySmall,
                    fontWeight = FontWeight.Bold,
                    color = MaterialTheme.colorScheme.primary
                )
                
                Column(horizontalAlignment = Alignment.End) {
                    Text(
                        text = "$successfulAttempts successful",
                        style = MaterialTheme.typography.bodyMedium
                    )
                    Text(
                        text = "out of $totalAttempts attempts",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
            }
        }
    }
}

@Composable
fun FavoriteGymCard(
    gymName: String,
    sessionCount: Int
) {
    Card(
        modifier = Modifier.fillMaxWidth()
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp)
        ) {
            Text(
                text = "Favorite Gym",
                style = MaterialTheme.typography.titleMedium,
                fontWeight = FontWeight.Bold
            )
            
            Spacer(modifier = Modifier.height(8.dp))
            
            Text(
                text = gymName,
                style = MaterialTheme.typography.titleLarge,
                fontWeight = FontWeight.Medium
            )
            
            if (sessionCount > 0) {
                Text(
                    text = "$sessionCount sessions",
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }
        }
    }
}

@Composable
fun RecentActivityCard(
    recentSessions: Int
) {
    Card(
        modifier = Modifier.fillMaxWidth()
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp)
        ) {
            Text(
                text = "Recent Activity",
                style = MaterialTheme.typography.titleMedium,
                fontWeight = FontWeight.Bold
            )
            
            Spacer(modifier = Modifier.height(8.dp))
            
            Text(
                text = if (recentSessions > 0) {
                    "You've had $recentSessions recent sessions"
                } else {
                    "No recent activity"
                },
                style = MaterialTheme.typography.bodyMedium
            )
        }
    }
}
