package app.closer.ui.wheel

import app.closer.ui.theme.closerCardColor
import app.closer.ui.theme.closerBackgroundBrush
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.safeDrawingPadding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Lock
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import app.closer.core.navigation.AppRoute
import app.closer.domain.model.GameType
import app.closer.domain.model.QuestionSession
import app.closer.domain.model.TimeCapsule
import app.closer.ui.components.EmptyState
import app.closer.ui.components.ErrorState
import app.closer.ui.components.LoadingState
import app.closer.ui.questions.displayCategoryName
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun GameHistoryScreen(
    onNavigate: (String) -> Unit = {},
    viewModel: GameHistoryViewModel = hiltViewModel()
) {
    val state by viewModel.uiState.collectAsState()

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("Past Games") },
                navigationIcon = {
                    IconButton(onClick = { onNavigate("back") }) {
                        Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")
                    }
                }
            )
        }
    ) { padding ->
        Box(
            modifier = Modifier
                .fillMaxSize()
                .background(
                    closerBackgroundBrush()
                )
        ) {
            LazyColumn(
                modifier = Modifier
                    .fillMaxSize()
                    .safeDrawingPadding()
                    .navigationBarsPadding()
                    .padding(padding)
                    .padding(horizontal = 20.dp),
                verticalArrangement = Arrangement.spacedBy(14.dp)
            ) {
                item {
                    Text(
                        text = "Past games",
                        style = MaterialTheme.typography.headlineMedium.copy(fontWeight = FontWeight.SemiBold),
                        color = MaterialTheme.colorScheme.onSurface,
                        modifier = Modifier.padding(top = 20.dp, bottom = 4.dp)
                    )
                }

                val hasAny = state.sessions.isNotEmpty() || state.completedChallenges.isNotEmpty() || state.unlockedCapsules.isNotEmpty()

                when {
                    !state.hasPremium -> item {
                        GameHistoryLockedCard(onUnlock = { onNavigate(AppRoute.PAYWALL) })
                    }
                    state.isLoading -> item { LoadingState(message = "Loading your games…") }
                    !hasAny && state.error != null -> item {
                        ErrorState(
                            message = state.error!!,
                            onRetry = viewModel::load
                        )
                    }
                    !hasAny -> item {
                        EmptyState(
                            title = "No games played yet",
                            body = "Finish a round of This or That, How Well, Desire Sync, Spin the Wheel, a Connection Challenge, or Memory Lane — your results will show up here.",
                            actionLabel = "Play a game",
                            onAction = { onNavigate(AppRoute.PLAY) }
                        )
                    }
                    else -> {
                        if (state.sessions.isNotEmpty()) {
                            item { HistorySectionHeader("Game Sessions") }
                            items(state.sessions, key = { it.id }) { session ->
                                WheelSessionCard(
                                    session = session,
                                    onClick = sessionReplayRoute(session)?.let { route -> { onNavigate(route) } }
                                )
                            }
                        } else if (state.error != null) {
                            item {
                                Card(
                                    modifier = Modifier.fillMaxWidth(),
                                    shape = androidx.compose.foundation.shape.RoundedCornerShape(16.dp),
                                    colors = CardDefaults.cardColors(
                                        containerColor = MaterialTheme.colorScheme.errorContainer.copy(alpha = 0.5f)
                                    )
                                ) {
                                    Row(
                                        modifier = Modifier
                                            .fillMaxWidth()
                                            .padding(horizontal = 16.dp, vertical = 10.dp),
                                        horizontalArrangement = Arrangement.SpaceBetween,
                                        verticalAlignment = Alignment.CenterVertically
                                    ) {
                                        Text(
                                            text = "Couldn't load game sessions",
                                            style = MaterialTheme.typography.bodySmall,
                                            color = MaterialTheme.colorScheme.onErrorContainer,
                                            modifier = Modifier.weight(1f)
                                        )
                                        TextButton(onClick = viewModel::load) {
                                            Text("Retry", color = MaterialTheme.colorScheme.error)
                                        }
                                    }
                                }
                            }
                        }
                        if (state.completedChallenges.isNotEmpty()) {
                            item { HistorySectionHeader("Completed Challenges") }
                            items(state.completedChallenges, key = { it.challengeId }) { entry ->
                                ChallengeHistoryCard(entry, onClick = { onNavigate(AppRoute.CONNECTION_CHALLENGES) })
                            }
                        }
                        if (state.unlockedCapsules.isNotEmpty()) {
                            item { HistorySectionHeader("Memory Lane") }
                            items(state.unlockedCapsules, key = { it.id }) { capsule ->
                                CapsuleHistoryCard(capsule, onClick = { onNavigate(AppRoute.memorylaneDetail(capsule.id)) })
                            }
                        }
                    }
                }
            }
        }
    }
}

@Composable
private fun WheelSessionCard(session: QuestionSession, onClick: (() -> Unit)?) {
    val replayable = onClick != null
    Card(
        onClick = onClick ?: {},
        enabled = replayable,
        modifier = Modifier.fillMaxWidth(),
        shape = RoundedCornerShape(20.dp),
        colors = CardDefaults.cardColors(containerColor = closerCardColor(alpha = 0.88f)),
        elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
    ) {
        Row(
            modifier = Modifier.padding(16.dp),
            horizontalArrangement = Arrangement.spacedBy(14.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(sessionEmoji(session), style = MaterialTheme.typography.headlineSmall)
            Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) {
                Text(
                    text = sessionTitle(session),
                    style = MaterialTheme.typography.titleMedium,
                    fontWeight = FontWeight.SemiBold,
                    color = MaterialTheme.colorScheme.onSurface
                )
                Text(
                    text = if (replayable) "${session.questionIds.size} questions" else "Replay not available",
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }
            session.completedAt?.let { ts ->
                Text(
                    text = SimpleDateFormat("d MMM", Locale.getDefault()).format(Date(ts)),
                    style = MaterialTheme.typography.labelMedium,
                    color = Color(0xFFB98AF4)
                )
            }
        }
    }
}

@Composable
private fun HistorySectionHeader(title: String) {
    Text(
        text = title,
        style = MaterialTheme.typography.titleSmall,
        fontWeight = FontWeight.SemiBold,
        color = MaterialTheme.colorScheme.onSurfaceVariant,
        modifier = Modifier.padding(top = 8.dp, bottom = 2.dp)
    )
}

@Composable
private fun ChallengeHistoryCard(entry: CompletedChallengeEntry, onClick: (() -> Unit)? = null) {
    Card(
        onClick = onClick ?: {},
        enabled = onClick != null,
        modifier = Modifier.fillMaxWidth(),
        shape = RoundedCornerShape(20.dp),
        colors = CardDefaults.cardColors(containerColor = closerCardColor(alpha = 0.88f)),
        elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
    ) {
        Row(
            modifier = Modifier.padding(16.dp),
            horizontalArrangement = Arrangement.spacedBy(14.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(entry.emoji, style = MaterialTheme.typography.headlineSmall)
            Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) {
                Text(
                    text = entry.title,
                    style = MaterialTheme.typography.titleMedium,
                    fontWeight = FontWeight.SemiBold,
                    color = MaterialTheme.colorScheme.onSurface
                )
                Text(
                    text = "Challenge complete",
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }
            if (entry.startedAt > 0L) {
                Text(
                    text = SimpleDateFormat("d MMM", java.util.Locale.getDefault()).format(Date(entry.startedAt)),
                    style = MaterialTheme.typography.labelMedium,
                    color = Color(0xFFB98AF4)
                )
            }
        }
    }
}

@Composable
private fun CapsuleHistoryCard(capsule: TimeCapsule, onClick: (() -> Unit)? = null) {
    Card(
        onClick = onClick ?: {},
        enabled = onClick != null,
        modifier = Modifier.fillMaxWidth(),
        shape = RoundedCornerShape(20.dp),
        colors = CardDefaults.cardColors(containerColor = closerCardColor(alpha = 0.88f)),
        elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
    ) {
        Row(
            modifier = Modifier.padding(16.dp),
            horizontalArrangement = Arrangement.spacedBy(14.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text("💌", style = MaterialTheme.typography.headlineSmall)
            Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) {
                Text(
                    text = capsule.title.ifBlank { "Untitled capsule" },
                    style = MaterialTheme.typography.titleMedium,
                    fontWeight = FontWeight.SemiBold,
                    color = MaterialTheme.colorScheme.onSurface,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis
                )
                Text(
                    text = "Memory Lane",
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }
            if (capsule.unlockAt > 0L) {
                Text(
                    text = SimpleDateFormat("d MMM", java.util.Locale.getDefault()).format(Date(capsule.unlockAt)),
                    style = MaterialTheme.typography.labelMedium,
                    color = Color(0xFFB98AF4)
                )
            }
        }
    }
}

private fun sessionTitle(session: QuestionSession): String = when (session.gameType) {
    GameType.THIS_OR_THAT -> "This or That"
    GameType.HOW_WELL -> "How Well Do You Know Me"
    GameType.DESIRE_SYNC -> "Desire Sync"
    GameType.WHEEL -> session.categoryId.displayCategoryName().ifBlank { "Spin Wheel" }
    else -> "Game Session"
}

private fun sessionEmoji(session: QuestionSession): String = when (session.gameType) {
    GameType.THIS_OR_THAT -> "🔀"
    GameType.HOW_WELL -> "🎯"
    GameType.DESIRE_SYNC -> "💋"
    GameType.WHEEL -> "🎡"
    else -> "🎮"
}

private fun sessionReplayRoute(session: QuestionSession): String? = when (session.gameType) {
    GameType.THIS_OR_THAT -> AppRoute.thisOrThatReplay(session.id)
    GameType.HOW_WELL -> AppRoute.howWellReplay(session.id)
    GameType.DESIRE_SYNC -> AppRoute.desireSyncReplay(session.id)
    GameType.WHEEL -> AppRoute.wheelComplete(session.id)
    else -> null  // no replay screen for this game type
}

@Composable
private fun GameHistoryLockedCard(onUnlock: () -> Unit) {
    Card(
        modifier = Modifier.fillMaxWidth(),
        shape = RoundedCornerShape(24.dp),
        colors = CardDefaults.cardColors(containerColor = closerCardColor(alpha = 0.86f)),
        elevation = CardDefaults.cardElevation(defaultElevation = 6.dp)
    ) {
        Column(
            modifier = Modifier.padding(24.dp),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            Surface(
                shape = RoundedCornerShape(50.dp),
                color = Color(0xFFF8F1FF)
            ) {
                Icon(
                    Icons.Filled.Lock,
                    contentDescription = null,
                    modifier = Modifier.padding(16.dp).size(28.dp),
                    tint = Color(0xFFB98AF4)
                )
            }
            Text(
                text = "History is a premium feature",
                style = MaterialTheme.typography.titleMedium,
                fontWeight = FontWeight.SemiBold,
                color = MaterialTheme.colorScheme.onSurface,
                maxLines = 2,
                overflow = TextOverflow.Ellipsis
            )
            Text(
                text = "Unlock to browse all your past game results together.",
                style = MaterialTheme.typography.bodyMedium,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
                maxLines = 3,
                overflow = TextOverflow.Ellipsis
            )
            Button(
                onClick = onUnlock,
                modifier = Modifier
                    .fillMaxWidth()
                    .heightIn(min = 52.dp),
                shape = RoundedCornerShape(16.dp),
                colors = ButtonDefaults.buttonColors(
                    containerColor = Color(0xFFB98AF4),
                    contentColor = MaterialTheme.colorScheme.onPrimary
                )
            ) {
                Text("Unlock premium", color = MaterialTheme.colorScheme.onPrimary)
            }
        }
    }
}
