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.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.LocalClipboardManager
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.crypto.CryptoManager
import com.rosetta.messenger.ui.onboarding.PrimaryBlue

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ImportSeedPhraseScreen(
    isDarkTheme: Boolean,
    onBack: () -> Unit,
    onSeedPhraseImported: (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 clipboardManager = LocalClipboardManager.current
    var words by remember { mutableStateOf(List(12) { "" }) }
    var error by remember { mutableStateOf<String?>(null) }
    var visible by remember { mutableStateOf(false) }
    
    LaunchedEffect(Unit) {
        visible = true
    }
    
    val allWordsFilled = words.all { it.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 = "Import Account",
                        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 your 12-word recovery phrase\nto restore your account.",
                        fontSize = 15.sp,
                        color = secondaryTextColor,
                        textAlign = TextAlign.Center,
                        lineHeight = 22.sp
                    )
                }
                
                Spacer(modifier = Modifier.height(24.dp))
                
                // Paste button - directly reads from clipboard
                AnimatedVisibility(
                    visible = visible,
                    enter = fadeIn(tween(500, delayMillis = 150)) + scaleIn(
                        initialScale = 0.9f,
                        animationSpec = tween(500, delayMillis = 150)
                    )
                ) {
                    TextButton(
                        onClick = {
                            val clipboardText = clipboardManager.getText()?.text
                            if (clipboardText != null && clipboardText.isNotBlank()) {
                                val parsed = clipboardText.trim().lowercase()
                                    .split(Regex("[\\s,;]+"))
                                    .filter { it.isNotBlank() }
                                    .map { it.trim() }
                                
                                when {
                                    parsed.size == 12 -> {
                                        words = parsed.toList()
                                        error = null
                                    }
                                    parsed.size > 12 -> {
                                        words = parsed.take(12).toList()
                                        error = null
                                    }
                                    parsed.isNotEmpty() -> {
                                        error = "Clipboard contains ${parsed.size} words, need 12"
                                    }
                                    else -> {
                                        error = "No valid words found in clipboard"
                                    }
                                }
                            } else {
                                error = "Clipboard is empty"
                            }
                        }
                    ) {
                        Icon(
                            Icons.Default.ContentPaste,
                            contentDescription = null,
                            tint = PrimaryBlue,
                            modifier = Modifier.size(20.dp)
                        )
                        Spacer(modifier = Modifier.width(8.dp))
                        Text(
                            "Paste all 12 words",
                            color = PrimaryBlue,
                            fontSize = 15.sp
                        )
                    }
                }
                
                Spacer(modifier = Modifier.height(20.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) {
                                AnimatedWordInputItem(
                                    number = i + 1,
                                    value = words[i],
                                    onValueChange = { newValue ->
                                        words = words.toMutableList().apply {
                                            this[i] = newValue.lowercase().trim()
                                        }
                                        error = 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) {
                                AnimatedWordInputItem(
                                    number = i + 1,
                                    value = words[i],
                                    onValueChange = { newValue ->
                                        words = words.toMutableList().apply {
                                            this[i] = newValue.lowercase().trim()
                                        }
                                        error = null
                                    },
                                    isDarkTheme = isDarkTheme,
                                    visible = visible,
                                    delay = 250 + (i * 50)
                                )
                            }
                        }
                    }
                }
                
                // Error
                AnimatedVisibility(
                    visible = error != null,
                    enter = fadeIn(tween(300)) + scaleIn(initialScale = 0.9f),
                    exit = fadeOut(tween(200))
                ) {
                    Column {
                        Spacer(modifier = Modifier.height(16.dp))
                        Text(
                            text = error ?: "",
                            fontSize = 14.sp,
                            color = Color(0xFFE53935),
                            textAlign = TextAlign.Center
                        )
                    }
                }
                
                Spacer(modifier = Modifier.height(24.dp))

                // Import button
                AnimatedVisibility(
                    visible = visible,
                    enter = fadeIn(tween(400, delayMillis = 600))
                ) {
                    Button(
                        onClick = {
                            val seedPhrase = words.map { it.trim() }
                            
                            if (seedPhrase.any { it.isBlank() }) {
                                error = "Please fill in all words"
                                return@Button
                            }
                            
                            if (!CryptoManager.validateSeedPhrase(seedPhrase)) {
                                error = "Invalid recovery phrase"
                                return@Button
                            }
                            
                            onSeedPhraseImported(seedPhrase)
                        },
                        enabled = allWordsFilled,
                        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 AnimatedWordInputItem(
    number: Int,
    value: String,
    onValueChange: (String) -> Unit,
    isDarkTheme: Boolean,
    visible: Boolean,
    delay: Int,
    modifier: Modifier = Modifier
) {
    AnimatedVisibility(
        visible = visible,
        enter = fadeIn(tween(400, delayMillis = delay))
    ) {
        WordInputItem(
            number = number,
            value = value,
            onValueChange = onValueChange,
            isDarkTheme = isDarkTheme,
            modifier = modifier
        )
    }
}

@Composable
private fun WordInputItem(
    number: Int,
    value: String,
    onValueChange: (String) -> Unit,
    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)
    
    var isFocused by remember { mutableStateOf(false) }
    
    // Beautiful solid colors that fit the theme - same as SeedPhraseScreen
    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]
    
    Box(
        modifier = modifier
            .fillMaxWidth()
            .clip(RoundedCornerShape(12.dp))
            .border(
                width = if (isFocused) 2.dp else 0.dp,
                color = if (isFocused) PrimaryBlue else Color.Transparent,
                shape = 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)
            )
            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(
                                "word",
                                fontSize = 17.sp,
                                color = hintColor,
                                fontFamily = FontFamily.Monospace,
                                fontWeight = FontWeight.SemiBold
                            )
                        }
                        innerTextField()
                    }
                }
            )
        }
    }
}
