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.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.Spacer
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.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
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.Icon
import androidx.compose.material3.IconButton
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.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
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.Question
import app.closer.domain.model.QuestionCategory
import app.closer.ui.components.CategoryGlyph

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

    QuestionCategoryContent(
        categoryId = categoryId,
        state = state,
        onBack = { onNavigate("back") },
        onPickPrompt = {
            val question = state.questions.randomOrNull()
            if (question != null) {
                val coupleId = state.coupleId
                if (coupleId != null) {
                    onNavigate(AppRoute.questionThread(coupleId, question.id))
                } else {
                    onNavigate(AppRoute.CREATE_INVITE)
                }
            }
        }
    )
}

@Composable
private fun QuestionCategoryContent(
    categoryId: String,
    state: QuestionCategoryUiState,
    onBack: () -> Unit,
    onPickPrompt: () -> Unit
) {
    val title = state.category?.displayName ?: categoryId.displayCategoryName()

    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(closerBackgroundBrush())
    ) {
        LazyColumn(
            modifier = Modifier
                .fillMaxSize()
                .safeDrawingPadding()
                .navigationBarsPadding()
                .padding(horizontal = 20.dp),
            verticalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            item {
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(top = 8.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    IconButton(onClick = onBack) {
                        Icon(
                            Icons.AutoMirrored.Filled.ArrowBack,
                            contentDescription = "Back",
                            tint = MaterialTheme.colorScheme.onBackground
                        )
                    }
                }
            }

            item {
                PackArtworkHeader(categoryId = categoryId)
            }

            item {
                CategoryHero(
                    title = title,
                    category = state.category,
                    questionCount = state.questions.size,
                    isLoading = state.isLoading
                )
            }

            when {
                state.isLoading -> item { CategoryLoadingCard() }
                state.error != null -> item {
                    CategoryMessageCard(
                        title = "Pack unavailable",
                        message = state.error
                    )
                }
                else -> item {
                    Button(
                        onClick = onPickPrompt,
                        enabled = state.questions.isNotEmpty(),
                        modifier = Modifier
                            .fillMaxWidth()
                            .heightIn(min = 54.dp),
                        shape = RoundedCornerShape(18.dp),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = MaterialTheme.colorScheme.primary,
                            contentColor = MaterialTheme.colorScheme.onPrimary,
                            disabledContainerColor = MaterialTheme.colorScheme.primary.copy(alpha = 0.35f),
                            disabledContentColor = MaterialTheme.colorScheme.onPrimary.copy(alpha = 0.54f)
                        )
                    ) {
                        Text(
                            text = if (state.questions.isEmpty()) "No prompts yet" else "Pick a prompt",
                            style = MaterialTheme.typography.labelLarge,
                            fontWeight = FontWeight.SemiBold
                        )
                    }
                }
            }

            item { Spacer(Modifier.height(16.dp)) }
        }
    }
}

@Composable
private fun CategoryHero(
    title: String,
    category: QuestionCategory?,
    questionCount: Int,
    isLoading: Boolean = false
) {
    Column(
        modifier = Modifier.fillMaxWidth(),
        verticalArrangement = Arrangement.spacedBy(12.dp)
    ) {
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.spacedBy(14.dp),
            verticalAlignment = Alignment.Top
        ) {
            CategoryGlyph(
                categoryId = category?.id ?: title,
                iconName = category?.iconName,
                modifier = Modifier.size(58.dp),
                size = 58.dp,
                iconSize = 28.dp
            )
            Column(
                modifier = Modifier.weight(1f),
                verticalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                Text(
                    text = title,
                    style = MaterialTheme.typography.headlineLarge.copy(fontWeight = FontWeight.SemiBold),
                    color = MaterialTheme.colorScheme.onSurface,
                    maxLines = 2,
                    overflow = TextOverflow.Ellipsis
                )
                Text(
                    text = category?.description ?: "Prompts for this kind of conversation.",
                    style = MaterialTheme.typography.bodyLarge,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    maxLines = 4,
                    overflow = TextOverflow.Ellipsis
                )
            }
        }
        if (!isLoading) {
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .horizontalScroll(rememberScrollState()),
                horizontalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                CategoryPill("$questionCount ${if (questionCount == 1) "prompt" else "prompts"}", emphasis = true)
                category?.access?.let { access ->
                    CategoryPill(
                        when (access) {
                            "premium" -> "Premium"
                            "mixed" -> "Some free"
                            else -> "Free"
                        }
                    )
                }
            }
        }
    }
}

@Composable
private fun PackArtworkHeader(categoryId: String) {
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .height(160.dp)
            .clip(RoundedCornerShape(24.dp))
    ) {
        Image(
            painter = painterResource(packArtworkRes(categoryId)),
            contentDescription = null,
            contentScale = ContentScale.Crop,
            modifier = Modifier.fillMaxSize()
        )
    }
}

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 CategoryPill(
    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
        )
    }
}

@Composable
private fun CategoryLoadingCard() {
    Card(
        modifier = Modifier.fillMaxWidth(),
        shape = RoundedCornerShape(24.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 prompts",
                style = MaterialTheme.typography.bodyMedium,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis
            )
        }
    }
}

@Composable
private fun CategoryMessageCard(title: String, message: String) {
    Card(
        modifier = Modifier.fillMaxWidth(),
        shape = RoundedCornerShape(24.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 QuestionCategoryScreenPreview() {
    QuestionCategoryContent(
        categoryId = "emotional_intimacy",
        state = QuestionCategoryUiState(
            isLoading = false,
            category = QuestionCategory(
                id = "emotional_intimacy",
                displayName = "Emotional Intimacy",
                description = "Prompts for closeness, tenderness, and reassurance.",
                access = "mixed",
                iconName = "heart"
            ),
            questions = listOf(
                Question(
                    id = "demo",
                    text = "What is one gentle thing I could do this week that would help you feel chosen?",
                    category = "emotional_intimacy",
                    depthLevel = 2,
                    type = "written"
                )
            )
        ),
        onBack = {},
        onPickPrompt = {}
    )
}
