package com.rosetta.messenger.ui.settings

import androidx.activity.compose.BackHandler
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.statusBars
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.material.icons.Icons
import compose.icons.TablerIcons
import compose.icons.tablericons.*
import androidx.compose.material.icons.filled.ContentCopy
import androidx.compose.material.icons.filled.Visibility
import androidx.compose.material.icons.filled.VisibilityOff
import androidx.compose.material.icons.filled.Warning
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import kotlinx.coroutines.launch
import com.airbnb.lottie.compose.*

@Composable
fun BackupScreen(
    isDarkTheme: Boolean,
    onBack: () -> Unit,
    onVerifyPassword: suspend (String) -> String? // Returns seed phrase if password is correct
) {
    val backgroundColor = if (isDarkTheme) Color(0xFF1A1A1A) else Color(0xFFFFFFFF)
    val surfaceColor = if (isDarkTheme) Color(0xFF2C2C2E) else Color(0xFFF2F2F7)
    val textColor = if (isDarkTheme) Color.White else Color.Black
    val secondaryTextColor = if (isDarkTheme) Color(0xFF8E8E93) else Color(0xFF666666)

    val scope = rememberCoroutineScope()
    var password by remember { mutableStateOf("") }
    var seedPhrase by remember { mutableStateOf<String?>(null) }
    var passwordVisible by remember { mutableStateOf(false) }
    
    // Handle back gesture
    BackHandler { onBack() }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(backgroundColor)
            .windowInsetsPadding(WindowInsets.statusBars)
    ) {
        // Telegram-style Header
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 4.dp, vertical = 12.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            IconButton(onClick = onBack) {
                Icon(
                    imageVector = TablerIcons.ChevronLeft,
                    contentDescription = "Back",
                    tint = textColor
                )
            }
            Text(
                text = "Backup",
                fontSize = 20.sp,
                fontWeight = FontWeight.SemiBold,
                color = textColor,
                modifier = Modifier.padding(start = 8.dp)
            )
        }

        // Content
        Column(
            modifier = Modifier
                .fillMaxSize()
                .verticalScroll(rememberScrollState())
                .padding(16.dp)
        ) {
            // Warning Card
            Surface(
                modifier = Modifier.fillMaxWidth(),
                color = surfaceColor,
                shape = RoundedCornerShape(10.dp)
            ) {
                Column(
                    modifier = Modifier.padding(16.dp),
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    val composition by rememberLottieComposition(LottieCompositionSpec.Asset("lottie/shush.json"))
                    val progress by animateLottieCompositionAsState(
                        composition = composition,
                        iterations = 1
                    )
                    LottieAnimation(
                        composition = composition,
                        progress = { progress },
                        modifier = Modifier.size(80.dp)
                    )
                    Spacer(modifier = Modifier.height(12.dp))
                    Text(
                        text = "If you want to give your recovery phrase to someone, please stop! This may lead to the compromise of your conversations.",
                        fontSize = 14.sp,
                        color = secondaryTextColor,
                        lineHeight = 20.sp,
                        modifier = Modifier.fillMaxWidth()
                    )
                }
            }

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

            if (seedPhrase == null) {
                // Password Input Section
                Surface(
                    modifier = Modifier.fillMaxWidth(),
                    color = surfaceColor,
                    shape = RoundedCornerShape(10.dp)
                ) {
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(horizontal = 16.dp, vertical = 12.dp),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        BasicTextField(
                            value = password,
                            onValueChange = { newValue ->
                                password = newValue
                                // Try to verify password
                                scope.launch {
                                    val result = onVerifyPassword(newValue)
                                    if (result != null) {
                                        seedPhrase = result
                                    }
                                }
                            },
                            modifier = Modifier.weight(1f),
                            textStyle = TextStyle(
                                color = textColor,
                                fontSize = 15.sp
                            ),
                            cursorBrush = SolidColor(textColor),
                            visualTransformation = if (passwordVisible) 
                                VisualTransformation.None 
                            else 
                                PasswordVisualTransformation(),
                            singleLine = true,
                            decorationBox = { innerTextField ->
                                Box(modifier = Modifier.fillMaxWidth()) {
                                    if (password.isEmpty()) {
                                        Text(
                                            text = "Enter your password",
                                            color = secondaryTextColor,
                                            fontSize = 15.sp
                                        )
                                    }
                                    innerTextField()
                                }
                            }
                        )
                        
                        IconButton(
                            onClick = { passwordVisible = !passwordVisible },
                            modifier = Modifier.size(40.dp)
                        ) {
                            Icon(
                                imageVector = if (passwordVisible) 
                                    Icons.Filled.Visibility 
                                else 
                                    Icons.Filled.VisibilityOff,
                                contentDescription = if (passwordVisible) "Hide password" else "Show password",
                                tint = secondaryTextColor,
                                modifier = Modifier.size(20.dp)
                            )
                        }
                    }
                }

                Text(
                    text = "To view your recovery phrase, enter the password you specified when creating your account or restoring from a seed phrase.",
                    fontSize = 14.sp,
                    color = secondaryTextColor,
                    modifier = Modifier.padding(top = 8.dp),
                    lineHeight = 20.sp
                )
            } else {
                // Seed Phrase Display with colored words
                Spacer(modifier = Modifier.height(8.dp))
                
                val words = seedPhrase!!.split(" ")
                
                // Two column layout like in SeedPhraseScreen
                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) {
                            if (i < words.size) {
                                WordItem(
                                    number = i + 1,
                                    word = words[i],
                                    isDarkTheme = isDarkTheme
                                )
                            }
                        }
                    }
                    
                    // Right column (words 7-12)
                    Column(
                        modifier = Modifier.weight(1f),
                        verticalArrangement = Arrangement.spacedBy(12.dp)
                    ) {
                        for (i in 6..11) {
                            if (i < words.size) {
                                WordItem(
                                    number = i + 1,
                                    word = words[i],
                                    isDarkTheme = isDarkTheme
                                )
                            }
                        }
                    }
                }

                Spacer(modifier = Modifier.height(16.dp))
                
                // Copy button
                val context = androidx.compose.ui.platform.LocalContext.current
                Button(
                    onClick = {
                        val clipboard = context.getSystemService(android.content.Context.CLIPBOARD_SERVICE) as android.content.ClipboardManager
                        val clip = android.content.ClipData.newPlainText("Seed Phrase", seedPhrase)
                        clipboard.setPrimaryClip(clip)
                        kotlinx.coroutines.MainScope().launch {
                            kotlinx.coroutines.delay(30_000)
                            clipboard.setPrimaryClip(android.content.ClipData.newPlainText("", ""))
                        }
                    },
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(52.dp),
                    colors = ButtonDefaults.buttonColors(
                        containerColor = Color(0xFF248AE6),
                        contentColor = Color.White
                    ),
                    shape = RoundedCornerShape(10.dp)
                ) {
                    Icon(
                        imageVector = Icons.Filled.ContentCopy,
                        contentDescription = null,
                        modifier = Modifier.size(20.dp)
                    )
                    Spacer(modifier = Modifier.width(8.dp))
                    Text(
                        text = "Copy Seed Phrase",
                        fontSize = 15.sp,
                        fontWeight = FontWeight.Medium,
                        color = Color.White
                    )
                }

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

                Text(
                    text = "Please don't share your seed phrase! The administration will never ask you for it.",
                    fontSize = 14.sp,
                    color = secondaryTextColor,
                    modifier = Modifier.padding(top = 8.dp),
                    lineHeight = 20.sp
                )


            }
        }
    }
}

@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 = androidx.compose.ui.text.font.FontFamily.Monospace
            )
        }
    }
}
