package app.closer.ui.answers

import app.closer.R
import app.closer.ui.theme.closerBackgroundBrush
import app.closer.ui.theme.closerCardColor
import app.closer.ui.theme.closerSoftPurpleColor
import app.closer.ui.theme.closerSoftSurfaceColor
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
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.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Lock
import androidx.compose.material.icons.filled.Visibility
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
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.collectAsState
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.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.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import app.closer.core.navigation.AppRoute
import app.closer.domain.model.LocalAnswer
import app.closer.ui.components.CategoryGlyph
import app.closer.ui.components.EmptyState
import app.closer.ui.theme.CloserPalette
import app.closer.ui.questions.displayCategoryName

private enum class AnswerHistoryFilter {
    ALL, PRIVATE, REVEALED
}

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

    AnswerHistoryContent(
        state = state,
        onAnswerSelected = {
            if (state.isPairingLoaded) {
                onNavigate(if (state.isPaired) AppRoute.answerReveal(it.questionId) else AppRoute.CREATE_INVITE)
            }
        },
        onEmptyAction = {
            if (state.isPairingLoaded) {
                onNavigate(if (state.isPaired) AppRoute.DAILY_QUESTION else AppRoute.CREATE_INVITE)
            }
        },
        onDelete = viewModel::deleteAnswer
    )
}

@Composable
private fun AnswerHistoryContent(
    state: AnswerHistoryUiState,
    onAnswerSelected: (LocalAnswer) -> Unit,
    onEmptyAction: () -> Unit,
    onDelete: (String) -> Unit
) {
    var pendingDelete by remember { mutableStateOf<LocalAnswer?>(null) }
    var selectedFilter by remember { mutableStateOf(AnswerHistoryFilter.ALL) }
    val visibleAnswers = remember(state.answers, selectedFilter) {
        state.answers.filter { answer ->
            when (selectedFilter) {
                AnswerHistoryFilter.ALL -> true
                AnswerHistoryFilter.PRIVATE -> !answer.isRevealed
                AnswerHistoryFilter.REVEALED -> answer.isRevealed
            }
        }
    }

    pendingDelete?.let { answer ->
        AlertDialog(
            onDismissRequest = { pendingDelete = null },
            title = { Text("Remove this answer?") },
            text = {
                Text("This removes the saved reflection from this device. The prompt itself will stay available.")
            },
            confirmButton = {
                Button(
                    onClick = {
                        onDelete(answer.questionId)
                        pendingDelete = null
                    },
                    colors = ButtonDefaults.buttonColors(
                        containerColor = Color(0xFF8D2D35),
                        contentColor = Color.White
                    )
                ) {
                    Text("Remove")
                }
            },
            dismissButton = {
                TextButton(onClick = { pendingDelete = null }) {
                    Text("Keep")
                }
            }
        )
    }

    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(
                closerBackgroundBrush()
            )
    ) {
        LazyColumn(
            modifier = Modifier
                .fillMaxSize()
                .safeDrawingPadding()
                .navigationBarsPadding()
                .padding(horizontal = 20.dp),
            verticalArrangement = Arrangement.spacedBy(14.dp)
        ) {
            item {
                Column(
                    modifier = Modifier.padding(top = 20.dp, bottom = 4.dp),
                    verticalArrangement = Arrangement.spacedBy(10.dp)
                ) {
                    Text(
                        text = "What you have opened",
                        style = MaterialTheme.typography.headlineLarge.copy(fontWeight = FontWeight.SemiBold),
                        color = MaterialTheme.colorScheme.onSurface
                    )
                    Text(
                        text = "Private answers and revealed reflections, gathered in one place.",
                        style = MaterialTheme.typography.bodyLarge,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
            }

            if (state.answers.isEmpty()) {
                item {
                    val title = when {
                        !state.isPairingLoaded -> "Checking your space"
                        state.isPaired -> "Nothing here yet"
                        else -> "Connect your partner"
                    }
                    val body = when {
                        !state.isPairingLoaded -> "We are checking whether this private space is connected."
                        state.isPaired -> "Answer today's question or pick a prompt from a pack. Every answer you save will wait for you here."
                        else -> "Invite your partner to unlock shared reveals and build your private answer history together."
                    }
                    val actionLabel = when {
                        !state.isPairingLoaded -> null
                        state.isPaired -> "Today's question"
                        else -> "Invite partner"
                    }
                    val onAction = if (state.isPairingLoaded) {
                        onEmptyAction
                    } else {
                        null
                    }
                    EmptyState(
                        title = title,
                        body = body,
                        actionLabel = actionLabel,
                        onAction = onAction,
                        illustrationResId = R.drawable.illustration_couple_history
                    )
                }
            } else {
                item {
                    HistoryFilterRow(
                        selected = selectedFilter,
                        privateCount = state.answers.count { !it.isRevealed },
                        revealedCount = state.answers.count { it.isRevealed },
                        onSelected = { selectedFilter = it }
                    )
                }

                if (visibleAnswers.isEmpty()) {
                    item {
                        EmptyState(
                            title = "Nothing in this filter",
                            body = "Your answers are here — just in the other tab. Switch between Private and Revealed to see them."
                        )
                    }
                }

                items(visibleAnswers, key = { it.questionId }) { answer ->
                    AnswerHistoryCard(
                        answer = answer,
                        onClick = { onAnswerSelected(answer) },
                        onDelete = { pendingDelete = answer }
                    )
                }
            }
        }
    }
}

@Composable
private fun HistoryFilterRow(
    selected: AnswerHistoryFilter,
    privateCount: Int,
    revealedCount: Int,
    onSelected: (AnswerHistoryFilter) -> Unit
) {
    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        HistoryFilterPill(
            label = "All",
            count = privateCount + revealedCount,
            selected = selected == AnswerHistoryFilter.ALL,
            onClick = { onSelected(AnswerHistoryFilter.ALL) },
            modifier = Modifier.weight(1f)
        )
        HistoryFilterPill(
            label = "Private",
            count = privateCount,
            selected = selected == AnswerHistoryFilter.PRIVATE,
            onClick = { onSelected(AnswerHistoryFilter.PRIVATE) },
            modifier = Modifier.weight(1f)
        )
        HistoryFilterPill(
            label = "Revealed",
            count = revealedCount,
            selected = selected == AnswerHistoryFilter.REVEALED,
            onClick = { onSelected(AnswerHistoryFilter.REVEALED) },
            modifier = Modifier.weight(1f)
        )
    }
}

@Composable
private fun HistoryFilterPill(
    label: String,
    count: Int,
    selected: Boolean,
    onClick: () -> Unit,
    modifier: Modifier = Modifier
) {
    Surface(
        modifier = modifier
            .heightIn(min = 44.dp)
            .clickable(onClick = onClick),
        shape = RoundedCornerShape(999.dp),
        color = if (selected) closerSoftPurpleColor() else closerSoftSurfaceColor(alpha = 0.74f),
        shadowElevation = if (selected) 2.dp else 0.dp
    ) {
        Text(
            text = "$label $count",
            modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp),
            style = MaterialTheme.typography.labelMedium,
            color = if (selected) MaterialTheme.colorScheme.onPrimaryContainer else MaterialTheme.colorScheme.onSurfaceVariant,
            fontWeight = if (selected) FontWeight.SemiBold else FontWeight.Medium,
            maxLines = 1,
            overflow = TextOverflow.Ellipsis
        )
    }
}


@OptIn(ExperimentalLayoutApi::class)
@Composable
private fun AnswerHistoryCard(
    answer: LocalAnswer,
    onClick: () -> Unit,
    onDelete: () -> Unit
) {
    Card(
        onClick = onClick,
        modifier = Modifier.fillMaxWidth(),
        shape = RoundedCornerShape(24.dp),
        colors = CardDefaults.cardColors(containerColor = closerCardColor(alpha = 0.94f)),
        elevation = CardDefaults.cardElevation(defaultElevation = 6.dp)
    ) {
        Row(
            modifier = Modifier.padding(17.dp),
            horizontalArrangement = Arrangement.spacedBy(12.dp),
            verticalAlignment = Alignment.Top
        ) {
            CategoryGlyph(
                categoryId = answer.category,
                modifier = Modifier.size(46.dp),
                size = 46.dp,
                iconSize = 22.dp
            )
            Column(
                modifier = Modifier.weight(1f),
                verticalArrangement = Arrangement.spacedBy(12.dp)
            ) {
                FlowRow(
                    horizontalArrangement = Arrangement.spacedBy(8.dp),
                    verticalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    HistoryStateBadge(isRevealed = answer.isRevealed)
                    HistoryPill(answer.category.displayCategoryName())
                }
                Text(
                    text = answer.questionText,
                    style = MaterialTheme.typography.titleMedium,
                    color = MaterialTheme.colorScheme.onSurface,
                    fontWeight = FontWeight.SemiBold,
                    maxLines = 2,
                    overflow = TextOverflow.Ellipsis
                )
                Text(
                    text = if (answer.isRevealed) answer.revealSummary() else "Saved privately. Tap to reveal.",
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    maxLines = 2,
                    overflow = TextOverflow.Ellipsis
                )
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween
                ) {
                    Text(
                        text = if (answer.isRevealed) "Opened" else "Private",
                        style = MaterialTheme.typography.labelMedium,
                        color = MaterialTheme.colorScheme.onPrimaryContainer,
                        fontWeight = FontWeight.SemiBold
                    )
                    TextButton(
                        onClick = onDelete,
                        modifier = Modifier.heightIn(min = 48.dp)
                    ) {
                        Text(
                            text = "Remove",
                            color = Color(0xFF8D2D35)
                        )
                    }
                }
            }
        }
    }
}

@Composable
private fun HistoryStateBadge(isRevealed: Boolean) {
    val tint = if (isRevealed) MaterialTheme.colorScheme.onPrimaryContainer else CloserPalette.Evergreen
    val container = if (isRevealed) closerSoftPurpleColor() else CloserPalette.Evergreen.copy(alpha = 0.10f)
    Surface(
        shape = RoundedCornerShape(999.dp),
        color = container
    ) {
        Row(
            modifier = Modifier.padding(horizontal = 10.dp, vertical = 7.dp),
            horizontalArrangement = Arrangement.spacedBy(6.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Icon(
                imageVector = if (isRevealed) Icons.Filled.Visibility else Icons.Filled.Lock,
                contentDescription = null,
                tint = tint,
                modifier = Modifier.size(14.dp)
            )
            Text(
                text = if (isRevealed) "Revealed" else "Private",
                style = MaterialTheme.typography.labelMedium,
                color = tint,
                fontWeight = FontWeight.SemiBold
            )
        }
    }
}

@Composable
private fun HistoryPill(label: String) {
    Surface(
        shape = RoundedCornerShape(999.dp),
        color = closerSoftSurfaceColor()
    ) {
        Text(
            text = label,
            modifier = Modifier.padding(horizontal = 11.dp, vertical = 7.dp),
            style = MaterialTheme.typography.labelMedium,
            color = MaterialTheme.colorScheme.onSurface
        )
    }
}

@Preview
@Composable
fun AnswerHistoryScreenPreview() {
    AnswerHistoryContent(
        state = AnswerHistoryUiState(
            answers = listOf(
                LocalAnswer(
                    questionId = "demo",
                    questionText = "What helped you feel close this week?",
                    category = "gratitude",
                    answerType = "written",
                    writtenText = "The quiet walk after dinner.",
                    isRevealed = true
                )
            )
        ),
        onAnswerSelected = {},
        onEmptyAction = {},
        onDelete = {}
    )
}
