package com.atridad.openclimb.ui.components

import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.rounded.Close
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.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.atridad.openclimb.data.model.ClimbSession
import com.atridad.openclimb.data.model.Gym
import java.time.LocalDateTime
import java.time.temporal.ChronoUnit

@Composable
fun ActiveSessionBanner(
    activeSession: ClimbSession?,
    gym: Gym?,
    onSessionClick: () -> Unit,
    onEndSession: () -> Unit
) {    
    if (activeSession != null) {
        Card(
            modifier = Modifier
                .fillMaxWidth()
                .clickable { onSessionClick() },
            colors = CardDefaults.cardColors(
                containerColor = MaterialTheme.colorScheme.primaryContainer
            )
        ) {
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(16.dp),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Column(modifier = Modifier.weight(1f)) {
                    Row(
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Icon(
                            Icons.Default.PlayArrow,
                            contentDescription = "Active session",
                            tint = MaterialTheme.colorScheme.primary,
                            modifier = Modifier.size(16.dp)
                        )
                        Spacer(modifier = Modifier.width(8.dp))
                        Text(
                            text = "Active Session",
                            style = MaterialTheme.typography.titleSmall,
                            fontWeight = FontWeight.Bold,
                            color = MaterialTheme.colorScheme.onPrimaryContainer
                        )
                    }
                    
                    Spacer(modifier = Modifier.height(4.dp))
                    
                    Text(
                        text = gym?.name ?: "Unknown Gym",
                        style = MaterialTheme.typography.bodyMedium,
                        color = MaterialTheme.colorScheme.onPrimaryContainer
                    )
                    
                    activeSession.startTime?.let { startTime ->
                        val duration = calculateDuration(startTime)
                        Text(
                            text = duration,
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.onPrimaryContainer.copy(alpha = 0.8f)
                        )
                    }
                }
                
                IconButton(
                    onClick = onEndSession,
                    colors = IconButtonDefaults.iconButtonColors(
                        containerColor = MaterialTheme.colorScheme.error,
                        contentColor = MaterialTheme.colorScheme.onError
                    )
                ) {
                    Icon(
                        Icons.Default.Close,
                        contentDescription = "End session"
                    )
                }
            }
        }
    }
}

@Composable
fun StartSessionButton(
    gyms: List<Gym>,
    onStartSession: (String) -> Unit
) {
    var showGymSelection by remember { mutableStateOf(false) }
    
    if (gyms.isEmpty()) {
        Card(
            modifier = Modifier.fillMaxWidth(),
            colors = CardDefaults.cardColors(
                containerColor = MaterialTheme.colorScheme.surfaceVariant
            )
        ) {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(16.dp),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                Text(
                    text = "No gyms available",
                    style = MaterialTheme.typography.titleMedium,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
                Text(
                    text = "Add a gym first to start a session",
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }
        }
    } else {
        Button(
            onClick = { showGymSelection = true },
            modifier = Modifier.fillMaxWidth()
        ) {
            Icon(Icons.Default.PlayArrow, contentDescription = null)
            Spacer(modifier = Modifier.width(8.dp))
            Text("Start Session")
        }
    }
    
    if (showGymSelection) {
        AlertDialog(
            onDismissRequest = { showGymSelection = false },
            title = { Text("Select Gym") },
            text = {
                Column {
                    gyms.forEach { gym ->
                        TextButton(
                            onClick = {
                                onStartSession(gym.id)
                                showGymSelection = false
                            },
                            modifier = Modifier.fillMaxWidth()
                        ) {
                            Text(
                                text = gym.name,
                                modifier = Modifier.fillMaxWidth()
                            )
                        }
                    }
                }
            },
            confirmButton = {
                TextButton(onClick = { showGymSelection = false }) {
                    Text("Cancel")
                }
            }
        )
    }
}

private fun calculateDuration(startTimeString: String): String {
    return try {
        val startTime = LocalDateTime.parse(startTimeString)
        val now = LocalDateTime.now()
        val minutes = ChronoUnit.MINUTES.between(startTime, now)
        val hours = minutes / 60
        val remainingMinutes = minutes % 60
        
        when {
            hours > 0 -> "${hours}h ${remainingMinutes}m"
            remainingMinutes > 0 -> "${remainingMinutes}m"
            else -> "< 1m"
        }
    } catch (e: Exception) {
        "Active"
    }
}
