package app.closer.ui.questions

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.heightIn
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.safeDrawingPadding
import androidx.compose.foundation.rememberScrollState
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.material3.Button
import androidx.compose.material3.ButtonDefaults
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.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
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.QuestionAnswer
import app.closer.ui.components.ErrorState
import app.closer.ui.components.LoadingState
import app.closer.ui.questions.components.AnswerBubble
import app.closer.ui.questions.components.QuestionAnswerInput
import app.closer.ui.questions.components.QuestionHeader
import app.closer.ui.theme.closerBackgroundBrush

@Composable
fun QuestionThreadScreen(
    coupleId: String,
    questionId: String,
    previousQuestionId: String? = null,
    nextQuestionId: String? = null,
    onNavigate: (String) -> Unit = {},
    onBack: () -> Unit = {},
    viewModel: QuestionThreadViewModel = hiltViewModel()
) {
    val state by viewModel.uiState.collectAsState()

    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(closerBackgroundBrush())
    ) {
        Column(
            modifier = Modifier
                .fillMaxSize()
                .safeDrawingPadding()
                .navigationBarsPadding()
                .verticalScroll(rememberScrollState())
                .padding(horizontal = 20.dp, vertical = 18.dp),
            verticalArrangement = Arrangement.spacedBy(18.dp)
        ) {
            IconButton(onClick = onBack) {
                Icon(
                    imageVector = Icons.AutoMirrored.Filled.ArrowBack,
                    contentDescription = "Back"
                )
            }

            when {
                state.isLoading -> LoadingState(message = "Opening thread")
                state.error != null -> ErrorState(
                    title = "Thread unavailable",
                    message = state.error ?: "Something went wrong."
                )
                state.question == null -> LoadingState(message = "Loading question")
                else -> {
                    val question = state.question!!

                    QuestionHeader(
                        question = question,
                        helpExpanded = state.helpExpanded,
                        onToggleHelp = viewModel::toggleHelp
                    )

                    when (state.phase) {
                        QuestionPhase.INPUT -> InputPhase(
                            question = question,
                            state = state,
                            viewModel = viewModel
                        )
                        QuestionPhase.WAITING -> WaitingPhase(
                            myAnswer = state.myAnswer,
                            question = question
                        )
                        QuestionPhase.REVEALED -> AnimatedVisibility(
                            visible = true,
                            enter = fadeIn(tween(300)) + slideInVertically(tween(300)) { it / 4 }
                        ) {
                            RevealedPhase(
                                state = state,
                                question = question,
                                viewModel = viewModel,
                                coupleId = coupleId,
                                questionId = questionId,
                                previousQuestionId = previousQuestionId,
                                nextQuestionId = nextQuestionId,
                                onNavigate = onNavigate
                            )
                        }
                    }
                }
            }

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

@Composable
private fun InputPhase(
    question: Question,
    state: QuestionThreadUiState,
    viewModel: QuestionThreadViewModel
) {
    Column(verticalArrangement = Arrangement.spacedBy(14.dp)) {
        Text(
            text = "Answer privately. Your partner won't see this until they answer too.",
            style = MaterialTheme.typography.bodyMedium,
            color = MaterialTheme.colorScheme.onSurfaceVariant
        )
        QuestionAnswerInput(
            question = question,
            pendingWrittenText = state.pendingWrittenText,
            pendingSelectedOptionIds = state.pendingSelectedOptionIds,
            pendingScaleValue = state.pendingScaleValue,
            onWrittenTextChanged = viewModel::updateWrittenText,
            onOptionToggled = viewModel::toggleOption,
            onScaleChanged = viewModel::updateScale,
            onSubmit = viewModel::submitAnswer,
            canSubmit = viewModel.canSubmit(),
            isSubmitting = state.isSubmitting
        )
    }
}

@Composable
private fun WaitingPhase(
    myAnswer: QuestionAnswer?,
    question: Question
) {
    Column(verticalArrangement = Arrangement.spacedBy(14.dp)) {
        Surface(
            modifier = Modifier.fillMaxWidth(),
            shape = RoundedCornerShape(20.dp),
            color = Color.White.copy(alpha = 0.78f)
        ) {
            Column(
                modifier = Modifier.padding(18.dp),
                verticalArrangement = Arrangement.spacedBy(10.dp)
            ) {
                Text(
                    text = "Your answer is saved",
                    style = MaterialTheme.typography.titleSmall,
                    fontWeight = FontWeight.SemiBold,
                    color = MaterialTheme.colorScheme.onSurface
                )
                if (myAnswer != null) {
                    Text(
                        text = answerPreviewText(myAnswer, question),
                        style = MaterialTheme.typography.bodyMedium,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
                Text(
                    text = "Waiting for your partner to answer. The discussion opens once you've both responded.",
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f)
                )
            }
        }
    }
}

@Composable
private fun RevealedPhase(
    state: QuestionThreadUiState,
    question: Question,
    viewModel: QuestionThreadViewModel,
    coupleId: String,
    questionId: String,
    previousQuestionId: String?,
    nextQuestionId: String?,
    onNavigate: (String) -> Unit
) {
    Column(verticalArrangement = Arrangement.spacedBy(14.dp)) {
        state.myAnswer?.let { myAnswer ->
            AnswerBubble(
                answer = myAnswer,
                question = question,
                isCurrentUser = true,
                partnerDisplayName = null,
                reactions = state.reactions.filter { it.targetUserId == viewModel.currentUserId },
                onAddReaction = { emoji ->
                    viewModel.addReaction(viewModel.currentUserId, emoji)
                }
            )
        }
        state.partnerAnswer?.let { partnerAnswer ->
            AnswerBubble(
                answer = partnerAnswer,
                question = question,
                isCurrentUser = false,
                partnerDisplayName = null,
                reactions = state.reactions.filter { it.targetUserId == partnerAnswer.userId },
                onAddReaction = { emoji ->
                    viewModel.addReaction(partnerAnswer.userId, emoji)
                }
            )
        }

        // Discussion now lives in the unified Messages conversation (q_<questionId>) so it's notified
        // and appears in the inbox — same as the daily flow.
        Button(
            onClick = { onNavigate(AppRoute.conversation(coupleId, "q_$questionId")) },
            modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp),
            shape = RoundedCornerShape(16.dp),
            colors = ButtonDefaults.buttonColors(
                containerColor = MaterialTheme.colorScheme.secondaryContainer,
                contentColor = MaterialTheme.colorScheme.onSecondaryContainer
            )
        ) {
            Text("Discuss this together")
        }

        // Navigation out of the thread
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.spacedBy(12.dp)
        ) {
            if (nextQuestionId != null) {
                Button(
                    onClick = {
                        onNavigate(
                            AppRoute.questionThread(
                                coupleId = coupleId,
                                questionId = nextQuestionId,
                                prevId = questionId
                            )
                        )
                    },
                    modifier = Modifier.weight(1f).heightIn(min = 48.dp),
                    shape = RoundedCornerShape(16.dp),
                    colors = ButtonDefaults.buttonColors(
                        containerColor = MaterialTheme.colorScheme.primary,
                        contentColor = MaterialTheme.colorScheme.onPrimary
                    )
                ) {
                    Text("Next prompt")
                }
            }
            OutlinedButton(
                onClick = { onNavigate(AppRoute.ANSWER_HISTORY) },
                modifier = Modifier.weight(1f).heightIn(min = 48.dp),
                shape = RoundedCornerShape(16.dp)
            ) {
                Text("Saved answers")
            }
        }

        if (previousQuestionId != null) {
            OutlinedButton(
                onClick = {
                    onNavigate(
                        AppRoute.questionThread(
                            coupleId = coupleId,
                            questionId = previousQuestionId,
                            nextId = questionId
                        )
                    )
                },
                modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp),
                shape = RoundedCornerShape(16.dp)
            ) {
                Text("Previous prompt")
            }
        }
    }
}

private fun answerPreviewText(answer: QuestionAnswer, question: Question): String {
    return when (question.type) {
        "written" -> answer.writtenText?.take(120) ?: "Your written answer."
        "scale" -> "Scale: ${answer.scaleValue}"
        "single_choice", "this_or_that" -> {
            val cfg = (question.answerConfig as? app.closer.domain.model.ChoiceAnswerConfigImpl)?.config
            val id = answer.selectedOptionIds.firstOrNull() ?: return "Your choice."
            cfg?.options?.find { it.id == id }?.text ?: "Your choice."
        }
        "multi_choice" -> {
            val cfg = (question.answerConfig as? app.closer.domain.model.ChoiceAnswerConfigImpl)?.config
            answer.selectedOptionIds.mapNotNull { id ->
                cfg?.options?.find { it.id == id }?.text
            }.joinToString(", ").ifBlank { "Your choices." }
        }
        else -> "Your answer is saved."
    }
}
