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 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.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)
    
    var seedPhrase by remember { mutableStateOf<List<String>>(emptyList()) }
    var hasCopied by remember { mutableStateOf(false) }
    var visible by remember { mutableStateOf(false) }
    val scope = rememberCoroutineScope()
    val clipboardManager = LocalClipboardManager.current
    
    LaunchedEffect(Unit) {
        // Генерируем фразу сразу, без задержек
        seedPhrase = CryptoManager.generateSeedPhrase()
        // Даем микро-паузу, чтобы верстка отрисовалась, и запускаем анимацию
        delay(50) 
        visible = true
    }
    
    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(backgroundColor)
            .statusBarsPadding()
            .navigationBarsPadding()
    ) {
        Column(modifier = Modifier.fillMaxSize()) {
            // Top bar
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(4.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                IconButton(onClick = onBack) {
                    Icon(TablerIcons.ChevronLeft, "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))
                
                // Сетка со словами (без Crossfade и лоадера)
                if (seedPhrase.isNotEmpty()) {
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.spacedBy(12.dp)
                    ) {
                        // Левая колонка (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 = i * 60
                                )
                            }
                        }
                        
                        // Правая колонка (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 = i * 60
                                )
                            }
                        }
                    }
                }
                
                Spacer(modifier = Modifier.height(24.dp))
                
                // Кнопка Copy
                AnimatedVisibility(
                    visible = visible,
                    enter = fadeIn(tween(400, delayMillis = 800)) + scaleIn(
                        initialScale = 0.8f,
                        animationSpec = tween(400, delayMillis = 800, easing = LinearOutSlowInEasing)
                    )
                ) {
                    TextButton(
                        onClick = {
                            clipboardManager.setText(AnnotatedString(seedPhrase.joinToString(" ")))
                            hasCopied = true
                            scope.launch {
                                delay(2000)
                                hasCopied = false
                            }
                            scope.launch {
                                delay(30_000)
                                clipboardManager.setText(AnnotatedString(""))
                            }
                        }
                    ) {
                        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
                AnimatedVisibility(
                    visible = visible,
                    enter = fadeIn(tween(400, delayMillis = 900)) + slideInVertically(
                        initialOffsetY = { 20 },
                        animationSpec = tween(400, delayMillis = 900)
                    )
                ) {
                    Button(
                        onClick = { onConfirm(seedPhrase) },
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(52.dp),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = PrimaryBlue,
                            contentColor = Color.White
                        ),
                        shape = RoundedCornerShape(14.dp)
                    ) {
                        Text(
                            text = "I Saved It",
                            fontSize = 17.sp,
                            fontWeight = FontWeight.SemiBold
                        )
                    }
                }
                
                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)
    val wordColors = listOf(
        Color(0xFF5E9FFF), Color(0xFFFF7EB3), Color(0xFF7B68EE), 
        Color(0xFF50C878), Color(0xFFFF6B6B), Color(0xFF4ECDC4), 
        Color(0xFFFFB347), Color(0xFFBA55D3), Color(0xFF87CEEB), 
        Color(0xFFDDA0DD), Color(0xFF98D8C8), Color(0xFFF7DC6F)
    )
    
    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 = 14.dp, vertical = 12.dp)
    ) {
        Row(verticalAlignment = Alignment.CenterVertically) {
            Text(
                text = "$number.",
                fontSize = 13.sp,
                color = numberColor,
                modifier = Modifier.width(26.dp)
            )
            Text(
                text = word,
                fontSize = 16.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
) {
    val overshootEasing = remember { CubicBezierEasing(0.175f, 0.885f, 0.32f, 1.275f) }

    AnimatedVisibility(
        visible = visible,
        enter = fadeIn(animationSpec = tween(300, delayMillis = delay)) + 
                slideInVertically(
                    initialOffsetY = { 30 }, 
                    animationSpec = tween(400, delayMillis = delay, easing = FastOutSlowInEasing)
                ) + 
                scaleIn(
                    initialScale = 0.85f, 
                    animationSpec = tween(400, delayMillis = delay, easing = overshootEasing)
                ),
        modifier = modifier
    ) {
        WordItem(number, word, isDarkTheme)
    }
}