package app.closer.ui.questions.components

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.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Person
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
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.Modifier
import androidx.compose.ui.draw.clip
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.Question
import app.closer.domain.model.QuestionAnswer
import app.closer.domain.model.QuestionReaction

private val REACTION_EMOJIS = listOf("❤️", "😊", "😂", "😮", "👏", "🥺")

@Composable
fun AnswerBubble(
    answer: QuestionAnswer,
    question: Question,
    isCurrentUser: Boolean,
    partnerDisplayName: String?,
    reactions: List<QuestionReaction>,
    onAddReaction: (emoji: String) -> Unit,
    modifier: Modifier = Modifier
) {
    val bubbleShape = if (isCurrentUser) {
        RoundedCornerShape(topStart = 18.dp, topEnd = 4.dp, bottomStart = 18.dp, bottomEnd = 18.dp)
    } else {
        RoundedCornerShape(topStart = 4.dp, topEnd = 18.dp, bottomStart = 18.dp, bottomEnd = 18.dp)
    }

    Column(
        modifier = modifier.fillMaxWidth(),
        horizontalAlignment = if (isCurrentUser) Alignment.End else Alignment.Start
    ) {
        if (!isCurrentUser) {
            Row(
                modifier = Modifier.padding(bottom = 4.dp, start = 44.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = partnerDisplayName ?: "Partner",
                    style = MaterialTheme.typography.labelSmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.6f)
                )
            }
        }

        Row(
            horizontalArrangement = if (isCurrentUser) Arrangement.End else Arrangement.Start,
            verticalAlignment = Alignment.Bottom,
            modifier = Modifier.fillMaxWidth()
        ) {
            if (!isCurrentUser) {
                AvatarCircle(name = partnerDisplayName)
                Spacer(modifier = Modifier.width(8.dp))
            }

            Column(
                horizontalAlignment = if (isCurrentUser) Alignment.End else Alignment.Start,
                modifier = Modifier.widthIn(max = 280.dp)
            ) {
                Surface(
                    shape = bubbleShape,
                    color = if (isCurrentUser)
                        MaterialTheme.colorScheme.primaryContainer
                    else
                        MaterialTheme.colorScheme.surfaceVariant,
                    tonalElevation = 1.dp
                ) {
                    Text(
                        text = answerSummary(answer, question),
                        style = MaterialTheme.typography.bodyMedium,
                        color = if (isCurrentUser)
                            MaterialTheme.colorScheme.onPrimaryContainer
                        else
                            MaterialTheme.colorScheme.onSurfaceVariant,
                        modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp),
                        maxLines = 5,
                        overflow = TextOverflow.Ellipsis
                    )
                }

                ExistingReactions(reactions = reactions, isCurrentUser = isCurrentUser)

                ReactionBar(
                    onEmojiSelected = onAddReaction,
                    isCurrentUser = isCurrentUser
                )
            }

            if (isCurrentUser) {
                Spacer(modifier = Modifier.width(8.dp))
            }
        }
    }
}

@Composable
private fun AvatarCircle(name: String?) {
    Box(
        modifier = Modifier
            .size(32.dp)
            .clip(CircleShape)
            .background(MaterialTheme.colorScheme.secondaryContainer),
        contentAlignment = Alignment.Center
    ) {
        if (name != null && name.isNotBlank()) {
            Text(
                text = name.take(1).uppercase(),
                style = MaterialTheme.typography.labelMedium.copy(fontWeight = FontWeight.Bold),
                color = MaterialTheme.colorScheme.onSecondaryContainer
            )
        } else {
            Icon(
                imageVector = Icons.Default.Person,
                contentDescription = null,
                modifier = Modifier.size(18.dp),
                tint = MaterialTheme.colorScheme.onSecondaryContainer
            )
        }
    }
}

@Composable
private fun ExistingReactions(reactions: List<QuestionReaction>, isCurrentUser: Boolean) {
    if (reactions.isEmpty()) return
    val grouped = reactions.groupBy { it.emoji }
    Row(
        modifier = Modifier.padding(top = 4.dp),
        horizontalArrangement = Arrangement.spacedBy(4.dp)
    ) {
        grouped.entries.take(5).forEach { (emoji, list) ->
            Surface(
                shape = RoundedCornerShape(12.dp),
                color = MaterialTheme.colorScheme.surface,
                tonalElevation = 2.dp
            ) {
                Text(
                    text = if (list.size > 1) "$emoji ${list.size}" else emoji,
                    style = MaterialTheme.typography.labelSmall,
                    modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp)
                )
            }
        }
    }
}

@Composable
private fun ReactionBar(onEmojiSelected: (String) -> Unit, isCurrentUser: Boolean) {
    var expanded by remember { mutableStateOf(false) }

    Column(horizontalAlignment = if (isCurrentUser) Alignment.End else Alignment.Start) {
        TextButton(
            onClick = { expanded = !expanded },
            contentPadding = androidx.compose.foundation.layout.PaddingValues(
                horizontal = 4.dp, vertical = 0.dp
            ),
            modifier = Modifier.heightIn(min = 48.dp)
        ) {
            Text(
                text = if (expanded) "Close" else "Add a reaction",
                style = MaterialTheme.typography.labelSmall,
                color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.6f)
            )
        }

        if (expanded) {
            Row(
                horizontalArrangement = Arrangement.spacedBy(4.dp),
                modifier = Modifier.padding(bottom = 4.dp)
            ) {
                REACTION_EMOJIS.forEach { emoji ->
                    Surface(
                        shape = RoundedCornerShape(10.dp),
                        color = MaterialTheme.colorScheme.surfaceVariant,
                        tonalElevation = 2.dp,
                        modifier = Modifier
                            .clip(RoundedCornerShape(10.dp))
                            .size(48.dp)
                    ) {
                        Box(
                            contentAlignment = Alignment.Center,
                            modifier = Modifier
                                .size(48.dp)
                                .clip(RoundedCornerShape(10.dp))
                                .background(MaterialTheme.colorScheme.surfaceVariant)
                                .padding(2.dp)
                        ) {
                            TextButton(
                                onClick = {
                                    onEmojiSelected(emoji)
                                    expanded = false
                                },
                                contentPadding = androidx.compose.foundation.layout.PaddingValues(0.dp),
                                modifier = Modifier.size(48.dp)
                            ) {
                                Text(text = emoji, style = MaterialTheme.typography.bodyMedium)
                            }
                        }
                    }
                }
            }
        }
    }
}

private fun answerSummary(answer: QuestionAnswer, question: Question): String {
    return when (question.type) {
        "written" -> answer.writtenText ?: ""
        "scale" -> {
            val cfg = (question.answerConfig as? app.closer.domain.model.ScaleAnswerConfigImpl)?.config
            val value = answer.scaleValue ?: 0
            if (cfg != null && cfg.maxLabel.isNotBlank()) {
                "$value / ${cfg.maxScale} — ${cfg.maxLabel}"
            } else {
                "$value"
            }
        }
        "single_choice", "this_or_that" -> {
            val cfg = (question.answerConfig as? app.closer.domain.model.ChoiceAnswerConfigImpl)?.config
            val id = answer.selectedOptionIds.firstOrNull() ?: return ""
            cfg?.options?.find { it.id == id }?.text ?: id
        }
        "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(", ")
        }
        else -> ""
    }
}
