package app.closer.ui.dates

import app.closer.ui.theme.closerCardColor
import app.closer.ui.theme.closerBackgroundBrush
import app.closer.ui.theme.closerSoftPinkColor
import app.closer.ui.theme.closerSoftPurpleColor
import app.closer.ui.theme.closerSoftSurfaceColor
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.height
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.layout.statusBarsPadding
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.filled.Favorite
import androidx.compose.material.icons.filled.Star
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
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.domain.model.DateCostLevel
import app.closer.domain.model.DateIdea
import app.closer.domain.model.DateMatch
import app.closer.domain.model.DateMatchSuggestion
import app.closer.domain.model.SwipeAction
import app.closer.ui.components.EmptyState
import app.closer.ui.components.ErrorState
import app.closer.ui.components.LoadingState

@Composable
fun DateMatchesScreen(
    onNavigate: (String) -> Unit = {},
    viewModel: DateMatchesViewModel = hiltViewModel()
) {
    val state by viewModel.uiState.collectAsState()

    DateMatchesContent(
        state = state,
        onRetry = viewModel::retry,
        onBack = { onNavigate("back") }
    )
}

@Composable
private fun DateMatchesContent(
    state: DateMatchesUiState,
    onRetry: () -> Unit,
    onBack: () -> Unit
) {
    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(
                closerBackgroundBrush()
            )
    ) {
        LazyColumn(
            modifier = Modifier
                .fillMaxSize()
                .safeDrawingPadding()
                .navigationBarsPadding()
                .padding(horizontal = 20.dp),
            verticalArrangement = Arrangement.spacedBy(12.dp)
        ) {
            item {
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .statusBarsPadding()
                        .padding(top = 20.dp, bottom = 6.dp),
                    verticalArrangement = Arrangement.spacedBy(6.dp)
                ) {
                    Text(
                        text = "Your Matches",
                        style = MaterialTheme.typography.headlineLarge.copy(fontWeight = FontWeight.SemiBold),
                        color = MaterialTheme.colorScheme.onSurface
                    )
                    Text(
                        text = state.partnerName?.let { "Ideas you and $it both love" }
                            ?: "Mutual love matches appear here",
                        style = MaterialTheme.typography.bodyLarge,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
            }

            when {
                state.isLoading -> item {
                    LoadingState(
                        message = "Loading matches…",
                        modifier = Modifier.padding(top = 80.dp)
                    )
                }

                state.error != null -> item {
                    ErrorState(
                        title = "Couldn't load your matches",
                        message = state.error ?: "Pull down to try again.",
                        onRetry = onRetry,
                        modifier = Modifier.padding(top = 80.dp)
                    )
                }

                state.mutualMatches.isEmpty() && state.maybeMatches.isEmpty() -> item {
                    EmptyState(
                        title = "No mutual matches yet",
                        body = buildString {
                            append("Swipe through date ideas — when you and ")
                            append(state.partnerName ?: "your partner")
                            append(" both love the same one, it shows up here as a match.")
                        },
                        modifier = Modifier.padding(top = 80.dp)
                    )
                }

                else -> {
                    if (state.mutualMatches.isNotEmpty()) {
                        item {
                            SectionHeader(
                                title = "Mutual love",
                                count = state.mutualMatches.size,
                                icon = Icons.Filled.Favorite,
                                iconColor = Color(0xFF9B1B5A),
                                modifier = Modifier.padding(top = 8.dp)
                            )
                        }
                        items(state.mutualMatches, key = { it.id }) { match ->
                            MatchCard(match = match)
                        }
                    }

                    if (state.maybeMatches.isNotEmpty()) {
                        item {
                            SectionHeader(
                                title = "Maybe together",
                                count = state.maybeMatches.size,
                                icon = Icons.Filled.Star,
                                iconColor = Color(0xFF6B5D00),
                                modifier = Modifier.padding(top = 8.dp)
                            )
                        }
                        items(state.maybeMatches, key = { it.dateIdeaId }) { suggestion ->
                            SuggestionCard(suggestion = suggestion)
                        }
                    }

                    item { Box(modifier = Modifier.padding(bottom = 24.dp)) }
                }
            }
        }
    }
}

@Composable
private fun SectionHeader(
    title: String,
    count: Int,
    icon: androidx.compose.ui.graphics.vector.ImageVector,
    iconColor: Color,
    modifier: Modifier = Modifier
) {
    Row(
        modifier = modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.CenterVertically
    ) {
        Row(
            horizontalArrangement = Arrangement.spacedBy(8.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Icon(
                imageVector = icon,
                contentDescription = null,
                tint = iconColor,
                modifier = Modifier.size(20.dp)
            )
            Text(
                text = title,
                style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.SemiBold),
                color = MaterialTheme.colorScheme.onSurface
            )
        }
        Surface(
            shape = RoundedCornerShape(999.dp),
            color = closerSoftSurfaceColor()
        ) {
            Text(
                text = count.toString(),
                modifier = Modifier.padding(horizontal = 11.dp, vertical = 5.dp),
                style = MaterialTheme.typography.labelMedium,
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )
        }
    }
}

@Composable
private fun MatchCard(match: DateMatch) {
    val idea = match.dateIdea ?: return
    IdeaCard(
        idea = idea,
        badge = {
            Surface(
                shape = RoundedCornerShape(999.dp),
                color = closerSoftPinkColor()
            ) {
                Row(
                    modifier = Modifier.padding(horizontal = 10.dp, vertical = 6.dp),
                    horizontalArrangement = Arrangement.spacedBy(4.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Icon(
                        imageVector = Icons.Filled.Favorite,
                        contentDescription = null,
                        modifier = Modifier.size(14.dp),
                        tint = Color(0xFF9B1B5A)
                    )
                    Text(
                        text = "Matched",
                        style = MaterialTheme.typography.labelSmall,
                        color = Color(0xFF9B1B5A),
                        fontWeight = FontWeight.SemiBold
                    )
                }
            }
        }
    )
}

@Composable
private fun SuggestionCard(suggestion: DateMatchSuggestion) {
    IdeaCard(
        idea = suggestion.dateIdea,
        badge = {
            Surface(
                shape = RoundedCornerShape(999.dp),
                color = MaterialTheme.colorScheme.tertiaryContainer.copy(alpha = 0.74f)
            ) {
                Row(
                    modifier = Modifier.padding(horizontal = 10.dp, vertical = 6.dp),
                    horizontalArrangement = Arrangement.spacedBy(4.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Icon(
                        imageVector = Icons.Filled.Star,
                        contentDescription = null,
                        modifier = Modifier.size(14.dp),
                        tint = Color(0xFF6B5D00)
                    )
                    Text(
                        text = if (suggestion.partnerAction == SwipeAction.LOVE) "They love it" else "Maybe match",
                        style = MaterialTheme.typography.labelSmall,
                        color = Color(0xFF6B5D00),
                        fontWeight = FontWeight.SemiBold
                    )
                }
            }
        }
    )
}

@Composable
private fun IdeaCard(
    idea: DateIdea,
    badge: @Composable () -> Unit
) {
    Card(
        modifier = Modifier.fillMaxWidth(),
        shape = RoundedCornerShape(24.dp),
        colors = CardDefaults.cardColors(containerColor = closerCardColor(alpha = 0.92f)),
        elevation = CardDefaults.cardElevation(defaultElevation = 3.dp)
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(18.dp),
            verticalArrangement = Arrangement.spacedBy(12.dp)
        ) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Surface(
                    shape = RoundedCornerShape(999.dp),
                    color = closerSoftPurpleColor()
                ) {
                    Text(
                        text = idea.category.displayDateCategory(),
                        modifier = Modifier.padding(horizontal = 11.dp, vertical = 7.dp),
                        style = MaterialTheme.typography.labelMedium,
                        color = MaterialTheme.colorScheme.onPrimaryContainer,
                        fontWeight = FontWeight.SemiBold,
                        maxLines = 1,
                        overflow = TextOverflow.Ellipsis
                    )
                }
                badge()
            }

            Text(
                text = idea.title,
                style = MaterialTheme.typography.titleLarge.copy(fontWeight = FontWeight.SemiBold),
                color = MaterialTheme.colorScheme.onSurface,
                maxLines = 2,
                overflow = TextOverflow.Ellipsis
            )

            Text(
                text = idea.description,
                style = MaterialTheme.typography.bodyMedium,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
                maxLines = 3,
                overflow = TextOverflow.Ellipsis
            )

            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                InfoChip(label = idea.estimatedDuration)
                InfoChip(label = idea.estimatedCost.displayLabel())
                if (idea.isPremium) {
                    InfoChip(label = "Premium", emphasis = true)
                }
            }
        }
    }
}

@Composable
private fun InfoChip(
    label: String,
    emphasis: Boolean = false
) {
    Surface(
        shape = RoundedCornerShape(12.dp),
        color = if (emphasis) closerSoftPinkColor() else closerSoftSurfaceColor()
    ) {
        Text(
            text = label,
            modifier = Modifier.padding(horizontal = 10.dp, vertical = 6.dp),
            style = MaterialTheme.typography.labelMedium,
            color = if (emphasis) MaterialTheme.colorScheme.onSecondaryContainer else MaterialTheme.colorScheme.onSurfaceVariant,
            fontWeight = if (emphasis) FontWeight.SemiBold else FontWeight.Medium
        )
    }
}

private fun String.displayDateCategory(): String =
    replace("_", " ")
        .split(" ")
        .joinToString(" ") { it.replaceFirstChar { c -> c.uppercaseChar() } }

private fun DateCostLevel.displayLabel(): String = when (this) {
    DateCostLevel.FREE -> "Free"
    DateCostLevel.LOW -> "$"
    DateCostLevel.MEDIUM -> "$$"
    DateCostLevel.HIGH -> "$$$"
}
