package app.closer.ui.questions

import app.closer.ui.theme.closerBackgroundBrush
import android.provider.Settings
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.slideInVertically
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.Spacer
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.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
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.platform.LocalContext
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.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import app.closer.domain.model.ChoiceAnswerConfigImpl
import app.closer.domain.model.Question
import app.closer.domain.model.ThisOrThatAnswerConfigImpl
import app.closer.ui.components.EmptyState
import app.closer.ui.components.ErrorState
import app.closer.ui.components.LoadingState
import app.closer.ui.questions.components.QuestionAnswerInput
import app.closer.ui.questions.components.QuestionHeader

@Composable
fun LocalQuestionContent(
    state: LocalQuestionUiState,
    title: String,
    subtitle: String,
    primaryRouteLabel: String,
    onPrimaryRoute: (Question) -> Unit,
    onSecondaryRoute: (() -> Unit)?,
    secondaryRouteLabel: String?,
    onWrittenTextChanged: (String) -> Unit,
    onOptionToggled: (String) -> Unit,
    onScaleChanged: (Int) -> Unit,
    onSubmit: () -> Unit,
    canSubmit: Boolean,
    onRefresh: (() -> Unit)? = null,
    modifier: Modifier = Modifier
) {
    val background = closerBackgroundBrush()

    Box(
        modifier = modifier
            .fillMaxSize()
            .background(background)
    ) {
        Column(
            modifier = Modifier
                .fillMaxSize()
                .safeDrawingPadding()
                .navigationBarsPadding()
                .verticalScroll(rememberScrollState())
                .padding(horizontal = 20.dp, vertical = 18.dp),
            verticalArrangement = Arrangement.spacedBy(18.dp)
        ) {
            LocalQuestionHeader(title = title, subtitle = subtitle)

            when {
                state.isLoading -> LoadingState(message = "Opening your question")
                state.error != null -> ErrorState(
                    title = "Question paused",
                    message = state.error,
                    onRetry = onRefresh
                )
                state.question == null -> EmptyState(
                    title = "This one's not available",
                    body = "Try a different prompt — there are plenty more in your packs."
                )
                else -> {
                    val question = state.question
                    val context = LocalContext.current
                    val reducedMotion = Settings.Global.getFloat(
                        context.contentResolver, Settings.Global.ANIMATOR_DURATION_SCALE, 1f
                    ) == 0f
                    var helpExpanded by remember(question.id) { mutableStateOf(false) }
                    QuestionMetaRow(question = question)
                    QuestionHeader(
                        question = question,
                        helpExpanded = helpExpanded,
                        onToggleHelp = { helpExpanded = !helpExpanded },
                    )
                    QuestionAnswerInput(
                        question = question,
                        pendingWrittenText = state.pendingWrittenText,
                        pendingSelectedOptionIds = state.pendingSelectedOptionIds,
                        pendingScaleValue = state.pendingScaleValue,
                        onWrittenTextChanged = onWrittenTextChanged,
                        onOptionToggled = onOptionToggled,
                        onScaleChanged = onScaleChanged,
                        onSubmit = onSubmit,
                        canSubmit = canSubmit,
                        isSubmitting = false
                    )

                    AnimatedVisibility(
                        visible = state.submitted,
                        enter = if (reducedMotion) fadeIn(tween(0))
                                else fadeIn(tween(260)) + slideInVertically(tween(260)) { it / 3 }
                    ) {
                        SubmittedAnswerCard(question = question, state = state)
                    }

                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.spacedBy(12.dp)
                    ) {
                        Button(
                            onClick = { onPrimaryRoute(question) },
                            modifier = Modifier.weight(1f),
                            shape = RoundedCornerShape(16.dp),
                            colors = ButtonDefaults.buttonColors(
                                containerColor = Color(0xFFB98AF4),
                                contentColor = Color(0xFF24122F)
                            )
                        ) {
                            Text(
                                text = primaryRouteLabel,
                                maxLines = 1,
                                overflow = TextOverflow.Ellipsis
                            )
                        }
                        if (onSecondaryRoute != null && secondaryRouteLabel != null) {
                            OutlinedButton(
                                onClick = onSecondaryRoute,
                                modifier = Modifier.weight(1f),
                                shape = RoundedCornerShape(16.dp)
                            ) {
                                Text(
                                    text = secondaryRouteLabel,
                                    maxLines = 1,
                                    overflow = TextOverflow.Ellipsis
                                )
                            }
                        }
                    }

                    onRefresh?.let {
                        FilledTonalButton(
                            onClick = it,
                            modifier = Modifier.fillMaxWidth(),
                            shape = RoundedCornerShape(16.dp)
                        ) {
                            Text("Try another question")
                        }
                    }
                }
            }

            Spacer(modifier = Modifier.height(8.dp))
        }
    }
}

@Composable
private fun LocalQuestionHeader(
    title: String,
    subtitle: String
) {
    Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
        Text(
            text = title,
            style = MaterialTheme.typography.headlineLarge.copy(fontWeight = FontWeight.SemiBold),
            color = MaterialTheme.colorScheme.onSurface
        )
        Text(
            text = subtitle,
            style = MaterialTheme.typography.bodyLarge,
            color = MaterialTheme.colorScheme.onSurfaceVariant,
            maxLines = 3,
            overflow = TextOverflow.Ellipsis
        )
    }
}


@Composable
private fun QuestionMetaRow(question: Question) {
    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.spacedBy(10.dp)
    ) {
        MetaPill(label = question.category.displayCategoryName())
        MetaPill(label = "Depth ${question.depthLevel}")
        MetaPill(label = question.type.displayQuestionType())
    }
}

@Composable
private fun MetaPill(label: String) {
    Surface(
        shape = RoundedCornerShape(999.dp),
        color = Color.White.copy(alpha = 0.72f),
        shadowElevation = 0.dp
    ) {
        Text(
            text = label,
            modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp),
            style = MaterialTheme.typography.labelMedium,
            color = MaterialTheme.colorScheme.onSurface,
            maxLines = 1,
            overflow = TextOverflow.Ellipsis
        )
    }
}

@Composable
private fun SubmittedAnswerCard(
    question: Question,
    state: LocalQuestionUiState
) {
    Surface(
        modifier = Modifier.fillMaxWidth(),
        shape = RoundedCornerShape(22.dp),
        color = Color.White.copy(alpha = 0.78f),
        shadowElevation = 0.dp
    ) {
        Row(
            modifier = Modifier.padding(15.dp),
            horizontalArrangement = Arrangement.spacedBy(12.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Box(
                modifier = Modifier
                    .size(36.dp)
                    .clip(CircleShape)
                    .background(Color(0xFFB98AF4).copy(alpha = 0.18f)),
                contentAlignment = Alignment.Center
            ) {
                Text(
                    text = "OK",
                    style = MaterialTheme.typography.labelSmall,
                    color = Color(0xFF56306F),
                    fontWeight = FontWeight.Bold
                )
            }
            Column(verticalArrangement = Arrangement.spacedBy(3.dp)) {
                Text(
                    text = "Private answer saved",
                    style = MaterialTheme.typography.titleSmall,
                    color = MaterialTheme.colorScheme.onSurface,
                    fontWeight = FontWeight.SemiBold
                )
                Text(
                    text = answerSummary(question, state),
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    maxLines = 2,
                    overflow = TextOverflow.Ellipsis
                )
            }
        }
    }
}

private fun answerSummary(question: Question, state: LocalQuestionUiState): String {
    return when (question.type) {
        "written" -> state.pendingWrittenText.ifBlank { "Your written answer is ready." }
        "scale" -> "You chose ${state.pendingScaleValue}."
        "this_or_that" -> {
            val cfg = question.answerConfig as? ThisOrThatAnswerConfigImpl
            val selected = listOfNotNull(cfg?.config?.optionA, cfg?.config?.optionB)
                .firstOrNull { it.id == state.pendingSelectedOptionIds.firstOrNull() }
            selected?.text ?: "Your choice is ready."
        }
        "single_choice", "multi_choice" -> {
            val cfg = question.answerConfig as? ChoiceAnswerConfigImpl
            val selected = cfg?.config?.options
                ?.filter { it.id in state.pendingSelectedOptionIds }
                ?.joinToString { it.text }
            selected?.ifBlank { null } ?: "Your choice is ready."
        }
        else -> "Your answer is ready."
    }
}

fun String.displayCategoryName(): String {
    return split("_", "-")
        .filter { it.isNotBlank() }
        .joinToString(" ") { part -> part.replaceFirstChar { it.uppercaseChar() } }
}

fun String.displayQuestionType(): String {
    return when (this) {
        "single_choice" -> "Single choice"
        "multi_choice" -> "Multi choice"
        "this_or_that" -> "This or that"
        "scale" -> "Scale"
        else -> "Written"
    }
}
