package com.rosetta.messenger.ui.auth

import android.content.ClipboardManager
import android.content.Context
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.foundation.text.BasicTextField
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.focus.onFocusChanged
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.TextStyle
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 com.rosetta.messenger.ui.onboarding.PrimaryBlue

// Beautiful solid colors that fit the theme
private 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
)

@Composable
fun ConfirmSeedPhraseScreen(
    seedPhrase: List<String>,
    isDarkTheme: Boolean,
    onBack: () -> Unit,
    onConfirmed: () -> 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 context = LocalContext.current
    
    // Select 4 words at fixed positions to confirm (2, 5, 9, 12)
    val wordsToConfirm = remember {
        listOf(1, 4, 8, 11).map { index -> index to seedPhrase[index] }
    }
    
    var userInputs by remember { mutableStateOf(List(12) { "" }) }
    var showError by remember { mutableStateOf(false) }
    var visible by remember { mutableStateOf(false) }
    var showPasteSuccess by remember { mutableStateOf(false) }
    
    // Function to handle paste from clipboard
    val handlePaste: () -> Unit = {
        try {
            val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
            val clipData = clipboard.primaryClip
            if (clipData != null && clipData.itemCount > 0) {
                val pastedText = clipData.getItemAt(0).text?.toString() ?: ""
                
                // Split by spaces, commas, or newlines and filter empty strings
                val pastedWords = pastedText
                    .split(Regex("\\s+|,|\\n"))
                    .map { it.trim().lowercase() }
                    .filter { it.isNotEmpty() }
                
                if (pastedWords.size >= 12) {
                    // Fill all 12 words
                    userInputs = pastedWords.take(12)
                    showPasteSuccess = true
                    showError = false
                } else if (pastedWords.isNotEmpty()) {
                    // Fill only the required input fields with available words
                    val newInputs = userInputs.toMutableList()
                    var pasteIndex = 0
                    
                    wordsToConfirm.forEach { (index, _) ->
                        if (pasteIndex < pastedWords.size) {
                            newInputs[index] = pastedWords[pasteIndex]
                            pasteIndex++
                        }
                    }
                    
                    userInputs = newInputs
                    showPasteSuccess = pasteIndex > 0
                    showError = false
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
    
    // Hide success message after delay
    LaunchedEffect(showPasteSuccess) {
        if (showPasteSuccess) {
            kotlinx.coroutines.delay(2000)
            showPasteSuccess = false
        }
    }
    
    LaunchedEffect(Unit) {
        visible = true
    }
    
    // Check if the 4 confirmation words are correct
    val allCorrect = wordsToConfirm.all { (index, word) ->
        userInputs[index].trim().lowercase() == word.lowercase()
    }
    
    // Check if all 4 words have input
    val allFilled = wordsToConfirm.all { (index, _) ->
        userInputs[index].isNotBlank()
    }
    
    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()
                    .imePadding()
                    .padding(horizontal = 24.dp)
                    .verticalScroll(rememberScrollState()),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                Spacer(modifier = Modifier.height(16.dp))
                
                AnimatedVisibility(
                    visible = visible,
                    enter = fadeIn(tween(300))
                ) {
                    Text(
                        text = "Confirm Backup",
                        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 = "Enter words #${wordsToConfirm[0].first + 1}, #${wordsToConfirm[1].first + 1}, #${wordsToConfirm[2].first + 1}, #${wordsToConfirm[3].first + 1}\nto confirm you've backed up your phrase.",
                        fontSize = 15.sp,
                        color = secondaryTextColor,
                        textAlign = TextAlign.Center,
                        lineHeight = 22.sp
                    )
                }
                
                // Paste success message
                AnimatedVisibility(
                    visible = showPasteSuccess,
                    enter = fadeIn(tween(300)) + scaleIn(initialScale = 0.9f),
                    exit = fadeOut(tween(300))
                ) {
                    Column(
                        modifier = Modifier.padding(top = 16.dp, bottom = 0.dp)
                    ) {
                        Card(
                            colors = CardDefaults.cardColors(
                                containerColor = Color(0xFF4CAF50).copy(alpha = 0.15f)
                            ),
                            shape = RoundedCornerShape(8.dp)
                        ) {
                            Row(
                                modifier = Modifier.padding(12.dp),
                                verticalAlignment = Alignment.CenterVertically
                            ) {
                                Icon(
                                    Icons.Default.CheckCircle,
                                    contentDescription = null,
                                    tint = Color(0xFF4CAF50),
                                    modifier = Modifier.size(20.dp)
                                )
                                Spacer(modifier = Modifier.width(8.dp))
                                Text(
                                    text = "Words pasted successfully!",
                                    fontSize = 14.sp,
                                    color = Color(0xFF4CAF50),
                                    fontWeight = FontWeight.Medium
                                )
                            }
                        }
                    }
                }
                
                Spacer(modifier = Modifier.height(24.dp))
                
                // Two column layout like SeedPhraseScreen
                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) {
                                val needsInput = wordsToConfirm.any { it.first == i }
                                val correctWord = seedPhrase[i]
                                
                                AnimatedConfirmWordItem(
                                    number = i + 1,
                                    displayWord = if (needsInput) "" else correctWord,
                                    inputValue = if (needsInput) userInputs[i] else "",
                                    isInput = needsInput,
                                    onValueChange = { newValue ->
                                        userInputs = userInputs.toMutableList().apply {
                                            this[i] = newValue.lowercase().trim()
                                        }
                                        showError = false
                                    },
                                    isCorrect = if (needsInput && userInputs[i].isNotBlank()) {
                                        userInputs[i].trim().lowercase() == correctWord.lowercase()
                                    } else null,
                                    isDarkTheme = isDarkTheme,
                                    visible = visible,
                                    delay = 250 + (i * 50)
                                )
                            }
                        }
                        
                        // Right column (words 7-12)
                        Column(
                            modifier = Modifier.weight(1f),
                            verticalArrangement = Arrangement.spacedBy(12.dp)
                        ) {
                            for (i in 6..11) {
                                val needsInput = wordsToConfirm.any { it.first == i }
                                val correctWord = seedPhrase[i]
                                
                                AnimatedConfirmWordItem(
                                    number = i + 1,
                                    displayWord = if (needsInput) "" else correctWord,
                                    inputValue = if (needsInput) userInputs[i] else "",
                                    isInput = needsInput,
                                    onValueChange = { newValue ->
                                        userInputs = userInputs.toMutableList().apply {
                                            this[i] = newValue.lowercase().trim()
                                        }
                                        showError = false
                                    },
                                    isCorrect = if (needsInput && userInputs[i].isNotBlank()) {
                                        userInputs[i].trim().lowercase() == correctWord.lowercase()
                                    } else null,
                                    isDarkTheme = isDarkTheme,
                                    visible = visible,
                                    delay = 250 + (i * 50)
                                )
                            }
                        }
                    }
                }
                
                Spacer(modifier = Modifier.height(20.dp))
                
                // Paste button
                AnimatedVisibility(
                    visible = visible,
                    enter = fadeIn(tween(500, delayMillis = 400))
                ) {
                    OutlinedButton(
                        onClick = handlePaste,
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(48.dp),
                        colors = ButtonDefaults.outlinedButtonColors(
                            contentColor = PrimaryBlue
                        ),
                        border = BorderStroke(1.dp, PrimaryBlue),
                        shape = RoundedCornerShape(12.dp)
                    ) {
                        Icon(
                            Icons.Default.ContentPaste,
                            contentDescription = "Paste",
                            modifier = Modifier.size(20.dp)
                        )
                        Spacer(modifier = Modifier.width(8.dp))
                        Text(
                            text = "Paste from Clipboard",
                            fontSize = 16.sp,
                            fontWeight = FontWeight.Medium
                        )
                    }
                }
                
                // Error message
                AnimatedVisibility(
                    visible = showError,
                    enter = fadeIn(tween(300)) + scaleIn(initialScale = 0.9f),
                    exit = fadeOut(tween(200))
                ) {
                    Column {
                        Spacer(modifier = Modifier.height(16.dp))
                        Text(
                            text = "Some words don't match. Please check and try again.",
                            fontSize = 14.sp,
                            color = Color(0xFFE53935),
                            textAlign = TextAlign.Center
                        )
                    }
                }
                
                Spacer(modifier = Modifier.height(16.dp))
                
                // Continue Button
                AnimatedVisibility(
                    visible = visible,
                    enter = fadeIn(tween(400, delayMillis = 600))
                ) {
                    Button(
                        onClick = {
                            if (allCorrect) {
                                onConfirmed()
                            } else {
                                showError = true
                            }
                        },
                        enabled = allFilled,
                        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 = "Confirm",
                            fontSize = 17.sp,
                            fontWeight = FontWeight.Medium
                        )
                    }
                }
                
                Spacer(modifier = Modifier.height(40.dp))
            }
        }
    }
}

@Composable
private fun AnimatedConfirmWordItem(
    number: Int,
    displayWord: String,
    inputValue: String,
    isInput: Boolean,
    onValueChange: (String) -> Unit,
    isCorrect: Boolean?,
    isDarkTheme: Boolean,
    visible: Boolean,
    delay: Int,
    modifier: Modifier = Modifier
) {
    AnimatedVisibility(
        visible = visible,
        enter = fadeIn(tween(400, delayMillis = delay))
    ) {
        if (isInput) {
            ConfirmWordInputItem(
                number = number,
                value = inputValue,
                onValueChange = onValueChange,
                isCorrect = isCorrect,
                isDarkTheme = isDarkTheme,
                modifier = modifier
            )
        } else {
            DisplayWordItem(
                number = number,
                word = displayWord,
                isDarkTheme = isDarkTheme,
                modifier = modifier
            )
        }
    }
}

@Composable
private fun DisplayWordItem(
    number: Int,
    word: String,
    isDarkTheme: Boolean,
    modifier: Modifier = Modifier
) {
    val numberColor = if (isDarkTheme) Color(0xFF888888) else Color(0xFF999999)
    val bgColor = if (isDarkTheme) Color(0xFF2A2A2A) else Color(0xFFF5F5F5)
    val wordColor = wordColors[(number - 1) % wordColors.size]
    
    Box(
        modifier = modifier
            .fillMaxWidth()
            .height(48.dp)
            .clip(RoundedCornerShape(12.dp))
            .background(bgColor)
            .padding(horizontal = 16.dp),
        contentAlignment = Alignment.CenterStart
    ) {
        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 ConfirmWordInputItem(
    number: Int,
    value: String,
    onValueChange: (String) -> Unit,
    isCorrect: Boolean?,
    isDarkTheme: Boolean,
    modifier: Modifier = Modifier
) {
    val numberColor = if (isDarkTheme) Color(0xFF888888) else Color(0xFF999999)
    val hintColor = if (isDarkTheme) Color(0xFF555555) else Color(0xFFBBBBBB)
    val bgColor = if (isDarkTheme) Color(0xFF2A2A2A) else Color(0xFFF5F5F5)
    val wordColor = wordColors[(number - 1) % wordColors.size]
    
    var isFocused by remember { mutableStateOf(false) }
    
    // Border color based on correctness
    val borderColor = when (isCorrect) {
        true -> Color(0xFF4CAF50) // Green
        false -> Color(0xFFE53935) // Red
        null -> if (isFocused) PrimaryBlue else Color.Transparent
    }
    
    Box(
        modifier = modifier
            .fillMaxWidth()
            .height(48.dp)
            .clip(RoundedCornerShape(12.dp))
            .border(
                width = 2.dp,
                color = borderColor,
                shape = RoundedCornerShape(12.dp)
            )
            .background(bgColor)
            .padding(horizontal = 16.dp),
        contentAlignment = Alignment.CenterStart
    ) {
        Row(
            verticalAlignment = Alignment.CenterVertically,
            modifier = Modifier.fillMaxWidth()
        ) {
            Text(
                text = "$number.",
                fontSize = 15.sp,
                color = numberColor,
                modifier = Modifier.width(28.dp)
            )
            BasicTextField(
                value = value,
                onValueChange = onValueChange,
                textStyle = TextStyle(
                    fontSize = 17.sp,
                    fontWeight = FontWeight.SemiBold,
                    color = if (value.isNotEmpty()) wordColor else hintColor,
                    fontFamily = FontFamily.Monospace
                ),
                singleLine = true,
                cursorBrush = SolidColor(PrimaryBlue),
                modifier = Modifier
                    .weight(1f)
                    .onFocusChanged { isFocused = it.isFocused },
                decorationBox = { innerTextField ->
                    Box {
                        if (value.isEmpty()) {
                            Text(
                                "enter word",
                                fontSize = 17.sp,
                                color = hintColor,
                                fontFamily = FontFamily.Monospace,
                                fontWeight = FontWeight.SemiBold,
                                maxLines = 1
                            )
                        }
                        innerTextField()
                    }
                }
            )
            
            // Show check/cross icon
            if (isCorrect != null) {
                Icon(
                    imageVector = if (isCorrect) Icons.Default.Check else Icons.Default.Close,
                    contentDescription = null,
                    tint = if (isCorrect) Color(0xFF4CAF50) else Color(0xFFE53935),
                    modifier = Modifier.size(20.dp)
                )
            }
        }
    }
}
