package app.closer.ui.questions

import app.closer.ui.theme.closerCardColor
import app.closer.ui.theme.closerBackgroundBrush
import app.closer.ui.theme.closerSoftPurpleColor
import app.closer.ui.theme.closerSoftSurfaceColor
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.horizontalScroll
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.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.rememberScrollState
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import app.closer.ui.components.CloserHeartLoader
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.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import app.closer.R
import app.closer.core.navigation.AppRoute
import app.closer.domain.model.QuestionCategory
import app.closer.ui.components.CategoryGlyph

private enum class PackFilter(val label: String) {
    ALL("All"),
    FREE("Free"),
    MIXED("Mixed"),
    PREMIUM("Premium")
}

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

    QuestionPackLibraryContent(
        state = state,
        onPackSelected = { onNavigate(AppRoute.questionCategory(it.category.id)) },
        onPaywall = { onNavigate(AppRoute.PAYWALL) }
    )
}

@Composable
private fun QuestionPackLibraryContent(
    state: QuestionPackLibraryUiState,
    onPackSelected: (QuestionPackItem) -> Unit,
    onPaywall: () -> Unit
) {
    var selectedFilter by remember { mutableStateOf(PackFilter.ALL) }
    val visiblePacks = remember(state.packs, selectedFilter) {
        state.packs.filter { item ->
            when (selectedFilter) {
                PackFilter.ALL -> true
                PackFilter.FREE -> item.category.access == "free"
                PackFilter.MIXED -> item.category.access == "mixed"
                PackFilter.PREMIUM -> item.category.access == "premium"
            }
        }
    }

    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(
                closerBackgroundBrush()
            )
    ) {
        LazyColumn(
            modifier = Modifier
                .fillMaxSize()
                .safeDrawingPadding()
                .navigationBarsPadding()
                .padding(horizontal = 20.dp),
            verticalArrangement = Arrangement.spacedBy(14.dp)
        ) {
            item {
                Column(
                    modifier = Modifier.padding(top = 20.dp, bottom = 4.dp),
                    verticalArrangement = Arrangement.spacedBy(10.dp)
                ) {
                    Text(
                        text = "Pick a doorway",
                        style = MaterialTheme.typography.headlineLarge.copy(fontWeight = FontWeight.SemiBold),
                        color = MaterialTheme.colorScheme.onSurface,
                        maxLines = 2,
                        overflow = TextOverflow.Ellipsis
                    )
                    Text(
                        text = "Choose a question pack by the kind of conversation you want to open together.",
                        style = MaterialTheme.typography.bodyLarge,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                        maxLines = 3,
                        overflow = TextOverflow.Ellipsis
                    )
                }
            }

            when {
                state.isLoading -> item { LoadingPackCard() }
                state.error != null -> item {
                    PackMessageCard(
                        title = "Packs paused",
                        message = state.error
                    )
                }
                state.packs.isEmpty() -> item {
                    PackMessageCard(
                        title = "No packs found",
                        message = "Question packs are not available right now. Try again in a moment."
                    )
                }
                visiblePacks.isEmpty() -> {
                    item {
                        PackFilterRow(
                            selected = selectedFilter,
                            onSelected = { selectedFilter = it }
                        )
                    }
                    item {
                        PackMessageCard(
                            title = "Nothing in ${selectedFilter.label.lowercase()} yet",
                            message = "Try another filter to keep browsing."
                        )
                    }
                }
                else -> {
                    item {
                        PackFilterRow(
                            selected = selectedFilter,
                            onSelected = { selectedFilter = it }
                        )
                    }
                    items(visiblePacks, key = { it.category.id }) { item ->
                        QuestionPackCard(
                            item = item,
                            onClick = {
                                if (item.isLocked) onPaywall() else onPackSelected(item)
                            }
                        )
                    }
                    item {
                        Button(
                            onClick = onPaywall,
                            modifier = Modifier
                                .fillMaxWidth()
                                .heightIn(min = 56.dp)
                                .padding(top = 6.dp, bottom = 22.dp),
                            shape = RoundedCornerShape(16.dp),
                            colors = ButtonDefaults.buttonColors(
                                containerColor = MaterialTheme.colorScheme.primary,
                                contentColor = MaterialTheme.colorScheme.onPrimary
                            )
                        ) {
                            Text("Unlock all packs")
                        }
                    }
                }
            }
        }
    }
}

@Composable
private fun QuestionPackCard(
    item: QuestionPackItem,
    onClick: () -> Unit
) {
    val containerColor = if (item.isLocked) closerSoftSurfaceColor(alpha = 0.9f) else closerCardColor(alpha = 0.9f)
    val accent = packAccent(item.category.id)

    Card(
        onClick = onClick,
        modifier = Modifier.fillMaxWidth(),
        shape = RoundedCornerShape(22.dp),
        colors = CardDefaults.cardColors(containerColor = containerColor),
        elevation = CardDefaults.cardElevation(defaultElevation = 6.dp)
    ) {
        Column(modifier = Modifier.fillMaxWidth()) {
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(94.dp)
                    .clip(RoundedCornerShape(topStart = 22.dp, topEnd = 22.dp))
            ) {
                Image(
                    painter = painterResource(packArtworkRes(item.category.id)),
                    contentDescription = null,
                    contentScale = ContentScale.Crop,
                    modifier = Modifier.fillMaxSize()
                )
                Box(
                    modifier = Modifier
                        .align(Alignment.BottomStart)
                        .fillMaxWidth()
                        .height(5.dp)
                        .background(if (item.isLocked) MaterialTheme.colorScheme.outlineVariant else accent)
                )
            }
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(17.dp),
                verticalArrangement = Arrangement.spacedBy(12.dp)
            ) {
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(12.dp),
                    verticalAlignment = Alignment.Top
                ) {
                    CategoryGlyph(
                        categoryId = item.category.id,
                        iconName = item.category.iconName,
                        locked = item.isLocked,
                        modifier = Modifier.size(50.dp),
                        size = 50.dp
                    )
                    Column(
                        modifier = Modifier.weight(1f),
                        verticalArrangement = Arrangement.spacedBy(6.dp)
                    ) {
                        Text(
                            text = item.category.displayName.ifBlank { item.category.id.displayCategoryName() },
                            style = MaterialTheme.typography.titleLarge,
                            color = MaterialTheme.colorScheme.onSurface,
                            fontWeight = FontWeight.SemiBold,
                            maxLines = 1,
                            overflow = TextOverflow.Ellipsis
                        )
                        Text(
                            text = item.category.description,
                            style = MaterialTheme.typography.bodyMedium,
                            color = MaterialTheme.colorScheme.onSurfaceVariant,
                            maxLines = 2,
                            overflow = TextOverflow.Ellipsis
                        )
                    }
                    PackPill(item.promptCountLabel(), emphasis = true)
                }
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .horizontalScroll(rememberScrollState()),
                    horizontalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    item.metadataLabels().forEach { label ->
                        PackPill(label, emphasis = label == "Premium")
                    }
                }
            }
        }
    }
}

@Composable
private fun PackFilterRow(
    selected: PackFilter,
    onSelected: (PackFilter) -> Unit
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .horizontalScroll(rememberScrollState()),
        horizontalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        PackFilter.entries.forEach { filter ->
            FilterPill(
                label = filter.label,
                selected = selected == filter,
                onClick = { onSelected(filter) }
            )
        }
    }
}

@Composable
private fun FilterPill(
    label: String,
    selected: Boolean,
    onClick: () -> Unit
) {
    Surface(
        modifier = Modifier
            .heightIn(min = 44.dp)
            .clickable(onClick = onClick),
        shape = RoundedCornerShape(999.dp),
        color = if (selected) closerSoftPurpleColor() else closerSoftSurfaceColor(alpha = 0.74f),
        tonalElevation = 0.dp,
        shadowElevation = if (selected) 3.dp else 0.dp
    ) {
        Text(
            text = label,
            modifier = Modifier.padding(horizontal = 13.dp, vertical = 8.dp),
            style = MaterialTheme.typography.labelMedium,
            color = if (selected) MaterialTheme.colorScheme.onPrimaryContainer else MaterialTheme.colorScheme.onSurface,
            fontWeight = if (selected) FontWeight.SemiBold else FontWeight.Medium,
            maxLines = 1,
            overflow = TextOverflow.Ellipsis
        )
    }
}

@Composable
private fun PackPill(
    label: String,
    emphasis: Boolean = false
) {
    Surface(
        shape = RoundedCornerShape(999.dp),
        color = if (emphasis) closerSoftPurpleColor() else closerSoftSurfaceColor(),
        modifier = Modifier.heightIn(min = 32.dp)
    ) {
        Text(
            text = label,
            modifier = Modifier.padding(horizontal = 11.dp, vertical = 7.dp),
            style = MaterialTheme.typography.labelMedium,
            color = if (emphasis) MaterialTheme.colorScheme.onPrimaryContainer else MaterialTheme.colorScheme.onSurface,
            maxLines = 1,
            overflow = TextOverflow.Ellipsis
        )
    }
}

private fun QuestionPackItem.promptCountLabel(): String =
    "$questionCount ${if (questionCount == 1) "prompt" else "prompts"}"

private fun QuestionPackItem.metadataLabels(): List<String> {
    val access = when (category.access) {
        "premium" -> "Premium"
        "mixed" -> "Mixed access"
        "free" -> "Free"
        else -> category.access.displayCategoryName()
    }
    return listOf(
        access,
        category.iconName.ifBlank { "question" }.displayCategoryName()
    ).filterNot { it == "Question" }.distinct()
}

@Composable
private fun packAccent(categoryId: String): Color {
    val palette = listOf(
        MaterialTheme.colorScheme.primary,
        MaterialTheme.colorScheme.secondary,
        MaterialTheme.colorScheme.tertiary,
        MaterialTheme.colorScheme.primaryContainer,
        MaterialTheme.colorScheme.secondaryContainer
    )
    return palette[kotlin.math.abs(categoryId.hashCode()) % palette.size]
}

private fun packArtworkRes(categoryId: String): Int = when (categoryId) {
    "communication" -> R.drawable.pack_art_communication
    "trust",
    "boundaries",
    "conflict",
    "conflict_repair",
    "rebuilding_trust" -> R.drawable.pack_art_trust_repair
    "emotional_intimacy",
    "gratitude",
    "couple_intimacy" -> R.drawable.pack_art_intimacy
    "fun",
    "date_night",
    "quality_time" -> R.drawable.pack_art_fun_date
    "future",
    "values" -> R.drawable.pack_art_future_goals
    "home_life",
    "stress" -> R.drawable.pack_art_home_life
    "money" -> R.drawable.pack_art_money_values
    "marriage",
    "parenting" -> R.drawable.pack_art_family_commitment
    "sex_and_desire",
    "sexual_preferences",
    "physical_intimacy" -> R.drawable.pack_art_desire
    "difficult_conversations" -> R.drawable.pack_art_deep_reflection
    else -> R.drawable.pack_art_deep_reflection
}

@Composable
private fun LoadingPackCard() {
    Card(
        modifier = Modifier.fillMaxWidth(),
        shape = RoundedCornerShape(26.dp),
        colors = CardDefaults.cardColors(containerColor = closerCardColor(alpha = 0.82f))
    ) {
        Row(
            modifier = Modifier.padding(22.dp),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.spacedBy(14.dp)
        ) {
            CloserHeartLoader(size = 32.dp)
            Text(
                text = "Loading question packs",
                style = MaterialTheme.typography.bodyMedium,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis
            )
        }
    }
}

@Composable
private fun PackMessageCard(title: String, message: String) {
    Card(
        modifier = Modifier.fillMaxWidth(),
        shape = RoundedCornerShape(26.dp),
        colors = CardDefaults.cardColors(containerColor = closerCardColor(alpha = 0.82f))
    ) {
        Column(
            modifier = Modifier.padding(22.dp),
            verticalArrangement = Arrangement.spacedBy(8.dp)
        ) {
            Text(
                text = title,
                style = MaterialTheme.typography.titleMedium,
                fontWeight = FontWeight.SemiBold,
                color = MaterialTheme.colorScheme.onSurface,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis
            )
            Text(
                text = message,
                style = MaterialTheme.typography.bodyMedium,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
                maxLines = 4,
                overflow = TextOverflow.Ellipsis
            )
        }
    }
}

@Preview
@Composable
fun QuestionPackLibraryScreenPreview() {
    QuestionPackLibraryContent(
        state = QuestionPackLibraryUiState(
            isLoading = false,
            packs = listOf(
                QuestionPackItem(
                    category = QuestionCategory(
                        id = "emotional_intimacy",
                        displayName = "Emotional Intimacy",
                        description = "Prompts for closeness, reassurance, and being known.",
                        access = "mixed",
                        iconName = "heart"
                    ),
                    questionCount = 250
                )
            )
        ),
        onPackSelected = {},
        onPaywall = {}
    )
}
