package app.closer.ui.wheel

import app.closer.ui.theme.closerCardColor
import androidx.compose.animation.core.LinearOutSlowInEasing
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Canvas
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.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.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Lock
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import app.closer.ui.components.CloserHeartLoader
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.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.runtime.mutableFloatStateOf
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.rotate
import androidx.compose.ui.draw.scale
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.drawscope.Stroke
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.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.R
import app.closer.ui.theme.CloserPalette
import app.closer.ui.theme.closerBackgroundBrush

@Composable
fun SpinWheelScreen(
    categoryId: String,
    onNavigate: (String) -> Unit = {},
    onBack: () -> Unit = {},
    viewModel: SpinWheelViewModel = hiltViewModel()
) {
    val state by viewModel.uiState.collectAsState()

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

    SpinWheelContent(
        state = state,
        onSpin = viewModel::spin,
        onStart = viewModel::startSession,
        onChooseCategory = viewModel::onChooseCategory,
        onHistory = viewModel::onHistory,
        onPaywall = viewModel::onPaywall,
        onBack = onBack
    )
}

@Composable
private fun SpinWheelContent(
    state: SpinWheelUiState,
    onSpin: () -> Unit,
    onStart: () -> Unit,
    onChooseCategory: () -> Unit,
    onHistory: () -> Unit,
    onPaywall: () -> Unit,
    onBack: () -> Unit
) {
    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(closerBackgroundBrush()),
        contentAlignment = Alignment.Center
    ) {
        Column(
            modifier = Modifier
                .fillMaxSize()
                .safeDrawingPadding()
                .navigationBarsPadding()
                .padding(horizontal = 28.dp, vertical = 32.dp),
            verticalArrangement = Arrangement.spacedBy(28.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            // Header row with back button
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                IconButton(onClick = onBack) {
                    Icon(
                        imageVector = Icons.AutoMirrored.Filled.ArrowBack,
                        contentDescription = "Back",
                        tint = MaterialTheme.colorScheme.onBackground
                    )
                }
                TextButton(onClick = onHistory) {
                    Text(
                        "History",
                        style = MaterialTheme.typography.labelLarge,
                        color = CloserPalette.PurpleDeep
                    )
                }
            }

            // Title + category pill
            Column(
                modifier = Modifier.fillMaxWidth(),
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.spacedBy(10.dp)
            ) {
                Text(
                    text = "Let the prompt find you",
                    style = MaterialTheme.typography.headlineMedium.copy(fontWeight = FontWeight.SemiBold),
                    color = MaterialTheme.colorScheme.onBackground,
                    textAlign = TextAlign.Center,
                    maxLines = 2,
                    overflow = TextOverflow.Ellipsis
                )
                if (state.categoryName.isNotBlank()) {
                    Surface(
                        shape = RoundedCornerShape(999.dp),
                        color = CloserPalette.PurpleMist
                    ) {
                        Text(
                            text = state.categoryName,
                            modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
                            style = MaterialTheme.typography.labelLarge,
                            color = CloserPalette.PurpleDeep,
                            maxLines = 1,
                            overflow = TextOverflow.Ellipsis
                        )
                    }
                }
            }

            Box(
                contentAlignment = Alignment.Center,
                modifier = Modifier.weight(1f)
            ) {
                WheelSpinner(
                    isSpinning = state.isSpinning,
                    spunAndReady = state.spunAndReady,
                    onSpin = onSpin
                )
            }

            Column(
                modifier = Modifier.fillMaxWidth(),
                verticalArrangement = Arrangement.spacedBy(12.dp)
            ) {
                when {
                    state.error != null -> Text(
                        text = state.error,
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.error,
                        textAlign = TextAlign.Center,
                        modifier = Modifier.fillMaxWidth()
                    )
                    state.spunAndReady -> {
                        Text(
                            text = "10 questions ready · ${state.categoryName}",
                            style = MaterialTheme.typography.bodyMedium,
                            color = MaterialTheme.colorScheme.onSurfaceVariant,
                            textAlign = TextAlign.Center,
                            modifier = Modifier.fillMaxWidth()
                        )
                        if (!state.isPaired) {
                            Text(
                                text = "Connect with a partner to start playing",
                                style = MaterialTheme.typography.bodySmall,
                                color = MaterialTheme.colorScheme.onSurfaceVariant,
                                textAlign = TextAlign.Center,
                                modifier = Modifier.fillMaxWidth()
                            )
                        }
                        Button(
                            onClick = onStart,
                            enabled = state.isPaired,
                            modifier = Modifier
                                .fillMaxWidth()
                                .heightIn(min = 56.dp),
                            shape = RoundedCornerShape(18.dp),
                            colors = ButtonDefaults.buttonColors(containerColor = CloserPalette.PurpleDeep)
                        ) {
                            Text("Start session", color = MaterialTheme.colorScheme.surface)
                        }
                        // Spin again is a premium feature
                        OutlinedButton(
                            onClick = { if (state.hasPremium) onSpin() else onPaywall() },
                            modifier = Modifier
                                .fillMaxWidth()
                                .heightIn(min = 56.dp),
                            shape = RoundedCornerShape(18.dp),
                            border = BorderStroke(
                                1.dp,
                                CloserPalette.PurpleDeep.copy(alpha = if (state.hasPremium) 0.44f else 0.28f)
                            ),
                            colors = ButtonDefaults.outlinedButtonColors(
                                contentColor = CloserPalette.PurpleDeep
                            )
                        ) {
                            if (!state.hasPremium) {
                                Icon(
                                    imageVector = Icons.Filled.Lock,
                                    contentDescription = null,
                                    modifier = Modifier.size(14.dp)
                                )
                                Spacer(Modifier.width(6.dp))
                            }
                            Text("Spin again")
                            if (!state.hasPremium) {
                                Spacer(Modifier.width(8.dp))
                                Surface(
                                    shape = RoundedCornerShape(999.dp),
                                    color = CloserPalette.PurpleMist
                                ) {
                                    Text(
                                        text = "Premium",
                                        modifier = Modifier.padding(horizontal = 8.dp, vertical = 3.dp),
                                        style = MaterialTheme.typography.labelSmall,
                                        color = CloserPalette.PurpleDeep
                                    )
                                }
                            }
                        }
                    }
                    state.isLoading -> CloserHeartLoader()
                    else -> {
                        Text(
                            text = "Spin to discover a random category and 10 questions",
                            style = MaterialTheme.typography.bodyMedium,
                            color = MaterialTheme.colorScheme.onSurfaceVariant,
                            textAlign = TextAlign.Center,
                            modifier = Modifier.fillMaxWidth()
                        )
                        Button(
                            onClick = onSpin,
                            modifier = Modifier
                                .fillMaxWidth()
                                .heightIn(min = 56.dp),
                            shape = RoundedCornerShape(18.dp),
                            colors = ButtonDefaults.buttonColors(containerColor = CloserPalette.PurpleDeep)
                        ) {
                            Text("Spin wheel", color = MaterialTheme.colorScheme.surface)
                        }
                        // Premium: choose a specific category
                        if (!state.isSpinning) {
                            ChooseCategoryButton(
                                hasPremium = state.hasPremium,
                                onClick = onChooseCategory
                            )
                        }
                    }
                }
            }
        }
    }
}

@Composable
private fun ChooseCategoryButton(hasPremium: Boolean, onClick: () -> Unit) {
    OutlinedButton(
        onClick = onClick,
        modifier = Modifier
            .fillMaxWidth()
            .heightIn(min = 48.dp),
        shape = RoundedCornerShape(18.dp),
        border = BorderStroke(1.dp, CloserPalette.PurpleDeep.copy(alpha = 0.28f)),
        colors = ButtonDefaults.outlinedButtonColors(contentColor = CloserPalette.PurpleDeep)
    ) {
        if (!hasPremium) {
            Icon(
                imageVector = Icons.Filled.Lock,
                contentDescription = null,
                modifier = Modifier.size(14.dp)
            )
            Spacer(Modifier.width(6.dp))
        }
        Text(
            text = "Choose a category",
            style = MaterialTheme.typography.labelLarge
        )
        if (!hasPremium) {
            Spacer(Modifier.width(8.dp))
            Surface(
                shape = RoundedCornerShape(999.dp),
                color = CloserPalette.PurpleMist
            ) {
                Text(
                    text = "Premium",
                    modifier = Modifier.padding(horizontal = 8.dp, vertical = 3.dp),
                    style = MaterialTheme.typography.labelSmall,
                    color = CloserPalette.PurpleDeep
                )
            }
        }
    }
}

@Composable
private fun WheelSpinner(
    isSpinning: Boolean,
    spunAndReady: Boolean,
    onSpin: () -> Unit
) {
    // Accumulated spin angle — increases with each spin, never resets.
    // Using a box so LaunchedEffect can write into it without triggering recomposition of its parent.
    var spinEndAngle by remember { mutableFloatStateOf(0f) }

    LaunchedEffect(isSpinning) {
        if (isSpinning) {
            // 4-6 full rotations plus a random stop angle for variety
            spinEndAngle += 360f * (4..6).random() + (0..359).random()
        }
    }

    val wheelAngle by animateFloatAsState(
        targetValue = spinEndAngle,
        animationSpec = tween(
            durationMillis = SpinWheelViewModel.SPIN_DURATION_MS.toInt(),
            easing = LinearOutSlowInEasing
        ),
        label = "wheel_decel"
    )

    val idleTransition = rememberInfiniteTransition(label = "wheel_idle")
    val idlePulse by idleTransition.animateFloat(
        initialValue = 0.98f,
        targetValue = 1.02f,
        animationSpec = infiniteRepeatable(
            animation = tween(durationMillis = 1400),
            repeatMode = RepeatMode.Reverse
        ),
        label = "wheel_idle_pulse"
    )
    val centerScale by animateFloatAsState(
        targetValue = if (spunAndReady) 1.08f else 1f,
        animationSpec = tween(durationMillis = 220),
        label = "wheel_center_scale"
    )
    val pointerScale by animateFloatAsState(
        targetValue = if (isSpinning) 1.12f else 1f,
        animationSpec = tween(durationMillis = 160),
        label = "wheel_pointer_scale"
    )
    val wheelRingColor = closerCardColor(alpha = 0.84f)

    Box(
        modifier = Modifier
            .size(270.dp)
            .scale(if (isSpinning) 1f else idlePulse),
        contentAlignment = Alignment.Center
    ) {
        Image(
            painter = painterResource(R.drawable.illustration_spin_wheel),
            contentDescription = null,
            contentScale = ContentScale.Fit,
            modifier = Modifier
                .size(236.dp)
                .rotate(wheelAngle)
        )

        Canvas(modifier = Modifier.size(236.dp)) {
            drawCircle(
                color = wheelRingColor,
                style = Stroke(width = 7.dp.toPx())
            )
        }

        Canvas(
            modifier = Modifier
                .align(Alignment.TopCenter)
                .size(width = 34.dp, height = 28.dp)
                .scale(pointerScale)
        ) {
            val path = Path().apply {
                moveTo(size.width / 2f, size.height)
                lineTo(0f, 0f)
                lineTo(size.width, 0f)
                close()
            }
            drawPath(path = path, color = CloserPalette.PurpleDeep)
        }

        Surface(
            onClick = onSpin,
            enabled = !isSpinning && !spunAndReady,
            modifier = Modifier
                .size(94.dp)
                .scale(centerScale),
            shape = CircleShape,
            color = if (spunAndReady) CloserPalette.PinkMist else MaterialTheme.colorScheme.surface,
            shadowElevation = 10.dp
        ) {
            Box(contentAlignment = Alignment.Center) {
                Text(
                    text = if (spunAndReady) "Ready" else "Spin",
                    style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.SemiBold),
                    color = CloserPalette.PurpleDeep,
                    textAlign = TextAlign.Center,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis
                )
            }
        }
    }
}

@Preview
@Composable
fun SpinWheelScreenPreview() {
    SpinWheelContent(
        state = SpinWheelUiState(isLoading = false, categoryName = "Trust"),
        onSpin = {},
        onStart = {},
        onChooseCategory = {},
        onHistory = {},
        onPaywall = {},
        onBack = {}
    )
}
