package app.closer.ui.questions

import app.closer.ui.theme.closerCardColor
import app.closer.ui.theme.closerBackgroundBrush
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.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.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CircularProgressIndicator
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.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.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
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,
        onQuestionSelected = { question ->
            val coupleId = state.coupleId
            if (coupleId != null) {
                onNavigate(AppRoute.questionThread(coupleId, question.id))
            } else {
                // Discussing requires a paired partner; send unpaired users to invite one.
                onNavigate(AppRoute.CREATE_INVITE)
            }
        }
    )
}

@Composable
private fun QuestionCategoryContent(
    categoryId: String,
    state: QuestionCategoryUiState,
    onQuestionSelected: (Question) -> Unit
) {
    var selectedType by remember { mutableStateOf<String?>(null) }
    val visibleQuestions = remember(state.questions, selectedType) {
        state.questions.filter { question ->
            selectedType == null || question.type == selectedType
        }
    }

    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(
                closerBackgroundBrush()
            )
    ) {
        LazyColumn(
            modifier = Modifier
                .fillMaxSize()
                .safeDrawingPadding()
                .navigationBarsPadding()
                .padding(horizontal = 20.dp),
            verticalArrangement = Arrangement.spacedBy(12.dp)
        ) {
            item {
                val title = state.category?.displayName
                    ?: categoryId.displayCategoryName()
                CategoryHero(
                    title = title,
                    category = state.category,
                    questionCount = state.questions.size,
                    modifier = Modifier.padding(top = 20.dp, bottom = 6.dp)
                )
            }

            when {
                state.isLoading -> item { CategoryLoadingCard() }
                state.error != null -> item {
                    CategoryMessageCard(
                        title = "Category paused",
                        message = state.error
                    )
                }
                state.questions.isEmpty() -> item {
                    CategoryMessageCard(
                        title = "No prompts found",
                        message = "No prompts are available for ${categoryId.displayCategoryName()} right now."
                    )
                }
                else -> {
                    item {
                        CategoryFilters(
                            questions = state.questions,
                            selectedType = selectedType,
                            onTypeSelected = { selectedType = it }
                        )
                    }
                    if (visibleQuestions.isEmpty()) {
                        item {
                            CategoryMessageCard(
                                title = "No prompts match",
                                message = "Try another filter to keep browsing."
                            )
                        }
                    } else {
                        visibleQuestions.groupBy { it.depthLevel }.toSortedMap().forEach { (depth, questions) ->
                            item(key = "depth-$depth") {
                                DepthHeader(depth = depth, count = questions.size)
                            }
                            items(questions, key = { it.id }) { question ->
                                QuestionListCard(
                                    question = question,
                                    onClick = { onQuestionSelected(question) }
                                )
                            }
                        }
                    }
                }
            }
        }
    }
}

@Composable
private fun CategoryHero(
    title: String,
    category: QuestionCategory?,
    questionCount: Int,
    modifier: Modifier = Modifier
) {
    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
                        ?: "Browse prompts for this kind of conversation.",
                    style = MaterialTheme.typography.bodyLarge,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    maxLines = 3,
                    overflow = TextOverflow.Ellipsis
                )
            }
        }
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .horizontalScroll(rememberScrollState()),
            horizontalArrangement = Arrangement.spacedBy(8.dp)
        ) {
            CategoryPill("$questionCount ${if (questionCount == 1) "prompt" else "prompts"}", emphasis = true)
            category?.access?.let { CategoryPill(it.displayCategoryName()) }
            category?.iconName
                ?.takeIf { it.isNotBlank() }
                ?.let { it.displayCategoryName() }
                ?.takeIf { it != "Question" }
                ?.let { CategoryPill(it) }
        }
    }
}

@Composable
private fun CategoryFilters(
    questions: List<Question>,
    selectedType: String?,
    onTypeSelected: (String?) -> Unit
) {
    val types = questions.map { it.type }.distinct().sorted()

    Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
        Text(
            text = "Format",
            style = MaterialTheme.typography.labelMedium,
            color = MaterialTheme.colorScheme.onSurfaceVariant,
            fontWeight = FontWeight.SemiBold
        )
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .horizontalScroll(rememberScrollState()),
            horizontalArrangement = Arrangement.spacedBy(8.dp)
        ) {
            (listOf(null) + types).forEach { option ->
                FilterPill(
                    label = option?.displayQuestionFilterName() ?: "All",
                    selected = selectedType == option,
                    onClick = { onTypeSelected(option) }
                )
            }
        }
    }
}

private fun String.displayQuestionFilterName(): String {
    return when (this) {
        "single_choice" -> "Single"
        "multi_choice" -> "Multi"
        "this_or_that" -> "Either/or"
        "scale" -> "Scale"
        else -> "Written"
    }
}

@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) Color(0xFFF3E8FF) else Color.White.copy(alpha = 0.74f),
        shadowElevation = if (selected) 2.dp else 0.dp
    ) {
        Text(
            text = label,
            modifier = Modifier.padding(horizontal = 13.dp, vertical = 8.dp),
            style = MaterialTheme.typography.labelMedium,
            color = if (selected) Color(0xFF56306F) else MaterialTheme.colorScheme.onSurface,
            fontWeight = if (selected) FontWeight.SemiBold else FontWeight.Medium,
            maxLines = 1,
            overflow = TextOverflow.Ellipsis
        )
    }
}

@Composable
private fun DepthHeader(depth: Int, count: Int) {
    Surface(
        modifier = Modifier
            .fillMaxWidth()
            .padding(top = 6.dp),
        shape = RoundedCornerShape(18.dp),
        color = Color.White.copy(alpha = 0.68f),
        shadowElevation = 0.dp
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 14.dp, vertical = 11.dp),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
                Text(
                    text = depthLabel(depth),
                    style = MaterialTheme.typography.titleSmall,
                    color = MaterialTheme.colorScheme.onSurface,
                    fontWeight = FontWeight.SemiBold,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis
                )
                Text(
                    text = "Depth $depth",
                    style = MaterialTheme.typography.labelSmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis
                )
            }
            CategoryPill("$count ${if (count == 1) "prompt" else "prompts"}", emphasis = true)
        }
    }
}

private fun depthLabel(depth: Int): String = when (depth) {
    1 -> "Light openers"
    2 -> "Closer prompts"
    3 -> "Deeper conversation"
    else -> "Depth $depth"
}

@Composable
private fun QuestionListCard(
    question: Question,
    onClick: () -> Unit
) {
    Card(
        onClick = onClick,
        modifier = Modifier.fillMaxWidth(),
        shape = RoundedCornerShape(20.dp),
        colors = CardDefaults.cardColors(containerColor = closerCardColor(alpha = 0.9f)),
        elevation = CardDefaults.cardElevation(defaultElevation = 3.dp)
    ) {
        Column(
            modifier = Modifier.padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(10.dp)
        ) {
            Text(
                text = question.text,
                style = MaterialTheme.typography.titleMedium,
                fontWeight = FontWeight.SemiBold,
                color = MaterialTheme.colorScheme.onSurface,
                maxLines = 3,
                overflow = TextOverflow.Ellipsis
            )
            Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                CategoryPill(question.type.displayQuestionType())
                if (question.isPremium) {
                    CategoryPill("Premium")
                } else {
                    CategoryPill("Free")
                }
            }
        }
    }
}

@Composable
private fun CategoryPill(
    label: String,
    emphasis: Boolean = false
) {
    Surface(
        shape = RoundedCornerShape(999.dp),
        color = if (emphasis) Color(0xFFF3E8FF) else Color(0xFFFFF8FC),
        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) Color(0xFF56306F) 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)
        ) {
            CircularProgressIndicator(color = Color(0xFFB98AF4))
            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"
                )
            )
        ),
        onQuestionSelected = {}
    )
}
