package com.rosetta.messenger.ui.chats

import android.view.HapticFeedbackConstants
import androidx.compose.animation.animateColorAsState
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.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.ArrowForward
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Check
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.platform.LocalView
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.rosetta.messenger.R
import com.rosetta.messenger.data.ForwardManager
import com.rosetta.messenger.data.MessageRepository
import com.rosetta.messenger.repository.AvatarRepository
import com.rosetta.messenger.ui.components.AppleEmojiText
import com.rosetta.messenger.ui.components.AvatarImage
import com.rosetta.messenger.ui.components.VerifiedBadge
import com.rosetta.messenger.ui.onboarding.PrimaryBlue
import androidx.compose.ui.res.painterResource
import java.util.*
import kotlinx.coroutines.launch

/**
 * 📨 BottomSheet для выбора чатов при Forward сообщений
 *
 * Поддержка мультивыбора:
 * 1. Показывает список диалогов с чекбоксами
 * 2. Можно выбрать один или несколько чатов
 * 3. Кнопка "Forward" внизу подтверждает выбор
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ForwardChatPickerBottomSheet(
        dialogs: List<DialogUiModel>,
        isDarkTheme: Boolean,
        currentUserPublicKey: String,
        avatarRepository: AvatarRepository? = null,
        onDismiss: () -> Unit,
        onChatSelected: (DialogUiModel) -> Unit = {},
        onChatsSelected: (List<DialogUiModel>) -> Unit = { list -> if (list.size == 1) onChatSelected(list.first()) }
) {
    val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
    val scope = rememberCoroutineScope()
    val view = LocalView.current

    val backgroundColor = if (isDarkTheme) Color(0xFF1C1C1E) else Color.White
    val textColor = if (isDarkTheme) Color.White else Color.Black
    val secondaryTextColor = if (isDarkTheme) Color(0xFF8E8E93) else Color(0xFF666666)
    val dividerColor = if (isDarkTheme) Color(0xFF3A3A3A) else Color(0xFFE8E8E8)

    val forwardMessages by ForwardManager.forwardMessages.collectAsState()
    val messagesCount = forwardMessages.size

    // 🔥 Фильтруем системные аккаунты (Safe, Rosetta Updates)
    // и всегда добавляем Saved Messages, даже если self-диалог еще не создан.
    val filteredDialogs = remember(dialogs, currentUserPublicKey) {
        val base = dialogs.filter { !MessageRepository.isSystemAccount(it.opponentKey) }
        val selfKey = currentUserPublicKey.trim()
        if (selfKey.isBlank() || base.any { it.opponentKey == selfKey }) {
            base
        } else {
            val savedMessagesDialog =
                    DialogUiModel(
                            id = Long.MIN_VALUE,
                            account = selfKey,
                            opponentKey = selfKey,
                            opponentTitle = "Saved Messages",
                            opponentUsername = "",
                            lastMessage = "",
                            lastMessageTimestamp = 0L,
                            unreadCount = 0,
                            isOnline = 0,
                            lastSeen = 0L,
                            verified = 0,
                            isSavedMessages = true,
                            lastMessageFromMe = 1,
                            lastMessageDelivered = 1,
                            lastMessageRead = 1,
                            lastMessageAttachmentType = null,
                            lastMessageSenderPrefix = null,
                            lastMessageSenderKey = null,
                            draftText = null
                    )
            listOf(savedMessagesDialog) + base
        }
    }

    // Мультивыбор чатов
    var selectedChats by remember { mutableStateOf<Set<String>>(emptySet()) }

    // 🔥 Haptic feedback при открытии
    LaunchedEffect(Unit) {
        view.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS)
    }

    // 🎨 Плавное затемнение статус бара когда bottom sheet открыт
    DisposableEffect(Unit) {
        if (!view.isInEditMode) {
            val window = (view.context as? android.app.Activity)?.window
            val originalStatusBarColor = window?.statusBarColor ?: 0
            val scrimColor = android.graphics.Color.argb(153, 0, 0, 0) // 60% черный

            // Плавное затемнение
            val fadeInAnimator = android.animation.ValueAnimator.ofArgb(originalStatusBarColor, scrimColor).apply {
                duration = 200
                addUpdateListener { animator ->
                    window?.statusBarColor = animator.animatedValue as Int
                }
            }
            fadeInAnimator.start()

            onDispose {
                // Плавное восстановление
                val fadeOutAnimator = android.animation.ValueAnimator.ofArgb(scrimColor, originalStatusBarColor).apply {
                    duration = 150
                    addUpdateListener { animator ->
                        window?.statusBarColor = animator.animatedValue as Int
                    }
                }
                fadeOutAnimator.start()
            }
        } else {
            onDispose { }
        }
    }

    // 🔥 Функция для красивого закрытия с анимацией
    fun dismissWithAnimation() {
        scope.launch {
            sheetState.hide()
            onDismiss()
        }
    }

    ModalBottomSheet(
            onDismissRequest = { dismissWithAnimation() },
            sheetState = sheetState,
            containerColor = backgroundColor,
            scrimColor = Color.Black.copy(alpha = 0.6f),
            dragHandle = {
                // Кастомный handle
                Column(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    Spacer(modifier = Modifier.height(8.dp))
                    Box(
                            modifier =
                                    Modifier.width(36.dp)
                                            .height(5.dp)
                                            .clip(RoundedCornerShape(2.5.dp))
                                            .background(
                                                    if (isDarkTheme) Color(0xFF4A4A4A)
                                                    else Color(0xFFD1D1D6)
                                            )
                    )
                    Spacer(modifier = Modifier.height(16.dp))
                }
            },
            shape = RoundedCornerShape(topStart = 16.dp, topEnd = 16.dp),
            modifier = Modifier.statusBarsPadding()
    ) {
        Column(modifier = Modifier.fillMaxWidth().navigationBarsPadding()) {
            // Header
            Row(
                    modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp),
                    horizontalArrangement = Arrangement.SpaceBetween,
                    verticalAlignment = Alignment.CenterVertically
            ) {
                // Иконка и заголовок
                Row(verticalAlignment = Alignment.CenterVertically) {
                    Icon(
                            Icons.Filled.ArrowForward,
                            contentDescription = null,
                            tint = PrimaryBlue,
                            modifier = Modifier.size(24.dp)
                    )
                    Spacer(modifier = Modifier.width(12.dp))
                    Column {
                        Text(
                                text = "Forward to",
                                fontSize = 18.sp,
                                fontWeight = FontWeight.Bold,
                                color = textColor
                        )
                        Text(
                                text =
                                        "$messagesCount message${if (messagesCount > 1) "s" else ""} selected",
                                fontSize = 14.sp,
                                color = secondaryTextColor
                        )
                    }
                }

                // Кнопка закрытия с анимацией
                IconButton(onClick = { dismissWithAnimation() }) {
                    Icon(
                            Icons.Default.Close,
                            contentDescription = "Close",
                            tint = secondaryTextColor.copy(alpha = 0.6f)
                    )
                }
            }

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

            Divider(color = dividerColor, thickness = 0.5.dp)

            // Список диалогов
            if (filteredDialogs.isEmpty()) {
                // Empty state
                Box(
                        modifier = Modifier.fillMaxWidth().height(200.dp),
                        contentAlignment = Alignment.Center
                ) {
                    Column(horizontalAlignment = Alignment.CenterHorizontally) {
                        Text(
                                text = "No chats yet",
                                fontSize = 16.sp,
                                fontWeight = FontWeight.Medium,
                                color = secondaryTextColor
                        )
                        Spacer(modifier = Modifier.height(4.dp))
                        Text(
                                text = "Start a conversation first",
                                fontSize = 14.sp,
                                color = secondaryTextColor.copy(alpha = 0.7f)
                        )
                    }
                }
            } else {
                LazyColumn(
                        modifier =
                                Modifier.fillMaxWidth()
                                        .weight(1f)
                ) {
                    items(filteredDialogs, key = { it.opponentKey }) { dialog ->
                        val isSelected = dialog.opponentKey in selectedChats
                        ForwardDialogItem(
                                dialog = dialog,
                                isDarkTheme = isDarkTheme,
                                isSavedMessages = dialog.opponentKey == currentUserPublicKey,
                                isSelected = isSelected,
                                avatarRepository = avatarRepository,
                                onClick = {
                                    view.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP)
                                    selectedChats = if (isSelected) {
                                        selectedChats - dialog.opponentKey
                                    } else {
                                        selectedChats + dialog.opponentKey
                                    }
                                }
                        )

                        // Сепаратор между диалогами
                        if (dialog != filteredDialogs.last()) {
                            Divider(
                                    modifier = Modifier.padding(start = 76.dp),
                                    color = dividerColor,
                                    thickness = 0.5.dp
                            )
                        }
                    }
                }
            }

            // Кнопка Forward (всегда видна, disabled когда ничего не выбрано)
            Spacer(modifier = Modifier.height(8.dp))
            Divider(color = dividerColor, thickness = 0.5.dp)
            Spacer(modifier = Modifier.height(8.dp))

            val hasSelection = selectedChats.isNotEmpty()
            Button(
                    onClick = {
                        val selectedDialogs = filteredDialogs.filter { it.opponentKey in selectedChats }
                        onChatsSelected(selectedDialogs)
                    },
                    enabled = hasSelection,
                    modifier = Modifier
                            .fillMaxWidth()
                            .padding(horizontal = 16.dp)
                            .height(48.dp),
                    shape = RoundedCornerShape(12.dp),
                    colors = ButtonDefaults.buttonColors(
                            containerColor = PrimaryBlue,
                            contentColor = Color.White,
                            disabledContainerColor = if (isDarkTheme) Color(0xFF3A3A3A) else Color(0xFFD1D1D6),
                            disabledContentColor = if (isDarkTheme) Color(0xFF8E8E93) else Color(0xFF999999)
                    )
            ) {
                Icon(
                        Icons.Filled.ArrowForward,
                        contentDescription = null,
                        modifier = Modifier.size(20.dp)
                )
                Spacer(modifier = Modifier.width(8.dp))
                Text(
                        text = if (hasSelection) "Forward (${selectedChats.size})" else "Select a chat",
                        fontSize = 16.sp,
                        fontWeight = FontWeight.SemiBold
                )
            }

            // Нижний padding
            Spacer(modifier = Modifier.height(16.dp))
        }
    }
}

/** Элемент диалога в списке выбора для Forward */
@Composable
private fun ForwardDialogItem(
        dialog: DialogUiModel,
        isDarkTheme: Boolean,
        isSavedMessages: Boolean = false,
        isSelected: Boolean = false,
        avatarRepository: AvatarRepository? = null,
        onClick: () -> Unit
) {
    val textColor = if (isDarkTheme) Color.White else Color.Black
    val secondaryTextColor = if (isDarkTheme) Color(0xFF8E8E93) else Color(0xFF666666)

    val displayName =
            remember(dialog.opponentTitle, dialog.opponentUsername, dialog.opponentKey, isSavedMessages) {
                when {
                    isSavedMessages -> "Saved Messages"
                    dialog.opponentTitle.isNotEmpty() -> dialog.opponentTitle
                    dialog.opponentUsername.isNotEmpty() -> "@${dialog.opponentUsername}"
                    else -> dialog.opponentKey.take(8)
                }
            }

    // Display name for avatar initials
    val avatarDisplayName = remember(dialog.opponentTitle, dialog.opponentUsername) {
        when {
            dialog.opponentTitle.isNotEmpty() -> dialog.opponentTitle
            dialog.opponentUsername.isNotEmpty() -> dialog.opponentUsername
            else -> null
        }
    }

    val selectedBg by animateColorAsState(
            targetValue = if (isSelected) PrimaryBlue.copy(alpha = 0.08f) else Color.Transparent,
            animationSpec = tween(150),
            label = "selectedBg"
    )

    Row(
            modifier =
                    Modifier.fillMaxWidth()
                            .background(selectedBg)
                            .clickable(onClick = onClick)
                            .padding(horizontal = 16.dp, vertical = 12.dp),
            verticalAlignment = Alignment.CenterVertically
    ) {
        // Avatar with real image support
        if (isSavedMessages) {
            Box(
                    modifier = Modifier
                            .size(48.dp)
                            .clip(CircleShape)
                            .background(Color(0xFF228BE6)),
                    contentAlignment = Alignment.Center
            ) {
                Icon(
                        painter = painterResource(R.drawable.bookmark_outlined),
                        contentDescription = null,
                        tint = Color.White,
                        modifier = Modifier.size(22.dp)
                )
            }
        } else {
            // Regular user - use AvatarImage with real avatar support
            AvatarImage(
                    publicKey = dialog.opponentKey,
                    avatarRepository = avatarRepository,
                    size = 48.dp,
                    isDarkTheme = isDarkTheme,
                    displayName = avatarDisplayName
            )
        }

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

        // Info
        Column(modifier = Modifier.weight(1f)) {
            Row(
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.spacedBy(4.dp)
            ) {
                Text(
                        text = displayName,
                        fontWeight = FontWeight.SemiBold,
                        fontSize = 16.sp,
                        color = textColor,
                        maxLines = 1,
                        overflow = TextOverflow.Ellipsis,
                        modifier = Modifier.weight(1f, fill = false)
                )

                // ✅ Verified badge
                if (!isSavedMessages && dialog.verified > 0) {
                    VerifiedBadge(
                        verified = dialog.verified,
                        size = 16,
                        isDarkTheme = isDarkTheme
                    )
                }
            }

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

            // 📎 Определяем текст превью с учетом attachments
            val previewText = when {
                isSavedMessages -> "Your personal notes"
                dialog.lastMessageAttachmentType == "Photo" -> "Photo"
                dialog.lastMessageAttachmentType == "File" -> "File"
                dialog.lastMessageAttachmentType == "Avatar" -> "Avatar"
                dialog.lastMessageAttachmentType == "Call" -> "Call"
                dialog.lastMessageAttachmentType == "Forwarded" -> "Forwarded message"
                dialog.lastMessage.isNotEmpty() -> dialog.lastMessage
                else -> "No messages"
            }

            AppleEmojiText(
                    text = previewText,
                    fontSize = 14.sp,
                    color = secondaryTextColor,
                    maxLines = 1,
                    enableLinks = false
            )
        }

        // Чекбокс выбора (справа)
        Spacer(modifier = Modifier.width(8.dp))
        Box(
                modifier = Modifier
                        .size(24.dp)
                        .clip(CircleShape)
                        .background(
                                if (isSelected) PrimaryBlue
                                else if (isDarkTheme) Color(0xFF3A3A3A)
                                else Color(0xFFE0E0E0)
                        ),
                contentAlignment = Alignment.Center
        ) {
            if (isSelected) {
                Icon(
                        Icons.Default.Check,
                        contentDescription = "Selected",
                        tint = Color.White,
                        modifier = Modifier.size(16.dp)
                )
            }
        }
    }
}
