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.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
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.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.rosetta.messenger.database.RosettaDatabase
import com.rosetta.messenger.repository.AvatarRepository
import com.rosetta.messenger.ui.components.AvatarImage
import com.rosetta.messenger.ui.onboarding.PrimaryBlue

data class AccountInfo(
    val id: String,
    val name: String,
    val username: String,
    val initials: String,
    val publicKey: String
)

// Avatar colors matching React Native app (Mantine inspired)
// Using primary colors (same as text colors from light theme for consistency)
private val accountColors = listOf(
    Color(0xFF1971c2), // blue
    Color(0xFF0c8599), // cyan
    Color(0xFF9c36b5), // grape
    Color(0xFF2f9e44), // green
    Color(0xFF4263eb), // indigo
    Color(0xFF5c940d), // lime
    Color(0xFFd9480f), // orange
    Color(0xFFc2255c), // pink
    Color(0xFFe03131), // red
    Color(0xFF099268), // teal
    Color(0xFF6741d9)  // violet
)

fun getAccountColor(name: String): Color {
    val index = name.hashCode().mod(accountColors.size).let { if (it < 0) it + accountColors.size else it }
    return accountColors[index]
}

@Composable
fun SelectAccountScreen(
    isDarkTheme: Boolean,
    accounts: List<AccountInfo>,
    selectedAccountId: String?,
    onSelectAccount: (String) -> Unit,
    onAddAccount: () -> Unit,
    showCreateModal: Boolean,
    onCreateNew: () -> Unit,
    onImportSeed: () -> Unit,
    onDismissModal: () -> 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 searchBarColor = if (isDarkTheme) Color(0xFF2A2A2A) else Color(0xFFF5F5F5)
    
    var searchQuery by remember { mutableStateOf("") }
    var visible by remember { mutableStateOf(false) }
    
    // Фильтрация аккаунтов по поиску
    val filteredAccounts = remember(accounts, searchQuery) {
        if (searchQuery.isEmpty()) {
            accounts
        } else {
            accounts.filter { account ->
                account.name.contains(searchQuery, ignoreCase = true) ||
                account.publicKey.contains(searchQuery, ignoreCase = true)
            }
        }
    }
    
    LaunchedEffect(Unit) {
        visible = true
    }

    // Status bar icons: black on light theme, white on dark
    val view = androidx.compose.ui.platform.LocalView.current
    DisposableEffect(isDarkTheme) {
        val window = (view.context as android.app.Activity).window
        val insetsController = androidx.core.view.WindowCompat.getInsetsController(window, view)
        insetsController.isAppearanceLightStatusBars = false
        onDispose { }
    }
    
    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(backgroundColor)
            .statusBarsPadding()
    ) {
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(horizontal = 24.dp)
        ) {
            Spacer(modifier = Modifier.height(40.dp))
            
            // Header
            AnimatedVisibility(
                visible = visible,
                enter = fadeIn(tween(300))
            ) {
                Column {
                    Row {
                        Text(
                            text = "Select ",
                            fontSize = 32.sp,
                            fontWeight = FontWeight.Bold,
                            color = PrimaryBlue
                        )
                        Text(
                            text = "account",
                            fontSize = 32.sp,
                            fontWeight = FontWeight.Bold,
                            color = textColor
                        )
                    }
                    
                    Spacer(modifier = Modifier.height(8.dp))
                    
                    Text(
                        text = "Choose account to login",
                        fontSize = 15.sp,
                        color = secondaryTextColor,
                        lineHeight = 22.sp
                    )
                }
            }
            
            Spacer(modifier = Modifier.height(24.dp))
            
            // Search bar
            AnimatedVisibility(
                visible = visible,
                enter = fadeIn(tween(500, delayMillis = 150)) + expandVertically(
                    animationSpec = tween(500, delayMillis = 150)
                )
            ) {
                OutlinedTextField(
                    value = searchQuery,
                    onValueChange = { searchQuery = it },
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(56.dp),
                    placeholder = {
                        Text(
                            text = "Search accounts...",
                            color = secondaryTextColor
                        )
                    },
                    leadingIcon = {
                        Icon(
                            Icons.Default.Search,
                            contentDescription = "Search",
                            tint = secondaryTextColor
                        )
                    },
                    trailingIcon = {
                        if (searchQuery.isNotEmpty()) {
                            IconButton(onClick = { searchQuery = "" }) {
                                Icon(
                                    Icons.Default.Clear,
                                    contentDescription = "Clear",
                                    tint = secondaryTextColor
                                )
                            }
                        }
                    },
                    colors = OutlinedTextFieldDefaults.colors(
                        unfocusedContainerColor = searchBarColor,
                        focusedContainerColor = searchBarColor,
                        unfocusedBorderColor = Color.Transparent,
                        focusedBorderColor = PrimaryBlue,
                        cursorColor = PrimaryBlue,
                        focusedTextColor = textColor,
                        unfocusedTextColor = textColor
                    ),
                    shape = RoundedCornerShape(12.dp),
                    singleLine = true
                )
            }
            
            Spacer(modifier = Modifier.height(16.dp))
            
            // Accounts list
            AnimatedVisibility(
                visible = visible,
                enter = fadeIn(tween(500, delayMillis = 200))
            ) {
                LazyColumn(
                    verticalArrangement = Arrangement.spacedBy(12.dp),
                    modifier = Modifier.fillMaxWidth()
                ) {
                    items(filteredAccounts, key = { it.id }) { account ->
                        val index = filteredAccounts.indexOf(account)
                        AccountListItem(
                            account = account,
                            isSelected = account.id == selectedAccountId,
                            isDarkTheme = isDarkTheme,
                            onClick = { onSelectAccount(account.id) },
                            animationDelay = 250 + (index * 50)
                        )
                    }
                    
                    // Empty state
                    if (filteredAccounts.isEmpty() && searchQuery.isNotEmpty()) {
                        item {
                            EmptySearchResult(
                                isDarkTheme = isDarkTheme,
                                searchQuery = searchQuery
                            )
                        }
                    }
                    
                    // Add Account button
                    item {
                        Spacer(modifier = Modifier.height(8.dp))
                        AddAccountButton(
                            isDarkTheme = isDarkTheme,
                            onClick = onAddAccount,
                            animationDelay = 250 + (filteredAccounts.size * 50)
                        )
                        Spacer(modifier = Modifier.height(24.dp))
                    }
                }
            }
        }
        
        // Create Account Modal
        AnimatedVisibility(
            visible = showCreateModal,
            enter = fadeIn(animationSpec = tween(200)),
            exit = fadeOut(animationSpec = tween(150))
        ) {
            CreateAccountModal(
                isDarkTheme = isDarkTheme,
                onCreateNew = onCreateNew,
                onImportSeed = onImportSeed,
                onDismiss = onDismissModal
            )
        }
    }
}

@Composable
private fun AccountListItem(
    account: AccountInfo,
    isSelected: Boolean,
    isDarkTheme: Boolean,
    onClick: () -> Unit,
    animationDelay: Int
) {
    val surfaceColor = if (isDarkTheme) Color(0xFF2A2A2A) else Color(0xFFF5F5F5)
    val textColor = if (isDarkTheme) Color.White else Color.Black
    val secondaryTextColor = if (isDarkTheme) Color(0xFF8E8E93) else Color(0xFF666666)
    
    val avatarColor = getAccountColor(account.name)
    
    val context = LocalContext.current
    val avatarRepository = remember(account.publicKey) {
        val database = RosettaDatabase.getDatabase(context)
        AvatarRepository(context, database.avatarDao(), account.publicKey)
    }
    
    var visible by remember { mutableStateOf(false) }
    
    LaunchedEffect(Unit) {
        kotlinx.coroutines.delay(animationDelay.toLong())
        visible = true
    }
    
    AnimatedVisibility(
        visible = visible,
        enter = fadeIn(tween(300))
    ) {
        Card(
            modifier = Modifier
                .fillMaxWidth()
                .height(80.dp)
                .clip(RoundedCornerShape(16.dp))
                .clickable(onClick = onClick),
            shape = RoundedCornerShape(16.dp),
            colors = CardDefaults.cardColors(
                containerColor = if (isSelected) PrimaryBlue.copy(alpha = 0.1f) else surfaceColor
            ),
            border = if (isSelected) BorderStroke(2.dp, PrimaryBlue) else null
        ) {
            Row(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(16.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                // Avatar
                AvatarImage(
                    publicKey = account.publicKey,
                    avatarRepository = avatarRepository,
                    size = 48.dp,
                    isDarkTheme = isDarkTheme
                )
                
                Spacer(modifier = Modifier.width(16.dp))
                
                // Account info
                Column(
                    modifier = Modifier.weight(1f)
                ) {
                    Text(
                        text = account.name,
                        fontSize = 16.sp,
                        fontWeight = FontWeight.Medium,
                        color = if (isSelected) PrimaryBlue else textColor,
                        maxLines = 1,
                        overflow = TextOverflow.Ellipsis
                    )
                    Spacer(modifier = Modifier.height(4.dp))
                    Text(
                        text = if (account.username.isNotEmpty()) "@${account.username}" else "${account.publicKey.take(8)}...${account.publicKey.takeLast(6)}",
                        fontSize = 13.sp,
                        color = secondaryTextColor,
                        maxLines = 1,
                        overflow = TextOverflow.Ellipsis
                    )
                }
                
                // Selected indicator
                if (isSelected) {
                    Box(
                        modifier = Modifier
                            .size(28.dp)
                            .clip(CircleShape)
                            .background(PrimaryBlue),
                        contentAlignment = Alignment.Center
                    ) {
                        Icon(
                            Icons.Default.Check,
                            contentDescription = "Selected",
                            tint = Color.White,
                            modifier = Modifier.size(16.dp)
                        )
                    }
                } else {
                    Icon(
                        Icons.Default.ArrowForward,
                        contentDescription = "Select",
                        tint = secondaryTextColor,
                        modifier = Modifier.size(24.dp)
                    )
                }
            }
        }
    }
}

@Composable
private fun AddAccountButton(
    isDarkTheme: Boolean,
    onClick: () -> Unit,
    animationDelay: Int
) {
    val surfaceColor = if (isDarkTheme) Color(0xFF2A2A2A) else Color(0xFFF5F5F5)
    
    var visible by remember { mutableStateOf(false) }
    
    LaunchedEffect(Unit) {
        kotlinx.coroutines.delay(animationDelay.toLong())
        visible = true
    }
    
    AnimatedVisibility(
        visible = visible,
        enter = fadeIn(tween(300))
    ) {
        Card(
            modifier = Modifier
                .fillMaxWidth()
                .height(64.dp)
                .clip(RoundedCornerShape(16.dp))
                .clickable(onClick = onClick),
            shape = RoundedCornerShape(16.dp),
            colors = CardDefaults.cardColors(containerColor = surfaceColor),
            border = BorderStroke(2.dp, PrimaryBlue)
        ) {
            Row(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(horizontal = 20.dp),
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.Center
            ) {
                Icon(
                    Icons.Default.Add,
                    contentDescription = null,
                    tint = PrimaryBlue,
                    modifier = Modifier.size(24.dp)
                )
                Spacer(modifier = Modifier.width(12.dp))
                Text(
                    text = "Add New Account",
                    fontSize = 16.sp,
                    fontWeight = FontWeight.Medium,
                    color = PrimaryBlue
                )
            }
        }
    }
}

@Composable
private fun EmptySearchResult(
    isDarkTheme: Boolean,
    searchQuery: String
) {
    val textColor = if (isDarkTheme) Color.White else Color.Black
    val secondaryTextColor = if (isDarkTheme) Color(0xFF8E8E93) else Color(0xFF666666)
    
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 40.dp),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Icon(
            Icons.Default.Search,
            contentDescription = null,
            tint = secondaryTextColor,
            modifier = Modifier.size(64.dp)
        )
        Spacer(modifier = Modifier.height(16.dp))
        Text(
            text = "No accounts found",
            fontSize = 18.sp,
            fontWeight = FontWeight.Medium,
            color = textColor
        )
        Spacer(modifier = Modifier.height(8.dp))
        Text(
            text = "No results for \"$searchQuery\"",
            fontSize = 14.sp,
            color = secondaryTextColor,
            textAlign = TextAlign.Center
        )
    }
}

@Composable
private fun CreateAccountModal(
    isDarkTheme: Boolean,
    onCreateNew: () -> Unit,
    onImportSeed: () -> Unit,
    onDismiss: () -> Unit
) {
    val backgroundColor = if (isDarkTheme) Color(0xFF2A2A2A) else Color(0xFFFFFFFF)
    val textColor = if (isDarkTheme) Color.White else Color.Black
    val secondaryTextColor = if (isDarkTheme) Color(0xFF8E8E93) else Color(0xFF666666)

    // Анимация карточки: scale + fade с пружинным эффектом
    val cardScale by animateFloatAsState(
        targetValue = 1f,
        animationSpec = spring(
            dampingRatio = Spring.DampingRatioMediumBouncy,
            stiffness = Spring.StiffnessMediumLow
        ),
        label = "cardScale"
    )

    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(Color.Black.copy(alpha = 0.5f))
            .clickable(onClick = onDismiss),
        contentAlignment = Alignment.Center
    ) {
        Card(
            modifier = Modifier
                .padding(32.dp)
                .graphicsLayer {
                    scaleX = cardScale
                    scaleY = cardScale
                }
                .clickable(enabled = false, onClick = {}),
            shape = RoundedCornerShape(20.dp),
            colors = CardDefaults.cardColors(containerColor = backgroundColor)
        ) {
            Column(
                modifier = Modifier.padding(24.dp),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                Text(
                    text = "Create account",
                    fontSize = 20.sp,
                    fontWeight = FontWeight.Bold,
                    color = textColor
                )
                
                Spacer(modifier = Modifier.height(8.dp))
                
                Text(
                    text = "You may be create new account\nor import existing",
                    fontSize = 15.sp,
                    color = secondaryTextColor,
                    textAlign = TextAlign.Center
                )
                
                Spacer(modifier = Modifier.height(24.dp))
                
                // Create New button
                Button(
                    onClick = onCreateNew,
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(50.dp),
                    colors = ButtonDefaults.buttonColors(
                        containerColor = PrimaryBlue,
                        contentColor = Color.White
                    ),
                    shape = RoundedCornerShape(12.dp)
                ) {
                    Text(
                        text = "Create new",
                        fontSize = 16.sp,
                        fontWeight = FontWeight.Medium
                    )
                }
                
                Spacer(modifier = Modifier.height(12.dp))
                
                // Import (Recover) button
                OutlinedButton(
                    onClick = onImportSeed,
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(50.dp),
                    colors = ButtonDefaults.outlinedButtonColors(
                        contentColor = PrimaryBlue
                    ),
                    border = BorderStroke(1.dp, PrimaryBlue),
                    shape = RoundedCornerShape(12.dp)
                ) {
                    Text(
                        text = "Recover",
                        fontSize = 16.sp,
                        fontWeight = FontWeight.Medium
                    )
                }
            }
        }
    }
}
