package com.rosetta.messenger.ui.chats

import androidx.compose.animation.*
import androidx.compose.animation.core.*
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Bookmark
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.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.airbnb.lottie.compose.*
import com.airbnb.lottie.LottieComposition
import com.rosetta.messenger.network.SearchUser
import com.rosetta.messenger.R
import com.rosetta.messenger.repository.AvatarRepository
import com.rosetta.messenger.ui.components.AvatarImage
import com.rosetta.messenger.ui.components.VerifiedBadge
import com.rosetta.messenger.ui.onboarding.PrimaryBlue

/**
 * Компонент отображения результатов поиска пользователей
 * Оптимизированный дизайн с минимальными анимациями для плавной работы
 */
@Composable
fun SearchResultsList(
        searchResults: List<SearchUser>,
        isSearching: Boolean,
        currentUserPublicKey: String,
        isDarkTheme: Boolean,
        preloadedComposition: LottieComposition? = null,
        avatarRepository: AvatarRepository? = null,
        onUserClick: (SearchUser) -> Unit,
        modifier: Modifier = Modifier
) {
    val textColor = if (isDarkTheme) Color.White else Color.Black
    val secondaryTextColor = if (isDarkTheme) Color(0xFF8E8E93) else Color(0xFF666666)

    Box(modifier = modifier.fillMaxSize()) {
        // Loading state - упрощенная анимация
        AnimatedVisibility(
                visible = isSearching,
                enter = fadeIn(animationSpec = snap()),
                exit = fadeOut(animationSpec = tween(100))
        ) {
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .imePadding(), // Поднимается при клавиатуре
                contentAlignment = Alignment.Center
            ) {
                Column(
                        horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    CircularProgressIndicator(
                            modifier = Modifier.size(32.dp),
                            color = PrimaryBlue,
                            strokeWidth = 2.5.dp
                    )
                    Spacer(modifier = Modifier.height(16.dp))
                    Text(
                        text = "Searching...",
                        fontSize = 14.sp,
                        color = secondaryTextColor
                    )
                }
            }
        }

        // Empty state - поднимается при открытии клавиатуры
        AnimatedVisibility(
                visible = !isSearching && searchResults.isEmpty(),
                enter = fadeIn(animationSpec = tween(150)),
                exit = fadeOut(animationSpec = tween(100))
        ) {
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .imePadding(), // Поднимается при клавиатуре
                contentAlignment = Alignment.Center
            ) {
                Column(
                        horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    // Lottie search animation - play once for better performance
                    // Use preloaded composition if available
                    val composition = preloadedComposition
                    val progress by animateLottieCompositionAsState(
                        composition = composition,
                        iterations = 1,
                        isPlaying = true,
                        restartOnPlay = false
                    )
                    
                    LottieAnimation(
                            composition = composition,
                            progress = { progress },
                            modifier = Modifier.size(120.dp),
                            maintainOriginalImageBounds = true
                    )
                    
                    Spacer(modifier = Modifier.height(20.dp))
                    Text(
                            text = "Search for users",
                            fontSize = 17.sp,
                            fontWeight = FontWeight.Medium,
                            color = textColor
                    )
                    Spacer(modifier = Modifier.height(6.dp))
                    Text(
                            text = "Enter username or public key",
                            fontSize = 14.sp,
                            color = secondaryTextColor
                    )
                }
            }
        }

        // Results list - упрощенная анимация без staggered
        AnimatedVisibility(
                visible = !isSearching && searchResults.isNotEmpty(),
                enter = fadeIn(animationSpec = tween(150)),
                exit = fadeOut(animationSpec = tween(100))
        ) {
            LazyColumn(
                modifier = Modifier.fillMaxSize(),
                contentPadding = PaddingValues(vertical = 4.dp)
            ) {
                itemsIndexed(
                    items = searchResults,
                    key = { _, user -> user.publicKey }
                ) { index, user ->
                    SearchResultItem(
                        user = user,
                        isOwnAccount = user.publicKey == currentUserPublicKey,
                        isDarkTheme = isDarkTheme,
                        isLastItem = index == searchResults.size - 1,
                        avatarRepository = avatarRepository,
                        onClick = { onUserClick(user) }
                    )
                }
            }
        }
    }
}

/** Элемент результата поиска - минималистичный дизайн */
@Composable
private fun SearchResultItem(
        user: SearchUser,
        isOwnAccount: Boolean,
        isDarkTheme: Boolean,
        isLastItem: Boolean,
        avatarRepository: AvatarRepository? = null,
        onClick: () -> Unit
) {
    val textColor = if (isDarkTheme) Color.White else Color.Black
    val secondaryTextColor = if (isDarkTheme) Color(0xFF8E8E93) else Color(0xFF666666)
    val dividerColor = if (isDarkTheme) Color(0xFF2A2A2A) else Color(0xFFE8E8E8)

    Column {
        Row(
                modifier = Modifier
                        .fillMaxWidth()
                        .clickable(onClick = onClick)
                        .padding(horizontal = 16.dp, vertical = 12.dp),
                verticalAlignment = Alignment.CenterVertically
        ) {
            if (isOwnAccount) {
                Box(
                        modifier = Modifier
                                .size(48.dp)
                                .clip(CircleShape)
                                .background(Color(0xFF228BE6)),
                        contentAlignment = Alignment.Center
                ) {
                    Icon(
                            painter = painterResource(R.drawable.bookmark_outlined),
                            contentDescription = "Saved Messages",
                            tint = Color.White,
                            modifier = Modifier.size(20.dp)
                    )
                }
            } else {
                AvatarImage(
                        publicKey = user.publicKey,
                        avatarRepository = avatarRepository,
                        size = 48.dp,
                        isDarkTheme = isDarkTheme,
                        displayName = user.title.ifEmpty { user.username }
                )
            }

            Spacer(modifier = Modifier.width(12.dp))

            // User info
            Column(modifier = Modifier.weight(1f)) {
                // Name and verification badge
                Row(
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.spacedBy(4.dp)
                ) {
                    Text(
                            text = if (isOwnAccount) "Saved Messages"
                                   else user.title.ifEmpty { user.publicKey.take(10) },
                            fontSize = 16.sp,
                            fontWeight = FontWeight.Medium,
                            color = textColor,
                            maxLines = 1,
                            overflow = TextOverflow.Ellipsis
                    )

                    if (!isOwnAccount && user.verified > 0) {
                        VerifiedBadge(verified = user.verified, size = 16, isDarkTheme = isDarkTheme)
                    }
                }

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

                // Username
                Text(
                        text = if (isOwnAccount) "Notes"
                               else "@${user.username.ifEmpty { user.publicKey.take(10) + "..." }}",
                        fontSize = 14.sp,
                        color = secondaryTextColor,
                        maxLines = 1,
                        overflow = TextOverflow.Ellipsis
                )
            }
        }

        // Simple divider
        if (!isLastItem) {
            Divider(
                modifier = Modifier.padding(start = 76.dp),
                color = dividerColor,
                thickness = 0.5.dp
            )
        }
    }
}
