package com.rosetta.messenger.ui.auth

import androidx.compose.animation.*
import androidx.compose.animation.core.*
import androidx.compose.foundation.*
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
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.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontFamily
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 androidx.compose.ui.platform.LocalClipboardManager
import androidx.compose.ui.text.AnnotatedString
import com.rosetta.messenger.crypto.CryptoManager
import com.rosetta.messenger.ui.onboarding.PrimaryBlue
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

@Composable
fun SeedPhraseScreen(
    isDarkTheme: Boolean,
    onBack: () -> Unit,
    onConfirm: (List<String>) -> Unit
) {
    val backgroundColor = if (isDarkTheme) Color(0xFF1E1E1E) else Color(0xFFFFFFFF)
    val textColor = if (isDarkTheme) Color.White else Color.Black
    val secondaryTextColor = if (isDarkTheme) Color(0xFF8E8E93) else Color(0xFF666666)
    val cardBackground = if (isDarkTheme) Color(0xFF2A2A2A) else Color(0xFFF5F5F5)
    
    var seedPhrase by remember { mutableStateOf<List<String>>(emptyList()) }
    var isGenerating by remember { mutableStateOf(true) }
    var hasCopied by remember { mutableStateOf(false) }
    var visible by remember { mutableStateOf(false) }
    val scope = rememberCoroutineScope()
    val clipboardManager = LocalClipboardManager.current
    
    LaunchedEffect(Unit) {
        delay(100)
        seedPhrase = CryptoManager.generateSeedPhrase()
        isGenerating = false
        visible = true
    }
    
    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(backgroundColor)
            .statusBarsPadding()
            .navigationBarsPadding()
    ) {
        Column(modifier = Modifier.fillMaxSize()) {
            // Simple top bar
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(4.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                IconButton(onClick = onBack) {
                    Icon(Icons.Default.ArrowBack, "Back", tint = textColor)
                }
            }
            
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(horizontal = 24.dp),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                Spacer(modifier = Modifier.height(16.dp))
                
                AnimatedVisibility(
                    visible = visible,
                    enter = fadeIn(tween(300))
                ) {
                    Text(
                        text = "Your Recovery Phrase",
                        fontSize = 28.sp,
                        fontWeight = FontWeight.Bold,
                        color = textColor
                    )
                }
                
                Spacer(modifier = Modifier.height(12.dp))
                
                AnimatedVisibility(
                    visible = visible,
                    enter = fadeIn(tween(400, delayMillis = 100))
                ) {
                    Text(
                        text = "Write down these 12 words in order.\nYou'll need them to restore your account.",
                        fontSize = 15.sp,
                        color = secondaryTextColor,
                        textAlign = TextAlign.Center,
                        lineHeight = 22.sp
                    )
                }
                
                Spacer(modifier = Modifier.height(32.dp))
                
                // Two column layout
                if (isGenerating) {
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(300.dp),
                        contentAlignment = Alignment.Center
                    ) {
                        CircularProgressIndicator(
                            color = PrimaryBlue,
                            strokeWidth = 2.dp,
                            modifier = Modifier.size(40.dp)
                        )
                    }
                } else {
                    AnimatedVisibility(
                        visible = visible,
                        enter = fadeIn(tween(500, delayMillis = 200))
                    ) {
                        Row(
                            modifier = Modifier.fillMaxWidth(),
                            horizontalArrangement = Arrangement.spacedBy(12.dp)
                        ) {
                            // Left column (words 1-6)
                            Column(
                                modifier = Modifier.weight(1f),
                                verticalArrangement = Arrangement.spacedBy(12.dp)
                            ) {
                                for (i in 0..5) {
                                    AnimatedWordItem(
                                        number = i + 1,
                                        word = seedPhrase[i],
                                        isDarkTheme = isDarkTheme,
                                        visible = visible,
                                        delay = 300 + (i * 50)
                                    )
                                }
                            }
                            
                            // Right column (words 7-12)
                            Column(
                                modifier = Modifier.weight(1f),
                                verticalArrangement = Arrangement.spacedBy(12.dp)
                            ) {
                                for (i in 6..11) {
                                    AnimatedWordItem(
                                        number = i + 1,
                                        word = seedPhrase[i],
                                        isDarkTheme = isDarkTheme,
                                        visible = visible,
                                        delay = 300 + (i * 50)
                                    )
                                }
                            }
                        }
                    }
                }
                
                Spacer(modifier = Modifier.height(20.dp))
                
                // Copy button
                if (!isGenerating) {
                    AnimatedVisibility(
                        visible = visible,
                        enter = fadeIn(tween(500, delayMillis = 600)) + scaleIn(
                            initialScale = 0.8f,
                            animationSpec = tween(500, delayMillis = 600)
                        )
                    ) {
                        TextButton(
                            onClick = {
                                clipboardManager.setText(AnnotatedString(seedPhrase.joinToString(" ")))
                                hasCopied = true
                                scope.launch {
                                    delay(2000)
                                    hasCopied = false
                                }
                            }
                        ) {
                            Icon(
                                imageVector = if (hasCopied) Icons.Default.Check else Icons.Default.ContentCopy,
                                contentDescription = null,
                                tint = if (hasCopied) Color(0xFF4CAF50) else PrimaryBlue,
                                modifier = Modifier.size(20.dp)
                            )
                            Spacer(modifier = Modifier.width(8.dp))
                            Text(
                                text = if (hasCopied) "Copied" else "Copy to clipboard",
                                color = if (hasCopied) Color(0xFF4CAF50) else PrimaryBlue,
                                fontSize = 15.sp
                            )
                        }
                    }
                }
                
                Spacer(modifier = Modifier.weight(1f))
                
                // Continue button
                AnimatedVisibility(
                    visible = visible,
                    enter = fadeIn(tween(400, delayMillis = 700))
                ) {
                    Button(
                        onClick = { onConfirm(seedPhrase) },
                        enabled = !isGenerating,
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(50.dp),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = PrimaryBlue,
                            contentColor = Color.White,
                            disabledContainerColor = PrimaryBlue.copy(alpha = 0.5f),
                            disabledContentColor = Color.White.copy(alpha = 0.5f)
                        ),
                        shape = RoundedCornerShape(12.dp)
                    ) {
                        Text(
                            text = "Continue",
                            fontSize = 17.sp,
                            fontWeight = FontWeight.Medium
                        )
                    }
                }
                
                Spacer(modifier = Modifier.height(40.dp))
            }
        }
    }
}

@Composable
private fun WordItem(
    number: Int,
    word: String,
    isDarkTheme: Boolean,
    modifier: Modifier = Modifier
) {
    val numberColor = if (isDarkTheme) Color(0xFF888888) else Color(0xFF999999)
    
    // Beautiful solid colors that fit the theme
    val wordColors = listOf(
        Color(0xFF5E9FFF), // Soft blue
        Color(0xFFFF7EB3), // Soft pink
        Color(0xFF7B68EE), // Medium purple
        Color(0xFF50C878), // Emerald green
        Color(0xFFFF6B6B), // Coral red
        Color(0xFF4ECDC4), // Teal
        Color(0xFFFFB347), // Pastel orange
        Color(0xFFBA55D3), // Medium orchid
        Color(0xFF87CEEB), // Sky blue
        Color(0xFFDDA0DD), // Plum
        Color(0xFF98D8C8), // Mint
        Color(0xFFF7DC6F)  // Soft yellow
    )
    
    val wordColor = wordColors[(number - 1) % wordColors.size]
    val bgColor = if (isDarkTheme) Color(0xFF2A2A2A) else Color(0xFFF5F5F5)
    
    Box(
        modifier = modifier
            .fillMaxWidth()
            .clip(RoundedCornerShape(12.dp))
            .background(bgColor)
            .padding(horizontal = 16.dp, vertical = 14.dp)
    ) {
        Row(
            verticalAlignment = Alignment.CenterVertically,
            modifier = Modifier.fillMaxWidth()
        ) {
            Text(
                text = "$number.",
                fontSize = 15.sp,
                color = numberColor,
                modifier = Modifier.width(28.dp)
            )
            Text(
                text = word,
                fontSize = 17.sp,
                fontWeight = FontWeight.SemiBold,
                color = wordColor,
                fontFamily = FontFamily.Monospace
            )
        }
    }
}

@Composable
private fun AnimatedWordItem(
    number: Int,
    word: String,
    isDarkTheme: Boolean,
    visible: Boolean,
    delay: Int,
    modifier: Modifier = Modifier
) {
    AnimatedVisibility(
        visible = visible,
        enter = fadeIn(tween(400, delayMillis = delay))
    ) {
        WordItem(
            number = number,
            word = word,
            isDarkTheme = isDarkTheme,
            modifier = modifier
        )
    }
}
