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.platform.LocalContext
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.ClimbSession
import com.atridad.openclimb.data.model.SessionStatus
import com.atridad.openclimb.ui.components.ActiveSessionBanner
import com.atridad.openclimb.ui.viewmodel.ClimbViewModel
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SessionsScreen(
    viewModel: ClimbViewModel,
    onNavigateToSessionDetail: (String) -> Unit,
    onNavigateToAddSession: (String?) -> Unit
) {
    val context = LocalContext.current
    val sessions by viewModel.sessions.collectAsState()
    val gyms by viewModel.gyms.collectAsState()
    val activeSession by viewModel.activeSession.collectAsState()
    
    // Filter out active sessions from regular session list
    val completedSessions = sessions.filter { it.status == SessionStatus.COMPLETED }
    val activeSessionGym = activeSession?.let { session ->
        gyms.find { it.id == session.gymId }
    }
    
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp)
    ) {
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(
                text = "Climbing Sessions",
                style = MaterialTheme.typography.headlineMedium,
                fontWeight = FontWeight.Bold
            )
            

        }
        
        Spacer(modifier = Modifier.height(16.dp))
        
        // Active session banner
        ActiveSessionBanner(
            activeSession = activeSession,
            gym = activeSessionGym,
            onSessionClick = {
                activeSession?.let { onNavigateToSessionDetail(it.id) }
            },
            onEndSession = {
                activeSession?.let { 
                    viewModel.endSession(context, it.id)
                }
            }
        )
        
        if (activeSession != null) {
            Spacer(modifier = Modifier.height(16.dp))
        }
        
        if (completedSessions.isEmpty() && activeSession == null) {
            EmptyStateMessage(
                title = if (gyms.isEmpty()) "No Gyms Available" else "No Sessions Yet",
                message = if (gyms.isEmpty()) "Add a gym first to start tracking your climbing sessions!" else "Start your first climbing session!",
                onActionClick = { },
                actionText = ""
            )
        } else {
            LazyColumn {
                items(completedSessions) { session ->
                    SessionCard(
                        session = session,
                        gymName = gyms.find { it.id == session.gymId }?.name ?: "Unknown Gym",
                        onClick = { onNavigateToSessionDetail(session.id) }
                    )
                    Spacer(modifier = Modifier.height(8.dp))
                }
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SessionCard(
    session: ClimbSession,
    gymName: String,
    onClick: () -> Unit
) {
    Card(
        onClick = onClick,
        modifier = Modifier.fillMaxWidth()
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp)
        ) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween
            ) {
                Text(
                    text = gymName,
                    style = MaterialTheme.typography.titleMedium,
                    fontWeight = FontWeight.Bold
                )
                Text(
                    text = formatDate(session.date),
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }
            
            Spacer(modifier = Modifier.height(4.dp))
            
            session.duration?.let { duration ->
                Text(
                    text = "Duration: ${duration} minutes",
                    style = MaterialTheme.typography.bodyMedium
                )
            }
            
            session.notes?.let { notes ->
                if (notes.isNotBlank()) {
                    Spacer(modifier = Modifier.height(4.dp))
                    Text(
                        text = notes,
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                        maxLines = 2
                    )
                }
            }
        }
    }
}

@Composable
fun EmptyStateMessage(
    title: String,
    message: String,
    onActionClick: () -> Unit,
    actionText: String
) {
    Column(
        modifier = Modifier.fillMaxSize(),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        Text(
            text = title,
            style = MaterialTheme.typography.headlineSmall,
            fontWeight = FontWeight.Bold,
            textAlign = TextAlign.Center
        )
        
        Spacer(modifier = Modifier.height(8.dp))
        
        Text(
            text = message,
            style = MaterialTheme.typography.bodyLarge,
            color = MaterialTheme.colorScheme.onSurfaceVariant,
            textAlign = TextAlign.Center
        )
        
        if (actionText.isNotEmpty()) {
            Spacer(modifier = Modifier.height(16.dp))
            
            Button(onClick = onActionClick) {
                Text(actionText)
            }
        }
    }
}

private fun formatDate(dateString: String): String {
    return try {
        val date = LocalDateTime.parse(dateString.split("T")[0] + "T00:00:00")
        date.format(DateTimeFormatter.ofPattern("MMM dd, yyyy"))
    } catch (e: Exception) {
        dateString
    }
}
