package app.closer.ui.questions

import app.closer.ui.theme.closerBackgroundBrush
import app.closer.ui.theme.closerCardColor
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.Image
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.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Lock
import androidx.compose.material.icons.filled.Visibility
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
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.ui.Alignment
import androidx.compose.ui.platform.LocalContext
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.unit.dp
import app.closer.R
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,
    onBack: (() -> 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)
        ) {
            if (onBack != null) {
                IconButton(onClick = onBack) {
                    Icon(
                        imageVector = Icons.AutoMirrored.Filled.ArrowBack,
                        contentDescription = "Back"
                    )
                }
            }
            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
                    QuestionHeader(
                        question = question,
                        helpExpanded = false,
                        onToggleHelp = {},
                        showHelp = false
                    )
                    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 = MaterialTheme.colorScheme.primary,
                                contentColor = MaterialTheme.colorScheme.onPrimary
                            )
                        ) {
                            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
) {
    Surface(
        modifier = Modifier.fillMaxWidth(),
        shape = RoundedCornerShape(28.dp),
        color = closerCardColor(alpha = 0.92f),
        shadowElevation = 5.dp
    ) {
        Column(
            modifier = Modifier.fillMaxWidth(),
            verticalArrangement = Arrangement.spacedBy(14.dp)
        ) {
            Image(
                painter = painterResource(R.drawable.illustration_daily_question),
                contentDescription = null,
                contentScale = ContentScale.Crop,
                modifier = Modifier
                    .fillMaxWidth()
                    .height(166.dp)
                    .clip(RoundedCornerShape(topStart = 28.dp, topEnd = 28.dp))
            )
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(start = 20.dp, end = 20.dp, bottom = 20.dp),
                verticalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                Text(
                    text = title,
                    style = MaterialTheme.typography.headlineMedium.copy(fontWeight = FontWeight.SemiBold),
                    color = MaterialTheme.colorScheme.onSurface,
                    maxLines = 2,
                    overflow = TextOverflow.Ellipsis
                )
                Text(
                    text = subtitle,
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    maxLines = 3,
                    overflow = TextOverflow.Ellipsis
                )
            }
        }
    }
}

@Composable
private fun SubmittedAnswerCard(
    question: Question,
    state: LocalQuestionUiState
) {
    val label = when {
        state.isRevealed -> "Answer revealed"
        !state.partnerHasAnswered -> "Private answer saved — waiting for partner"
        else -> "Private answer saved"
    }
    Surface(
        modifier = Modifier.fillMaxWidth(),
        shape = RoundedCornerShape(22.dp),
        color = closerCardColor(alpha = 0.86f),
        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(MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.58f)),
                contentAlignment = Alignment.Center
            ) {
                Icon(
                    imageVector = if (state.isRevealed) Icons.Filled.Visibility else Icons.Filled.Lock,
                    contentDescription = null,
                    tint = MaterialTheme.colorScheme.onPrimaryContainer,
                    modifier = Modifier.size(18.dp)
                )
            }
            Column(verticalArrangement = Arrangement.spacedBy(3.dp)) {
                Text(
                    text = label,
                    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"
    }
}
