package com.atridad.ascently.ui.components

import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.PlayArrow
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.ascently.data.model.ClimbSession
import com.atridad.ascently.data.model.Gym
import com.atridad.ascently.ui.theme.CustomIcons
import com.atridad.ascently.utils.DateFormatUtils
import kotlinx.coroutines.delay
import java.time.Instant
import java.time.temporal.ChronoUnit

@Composable
fun ActiveSessionBanner(
    activeSession: ClimbSession?,
    gym: Gym?,
    onSessionClick: () -> Unit,
    onEndSession: () -> Unit,
    modifier: Modifier = Modifier,
) {
    if (activeSession == null) return

    val sessionId = activeSession.id
    val startTimeString = activeSession.startTime
    val gymName = gym?.name ?: "Unknown Gym"

    var elapsedSeconds by remember(sessionId) { mutableLongStateOf(0L) }

    LaunchedEffect(sessionId, startTimeString) {
        if (startTimeString == null) return@LaunchedEffect

        while (true) {
            elapsedSeconds = calculateElapsedSeconds(startTimeString)
            delay(1000)
        }
    }

    val durationText = remember(elapsedSeconds) {
        formatDuration(elapsedSeconds)
    }

    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 = null,
                        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 = gymName,
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onPrimaryContainer,
                )

                if (startTimeString != null) {
                    Text(
                        text = durationText,
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onPrimaryContainer.copy(alpha = 0.8f),
                    )
                }
            }

            FilledIconButton(
                onClick = onEndSession,
                colors = IconButtonDefaults.filledIconButtonColors(
                    containerColor = MaterialTheme.colorScheme.error,
                    contentColor = MaterialTheme.colorScheme.onError,
                ),
            ) {
                Icon(
                    imageVector = CustomIcons.Stop(MaterialTheme.colorScheme.onError),
                    contentDescription = "End session",
                )
            }
        }
    }
}

private fun calculateElapsedSeconds(startTimeString: String): Long {
    return try {
        val startTime = DateFormatUtils.parseISO8601(startTimeString) ?: return 0L
        val now = Instant.now()
        ChronoUnit.SECONDS.between(startTime, now).coerceAtLeast(0)
    } catch (_: Exception) {
        0L
    }
}

private fun formatDuration(totalSeconds: Long): String {
    val hours = totalSeconds / 3600
    val minutes = (totalSeconds % 3600) / 60
    val seconds = totalSeconds % 60

    return when {
        hours > 0 -> "${hours}h ${minutes}m ${seconds}s"
        minutes > 0 -> "${minutes}m ${seconds}s"
        else -> "${seconds}s"
    }
}
