package app.closer.ui.wheel

import app.closer.ui.theme.closerCardColor
import app.closer.ui.theme.closerBackgroundBrush
import app.closer.ui.theme.closerSoftPurpleColor
import androidx.compose.foundation.BorderStroke
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.layout.size
import androidx.compose.foundation.rememberScrollState
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.Checkbox
import androidx.compose.material3.CheckboxDefaults
import app.closer.ui.components.CloserHeartLoader
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.OutlinedTextFieldDefaults
import androidx.compose.material3.RadioButton
import androidx.compose.material3.RadioButtonDefaults
import androidx.compose.material3.Slider
import androidx.compose.material3.SliderDefaults
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
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.TextAlign
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.domain.model.ChoiceAnswerConfigImpl
import app.closer.domain.model.Question
import app.closer.domain.model.ScaleAnswerConfigImpl
import app.closer.domain.model.ThisOrThatAnswerConfigImpl
import app.closer.domain.model.WrittenAnswerConfigImpl

@Composable
fun WheelSessionScreen(
    sessionId: String,
    onNavigate: (String) -> Unit = {},
    viewModel: WheelSessionViewModel = hiltViewModel()
) {
    val state by viewModel.uiState.collectAsState()

    LaunchedEffect(state.navigateTo) {
        state.navigateTo?.let {
            onNavigate(it)
            viewModel.onNavigated()
        }
    }

    WheelSessionContent(
        state = state,
        onSelectOption = viewModel::selectOption,
        onScaleChanged = viewModel::onScaleChanged,
        onWrittenTextChanged = viewModel::onWrittenTextChanged,
        onNext = viewModel::next,
        onSkip = viewModel::skip,
        onEnd = viewModel::endEarly
    )
}

@Composable
private fun WheelSessionContent(
    state: WheelSessionUiState,
    onSelectOption: (String) -> Unit,
    onScaleChanged: (Int) -> Unit,
    onWrittenTextChanged: (String) -> Unit,
    onNext: () -> Unit,
    onSkip: () -> Unit,
    onEnd: () -> Unit
) {
    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(closerBackgroundBrush())
    ) {
        Column(
            modifier = Modifier
                .fillMaxSize()
                .safeDrawingPadding()
                .navigationBarsPadding()
                .padding(horizontal = 24.dp, vertical = 24.dp),
            verticalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            if (state.isLoading) {
                Box(
                    modifier = Modifier.fillMaxSize(),
                    contentAlignment = Alignment.Center
                ) {
                    CloserHeartLoader()
                }
                return@Column
            }

            if (state.isEmpty) {
                EmptySessionCard()
                return@Column
            }

            val total = state.questions.size
            val current = state.currentIndex
            val progress = if (total > 0) (current.toFloat() / total) else 0f

            // Header row
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                if (state.categoryName.isNotBlank()) {
                    Surface(
                        shape = RoundedCornerShape(999.dp),
                        color = closerSoftPurpleColor(),
                        modifier = Modifier.heightIn(min = 32.dp)
                    ) {
                        Text(
                            text = state.categoryName,
                            modifier = Modifier.padding(horizontal = 12.dp, vertical = 6.dp),
                            style = MaterialTheme.typography.labelMedium,
                            color = MaterialTheme.colorScheme.onPrimaryContainer,
                            maxLines = 1,
                            overflow = TextOverflow.Ellipsis
                        )
                    }
                }
                Text(
                    text = "${current + 1} / $total",
                    style = MaterialTheme.typography.labelLarge,
                    color = Color(0xFF9B8AA6),
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis
                )
            }

            // Progress bar
            LinearProgressIndicator(
                progress = { progress },
                modifier = Modifier.fillMaxWidth(),
                color = MaterialTheme.colorScheme.primary,
                trackColor = MaterialTheme.colorScheme.primaryContainer
            )

            // Question card
            val question = state.questions.getOrNull(current)

            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .weight(1f),
                shape = RoundedCornerShape(28.dp),
                colors = CardDefaults.cardColors(containerColor = closerCardColor(alpha = 0.88f)),
                elevation = CardDefaults.cardElevation(defaultElevation = 10.dp)
            ) {
                Column(
                    modifier = Modifier
                        .fillMaxSize()
                        .verticalScroll(rememberScrollState())
                        .padding(24.dp),
                    verticalArrangement = Arrangement.spacedBy(20.dp)
                ) {
                    // Question text
                    Text(
                        text = question?.text ?: "",
                        style = MaterialTheme.typography.titleLarge.copy(fontWeight = FontWeight.SemiBold),
                        color = MaterialTheme.colorScheme.onSurface,
                        textAlign = TextAlign.Center,
                        maxLines = 8,
                        overflow = TextOverflow.Ellipsis,
                        modifier = Modifier.fillMaxWidth()
                    )

                    // Answer options
                    if (question != null) {
                        AnswerOptions(
                            question = question,
                            selectedOptionIds = state.selectedOptionIds,
                            selectedScaleValue = state.selectedScaleValue,
                            writtenText = state.writtenText,
                            onSelectOption = onSelectOption,
                            onScaleChanged = onScaleChanged,
                            onWrittenTextChanged = onWrittenTextChanged
                        )
                    }
                }
            }

            // Action buttons
            Column(
                modifier = Modifier.fillMaxWidth(),
                verticalArrangement = Arrangement.spacedBy(12.dp)
            ) {
                Button(
                    onClick = onNext,
                    modifier = Modifier
                        .fillMaxWidth()
                        .heightIn(min = 56.dp),
                    shape = RoundedCornerShape(18.dp),
                    colors = ButtonDefaults.buttonColors(containerColor = Color(0xFF56306F))
                ) {
                    Text(
                        text = if (current + 1 >= total) "Finish" else "Next question",
                        color = Color.White
                    )
                }
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(12.dp)
                ) {
                    OutlinedButton(
                        onClick = onSkip,
                        modifier = Modifier
                            .weight(1f)
                            .heightIn(min = 48.dp),
                        shape = RoundedCornerShape(14.dp)
                    ) {
                        Text("Skip")
                    }
                    TextButton(
                        onClick = onEnd,
                        modifier = Modifier
                            .weight(1f)
                            .heightIn(min = 48.dp)
                    ) {
                        Text("End session", color = Color(0xFF9B8AA6))
                    }
                }
            }
        }
    }
}

@Composable
private fun AnswerOptions(
    question: Question,
    selectedOptionIds: List<String>,
    selectedScaleValue: Int,
    writtenText: String,
    onSelectOption: (String) -> Unit,
    onScaleChanged: (Int) -> Unit,
    onWrittenTextChanged: (String) -> Unit
) {
    when (question.type) {
        "written" -> {
            val config = question.answerConfig as? WrittenAnswerConfigImpl
            OutlinedTextField(
                value = writtenText,
                onValueChange = onWrittenTextChanged,
                modifier = Modifier
                    .fillMaxWidth()
                    .heightIn(min = 120.dp),
                placeholder = {
                    Text(
                        text = config?.config?.placeholder ?: "Write your answer…",
                        style = MaterialTheme.typography.bodyMedium,
                        color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.45f)
                    )
                },
                singleLine = false,
                minLines = 3,
                maxLines = 6,
                shape = RoundedCornerShape(14.dp),
                colors = OutlinedTextFieldDefaults.colors(
                    focusedBorderColor = Color(0xFF56306F),
                    unfocusedBorderColor = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.25f),
                    focusedContainerColor = MaterialTheme.colorScheme.surface,
                    unfocusedContainerColor = MaterialTheme.colorScheme.surface
                ),
                textStyle = MaterialTheme.typography.bodyLarge
            )
        }
        "single_choice" -> {
            val config = question.answerConfig as? ChoiceAnswerConfigImpl
            val options = config?.config?.options ?: return
            Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
                options.forEach { option ->
                    val isSelected = option.id in selectedOptionIds
                    OutlinedButton(
                        onClick = { onSelectOption(option.id) },
                        modifier = Modifier.fillMaxWidth(),
                        shape = RoundedCornerShape(12.dp),
                        border = BorderStroke(
                            width = if (isSelected) 2.dp else 1.dp,
                            color = if (isSelected) Color(0xFF56306F)
                            else MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.25f)
                        ),
                        colors = ButtonDefaults.outlinedButtonColors(
                            containerColor = if (isSelected) Color(0xFFF0EDF9)
                            else MaterialTheme.colorScheme.surface,
                            contentColor = MaterialTheme.colorScheme.onSurface
                        )
                    ) {
                        Row(
                            verticalAlignment = Alignment.CenterVertically,
                            modifier = Modifier.fillMaxWidth()
                        ) {
                            RadioButton(
                                selected = isSelected,
                                onClick = null,
                                colors = RadioButtonDefaults.colors(
                                    selectedColor = Color(0xFF56306F)
                                )
                            )
                            Text(
                                text = option.text,
                                style = MaterialTheme.typography.bodyMedium,
                                modifier = Modifier.padding(start = 8.dp),
                                maxLines = 2,
                                overflow = TextOverflow.Ellipsis
                            )
                        }
                    }
                }
            }
        }
        "multi_choice" -> {
            val config = question.answerConfig as? ChoiceAnswerConfigImpl
            val options = config?.config?.options ?: return
            Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
                options.forEach { option ->
                    val isChecked = option.id in selectedOptionIds
                    OutlinedButton(
                        onClick = { onSelectOption(option.id) },
                        modifier = Modifier.fillMaxWidth(),
                        shape = RoundedCornerShape(12.dp),
                        border = BorderStroke(
                            width = if (isChecked) 2.dp else 1.dp,
                            color = if (isChecked) Color(0xFF56306F)
                            else MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.25f)
                        ),
                        colors = ButtonDefaults.outlinedButtonColors(
                            containerColor = if (isChecked) Color(0xFFF0EDF9)
                            else MaterialTheme.colorScheme.surface,
                            contentColor = MaterialTheme.colorScheme.onSurface
                        )
                    ) {
                        Row(
                            verticalAlignment = Alignment.CenterVertically,
                            modifier = Modifier.fillMaxWidth()
                        ) {
                            Checkbox(
                                checked = isChecked,
                                onCheckedChange = null,
                                colors = CheckboxDefaults.colors(
                                    checkedColor = Color(0xFF56306F)
                                )
                            )
                            Text(
                                text = option.text,
                                style = MaterialTheme.typography.bodyMedium,
                                modifier = Modifier.padding(start = 8.dp),
                                maxLines = 2,
                                overflow = TextOverflow.Ellipsis
                            )
                        }
                    }
                }
            }
        }
        "scale" -> {
            val config = question.answerConfig as? ScaleAnswerConfigImpl
            val cfg = config?.config ?: return
            Column(modifier = Modifier.fillMaxWidth()) {
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.Center
                ) {
                    Text(
                        text = "$selectedScaleValue",
                        style = MaterialTheme.typography.headlineMedium.copy(fontWeight = FontWeight.Bold),
                        color = Color(0xFF56306F)
                    )
                }
                Spacer(modifier = Modifier.height(8.dp))
                Slider(
                    value = selectedScaleValue.toFloat(),
                    onValueChange = { onScaleChanged(it.toInt()) },
                    valueRange = cfg.minScale.toFloat()..cfg.maxScale.toFloat(),
                    steps = if (cfg.maxScale > cfg.minScale) (cfg.maxScale - cfg.minScale - 1).coerceAtLeast(0) else 0,
                    modifier = Modifier.fillMaxWidth(),
                    colors = SliderDefaults.colors(
                        thumbColor = Color(0xFF56306F),
                        activeTrackColor = Color(0xFF56306F),
                        inactiveTrackColor = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.2f)
                    )
                )
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween
                ) {
                    Text(
                        text = cfg.minLabel.ifBlank { "${cfg.minScale}" },
                        style = MaterialTheme.typography.labelSmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                    Text(
                        text = cfg.maxLabel.ifBlank { "${cfg.maxScale}" },
                        style = MaterialTheme.typography.labelSmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
            }
        }
        "this_or_that" -> {
            val config = question.answerConfig as? ThisOrThatAnswerConfigImpl
            val cfg = config?.config ?: return
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.spacedBy(12.dp)
            ) {
                listOf(cfg.optionA, cfg.optionB).forEach { option ->
                    val isSelected = option.id in selectedOptionIds
                    Button(
                        onClick = { onSelectOption(option.id) },
                        modifier = Modifier
                            .weight(1f)
                            .height(96.dp),
                        shape = RoundedCornerShape(16.dp),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = if (isSelected) Color(0xFF56306F)
                            else MaterialTheme.colorScheme.surfaceVariant,
                            contentColor = if (isSelected) Color.White
                            else MaterialTheme.colorScheme.onSurfaceVariant
                        ),
                        elevation = ButtonDefaults.buttonElevation(
                            defaultElevation = if (isSelected) 4.dp else 0.dp
                        )
                    ) {
                        Text(
                            text = option.text,
                            style = MaterialTheme.typography.bodyMedium.copy(fontWeight = FontWeight.Medium),
                            textAlign = TextAlign.Center,
                            maxLines = 3,
                            overflow = TextOverflow.Ellipsis
                        )
                    }
                }
            }
        }
    }
}

@Composable
private fun EmptySessionCard() {
    Card(
        modifier = Modifier.fillMaxWidth(),
        shape = RoundedCornerShape(24.dp),
        colors = CardDefaults.cardColors(containerColor = closerCardColor(alpha = 0.84f))
    ) {
        Column(
            modifier = Modifier.padding(24.dp),
            verticalArrangement = Arrangement.spacedBy(10.dp)
        ) {
            Text(
                "No active session",
                style = MaterialTheme.typography.titleMedium,
                fontWeight = FontWeight.SemiBold,
                color = MaterialTheme.colorScheme.onSurface,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis
            )
            Text(
                "Go back to the category picker and spin the wheel to start.",
                style = MaterialTheme.typography.bodyMedium,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
                maxLines = 3,
                overflow = TextOverflow.Ellipsis
            )
        }
    }
}

@Preview
@Composable
fun WheelSessionScreenPreview() {
    WheelSessionContent(
        state = WheelSessionUiState(
            isLoading = false,
            questions = listOf(
                Question(id = "1", text = "When did you last feel truly seen by me?", category = "trust", depthLevel = 3),
                Question(id = "2", text = "What's one thing you wish we talked about more?", category = "communication", depthLevel = 2)
            ),
            currentIndex = 0,
            categoryName = "Trust"
        ),
        onSelectOption = {},
        onScaleChanged = {},
        onWrittenTextChanged = {},
        onNext = {},
        onSkip = {},
        onEnd = {}
    )
}
