package com.rosetta.messenger.ui.auth

import androidx.compose.animation.*
import androidx.compose.animation.core.*
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import compose.icons.TablerIcons
import compose.icons.tablericons.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.airbnb.lottie.compose.*
import com.rosetta.messenger.ui.onboarding.PrimaryBlue

// Auth colors
val AuthBackground = Color(0xFF1B1B1B)
val AuthBackgroundLight = Color(0xFFFFFFFF)
val AuthSurface = Color(0xFF2A2A2A)
val AuthSurfaceLight = Color(0xFFF5F5F5)

@Composable
fun WelcomeScreen(
        isDarkTheme: Boolean,
        hasExistingAccount: Boolean = false,
        onBack: () -> Unit = {},
        onCreateSeed: () -> Unit,
        onImportSeed: () -> Unit
) {
    val themeAnimSpec =
            tween<Color>(durationMillis = 500, easing = CubicBezierEasing(0.4f, 0f, 0.2f, 1f))
    val backgroundColor by
            animateColorAsState(
                    if (isDarkTheme) AuthBackground else AuthBackgroundLight,
                    animationSpec = themeAnimSpec
            )
    val textColor by
            animateColorAsState(
                    if (isDarkTheme) Color.White else Color.Black,
                    animationSpec = themeAnimSpec
            )
    val secondaryTextColor by
            animateColorAsState(
                    if (isDarkTheme) Color(0xFF8E8E93) else Color(0xFF666666),
                    animationSpec = themeAnimSpec
            )

    // Sync navigation bar color with background
    val view = LocalView.current
    SideEffect {
        val window = (view.context as? android.app.Activity)?.window
        window?.navigationBarColor = backgroundColor.toArgb()
    }

    // Animation for Lottie
    val lockComposition by
            rememberLottieComposition(LottieCompositionSpec.Asset("lottie/lock.json"))
    val lockProgress by
            animateLottieCompositionAsState(
                    composition = lockComposition,
                    iterations = 1, // Play once
                    speed = 1f
            )

    // Entry animation
    var visible by remember { mutableStateOf(false) }
    LaunchedEffect(Unit) { visible = true }

    Box(modifier = Modifier.fillMaxSize().background(backgroundColor).navigationBarsPadding()) {
        // Back button when coming from UnlockScreen
        if (hasExistingAccount) {
            IconButton(onClick = onBack, modifier = Modifier.statusBarsPadding().padding(4.dp)) {
                Icon(
                        TablerIcons.ChevronLeft,
                        contentDescription = "Back",
                        tint = textColor.copy(alpha = 0.6f)
                )
            }
        }

        Column(
                modifier = Modifier.fillMaxSize().padding(horizontal = 24.dp).statusBarsPadding(),
                horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Spacer(modifier = Modifier.weight(0.15f))

            // Animated Lock Icon
            AnimatedVisibility(
                    visible = visible,
                    enter = fadeIn(tween(300)) + scaleIn(tween(300, easing = FastOutSlowInEasing))
            ) {
                Box(modifier = Modifier.size(180.dp), contentAlignment = Alignment.Center) {
                    lockComposition?.let { comp ->
                        LottieAnimation(
                                composition = comp,
                                progress = { lockProgress },
                                modifier = Modifier.fillMaxSize()
                        )
                    }
                }
            }

            Spacer(modifier = Modifier.height(32.dp))

            // Title
            AnimatedVisibility(
                    visible = visible,
                    enter = fadeIn(tween(400, delayMillis = 200))
            ) {
                Text(
                        text = "Your Keys,\nYour Messages",
                        fontSize = 32.sp,
                        fontWeight = FontWeight.Bold,
                        color = textColor,
                        textAlign = TextAlign.Center,
                        lineHeight = 40.sp
                )
            }

            Spacer(modifier = Modifier.height(16.dp))

            // Subtitle
            AnimatedVisibility(
                    visible = visible,
                    enter = fadeIn(tween(400, delayMillis = 300))
            ) {
                Text(
                        text = "Secure messaging with\ncryptographic keys",
                        fontSize = 16.sp,
                        color = secondaryTextColor,
                        textAlign = TextAlign.Center,
                        lineHeight = 24.sp,
                        modifier = Modifier.padding(horizontal = 8.dp)
                )
            }

            Spacer(modifier = Modifier.height(24.dp))

            // Features list with icons - placed above buttons
            AnimatedVisibility(visible = visible, enter = fadeIn(tween(600, delayMillis = 400))) {
                Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceEvenly
                ) {
                    CompactFeatureItem(
                            icon = Icons.Default.Security,
                            text = "Encrypted",
                            isDarkTheme = isDarkTheme,
                            textColor = textColor
                    )
                    CompactFeatureItem(
                            icon = Icons.Default.NoAccounts,
                            text = "No Phone",
                            isDarkTheme = isDarkTheme,
                            textColor = textColor
                    )
                    CompactFeatureItem(
                            icon = Icons.Default.Key,
                            text = "Your Keys",
                            isDarkTheme = isDarkTheme,
                            textColor = textColor
                    )
                }
            }

            Spacer(modifier = Modifier.height(32.dp))

            // Create Seed Button
            AnimatedVisibility(
                    visible = visible,
                    enter = fadeIn(tween(400, delayMillis = 500))
            ) {
                Button(
                        onClick = onCreateSeed,
                        modifier = Modifier.fillMaxWidth().height(56.dp),
                        colors =
                                ButtonDefaults.buttonColors(
                                        containerColor = PrimaryBlue,
                                        contentColor = Color.White
                                ),
                        shape = RoundedCornerShape(16.dp),
                        elevation =
                                ButtonDefaults.buttonElevation(
                                        defaultElevation = 0.dp,
                                        pressedElevation = 0.dp
                                )
                ) {
                    Icon(
                            imageVector = Icons.Default.Key,
                            contentDescription = null,
                            modifier = Modifier.size(22.dp)
                    )
                    Spacer(modifier = Modifier.width(12.dp))
                    Text(
                            text = "Generate New Seed Phrase",
                            fontSize = 16.sp,
                            fontWeight = FontWeight.SemiBold
                    )
                }
            }

            Spacer(modifier = Modifier.height(12.dp))

            // Import Seed Button
            AnimatedVisibility(
                    visible = visible,
                    enter = fadeIn(tween(400, delayMillis = 600))
            ) {
                TextButton(
                        onClick = onImportSeed,
                        modifier = Modifier.fillMaxWidth().height(56.dp),
                        shape = RoundedCornerShape(16.dp)
                ) {
                    Icon(
                            imageVector = Icons.Default.Download,
                            contentDescription = null,
                            modifier = Modifier.size(20.dp),
                            tint = PrimaryBlue
                    )
                    Spacer(modifier = Modifier.width(8.dp))
                    Text(
                            text = "I Already Have a Seed Phrase",
                            fontSize = 15.sp,
                            fontWeight = FontWeight.Medium,
                            color = PrimaryBlue
                    )
                }
            }

            Spacer(modifier = Modifier.weight(0.15f))
        }
    }
}

@Composable
private fun CompactFeatureItem(
        icon: androidx.compose.ui.graphics.vector.ImageVector,
        text: String,
        isDarkTheme: Boolean,
        textColor: Color
) {
    Column(
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        Box(
                modifier =
                        Modifier.size(48.dp)
                                .clip(CircleShape)
                                .background(PrimaryBlue.copy(alpha = 0.12f)),
                contentAlignment = Alignment.Center
        ) {
            Icon(
                    imageVector = icon,
                    contentDescription = null,
                    tint = PrimaryBlue,
                    modifier = Modifier.size(24.dp)
            )
        }
        Text(
                text = text,
                fontSize = 13.sp,
                color = textColor.copy(alpha = 0.8f),
                fontWeight = FontWeight.Medium,
                textAlign = TextAlign.Center
        )
    }
}

@Composable
private fun FeatureItem(
        icon: androidx.compose.ui.graphics.vector.ImageVector,
        text: String,
        isDarkTheme: Boolean,
        textColor: Color
) {
    Row(modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
        Box(
                modifier =
                        Modifier.size(40.dp)
                                .clip(CircleShape)
                                .background(PrimaryBlue.copy(alpha = 0.15f)),
                contentAlignment = Alignment.Center
        ) {
            Icon(
                    imageVector = icon,
                    contentDescription = null,
                    tint = PrimaryBlue,
                    modifier = Modifier.size(20.dp)
            )
        }
        Spacer(modifier = Modifier.width(16.dp))
        Text(text = text, fontSize = 15.sp, color = textColor, fontWeight = FontWeight.Medium)
    }
}
