package com.rosetta.messenger.ui.chats.input

import android.content.Context
import android.view.inputmethod.InputMethodManager
import androidx.compose.animation.*
import androidx.compose.animation.core.*
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
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.material3.*
import androidx.compose.ui.draw.alpha
import com.rosetta.messenger.ui.icons.TelegramIcons
import androidx.compose.runtime.*
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalFocusManager

import androidx.compose.ui.draw.shadow
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 androidx.compose.ui.window.Popup
import androidx.compose.ui.window.PopupProperties
import app.rosette.android.ui.keyboard.AnimatedKeyboardTransition
import app.rosette.android.ui.keyboard.KeyboardTransitionCoordinator
import coil.compose.AsyncImage
import coil.request.ImageRequest
import com.rosetta.messenger.network.AttachmentType
import com.rosetta.messenger.repository.AvatarRepository
import com.rosetta.messenger.ui.components.AppleEmojiText
import com.rosetta.messenger.ui.components.AppleEmojiTextField
import com.rosetta.messenger.ui.components.AvatarImage
import com.rosetta.messenger.ui.components.OptimizedEmojiPicker
import com.rosetta.messenger.ui.onboarding.PrimaryBlue
import com.rosetta.messenger.ui.chats.models.*
import com.rosetta.messenger.ui.chats.components.*
import com.rosetta.messenger.ui.chats.utils.*
import com.rosetta.messenger.ui.chats.ChatViewModel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.util.Locale

/**
 * Message input bar and related components
 * Extracted from ChatDetailScreen.kt for better organization
 * 
 * Telegram UX rules:
 * 1. Input always linked to keyboard (imePadding)
 * 2. Last message always visible

 * 3. No layout jumps
 * 4. After sending: input clears, keyboard stays open
 * 5. Input grows upward for multi-line (up to 6 lines)
 */

data class MentionCandidate(
    val username: String,
    val title: String,
    val publicKey: String
)

@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun MessageInputBar(
    value: String,
    onValueChange: (String) -> Unit,
    onSend: () -> Unit,
    isDarkTheme: Boolean,
    backgroundColor: Color,
    textColor: Color,
    placeholderColor: Color,
    secondaryTextColor: Color,
    replyMessages: List<ChatViewModel.ReplyMessage> = emptyList(),
    isForwardMode: Boolean = false,
    onCloseReply: () -> Unit = {},
    onShowForwardOptions: (List<ChatViewModel.ReplyMessage>) -> Unit = {},
    chatTitle: String = "",
    isBlocked: Boolean = false,
    showEmojiPicker: Boolean = false,
    onToggleEmojiPicker: (Boolean) -> Unit = {},
    focusRequester: FocusRequester? = null,
    coordinator: KeyboardTransitionCoordinator,
    displayReplyMessages: List<ChatViewModel.ReplyMessage> = emptyList(),
    onReplyClick: (String) -> Unit = {},
    onAttachClick: () -> Unit = {},
    myPublicKey: String = "",
    opponentPublicKey: String = "",
    myPrivateKey: String = "",
    isGroupChat: Boolean = false,
    mentionCandidates: List<MentionCandidate> = emptyList(),
    avatarRepository: AvatarRepository? = null,
    inputFocusTrigger: Int = 0,
    suppressKeyboard: Boolean = false,
    hasNativeNavigationBar: Boolean = true
) {
    val hasReply = replyMessages.isNotEmpty()
    val liveReplyMessages =
        remember(replyMessages, displayReplyMessages) {
            if (displayReplyMessages.isNotEmpty()) displayReplyMessages else replyMessages
        }

    var animatedReplyMessages by remember {
        mutableStateOf<List<ChatViewModel.ReplyMessage>>(emptyList())
    }
    var animatedForwardMode by remember { mutableStateOf(isForwardMode) }

    LaunchedEffect(liveReplyMessages, isForwardMode) {
        if (liveReplyMessages.isNotEmpty()) {
            animatedReplyMessages = liveReplyMessages
            animatedForwardMode = isForwardMode
        }
    }

    val focusManager = LocalFocusManager.current
    val scope = rememberCoroutineScope()
    val context = LocalContext.current
    val view = LocalView.current
    val density = LocalDensity.current

    var editTextView by remember { mutableStateOf<com.rosetta.messenger.ui.components.AppleEmojiEditTextView?>(null) }

    // Auto-focus when reply panel opens
    LaunchedEffect(hasReply, editTextView) {
        if (hasReply && !suppressKeyboard) {
            delay(50)
            editTextView?.let { editText ->
                if (!showEmojiPicker) {
                    editText.requestFocus()
                    val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                    imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT)
                }
            }
        }
    }

    // Return focus to input after closing the photo editor
    LaunchedEffect(inputFocusTrigger) {
        if (inputFocusTrigger > 0 && !suppressKeyboard) {
            delay(100)
            editTextView?.let { editText ->
                editText.requestFocus()
                val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT)
            }
        }
    }

    // Camera overlay opened: hard-stop any keyboard/focus restoration from input effects.
    LaunchedEffect(suppressKeyboard) {
        if (suppressKeyboard) {
            val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm.hideSoftInputFromWindow(view.windowToken, 0)
            focusManager.clearFocus(force = true)
            view.findFocus()?.clearFocus()
        }
    }

    val imeInsets = WindowInsets.ime
    var isKeyboardVisible by remember { mutableStateOf(false) }
    var lastStableKeyboardHeight by remember { mutableStateOf(0.dp) }
    var lastToggleTime by remember { mutableLongStateOf(0L) }
    val toggleCooldownMs = 500L
    var isKeyboardAnimating by remember { mutableStateOf(false) }
    var lastKeyboardHeightChange by remember { mutableLongStateOf(0L) }
    val keyboardAnimationStabilizeMs = 250L

    // Update coordinator through snapshotFlow (no recomposition)
    LaunchedEffect(Unit) {
        snapshotFlow { with(density) { imeInsets.getBottom(density).toDp() } }.collect { currentImeHeight ->
            val now = System.currentTimeMillis()
            val heightChanged = kotlin.math.abs((currentImeHeight - lastStableKeyboardHeight).value) > 5f
            if (heightChanged && currentImeHeight.value > 0) {
                lastKeyboardHeightChange = now
                isKeyboardAnimating = true
            }
            if (now - lastKeyboardHeightChange > keyboardAnimationStabilizeMs && isKeyboardAnimating) {
                isKeyboardAnimating = false
            }

            isKeyboardVisible = currentImeHeight > 50.dp
            coordinator.updateKeyboardHeight(currentImeHeight)
            if (currentImeHeight > 100.dp) {
                coordinator.syncHeights()
                lastStableKeyboardHeight = currentImeHeight
            }
        }
    }

    // Load saved keyboard height
    LaunchedEffect(Unit) {
        com.rosetta.messenger.ui.components.KeyboardHeightProvider.getSavedKeyboardHeight(context)
    }

    // Save keyboard height when stable
    LaunchedEffect(isKeyboardVisible, showEmojiPicker) {
        if (isKeyboardVisible && !showEmojiPicker) {
            delay(350)
            if (isKeyboardVisible && !showEmojiPicker && lastStableKeyboardHeight > 300.dp) {
                val heightPx = with(density) { lastStableKeyboardHeight.toPx().toInt() }
                com.rosetta.messenger.ui.components.KeyboardHeightProvider.saveKeyboardHeight(context, heightPx)
            }
        }
    }

    val canSend = remember(value, hasReply) { value.isNotBlank() || hasReply }
    var isSending by remember { mutableStateOf(false) }
    var showForwardCancelDialog by remember { mutableStateOf(false) }
    var forwardCancelDialogCount by remember { mutableIntStateOf(0) }
    var forwardCancelDialogMessages by remember {
        mutableStateOf<List<ChatViewModel.ReplyMessage>>(emptyList())
    }
    val mentionPattern = remember { Regex("@([\\w\\d_]*)$") }
    val mentionedPattern = remember { Regex("@([\\w\\d_]{1,})") }
    val mentionMatch = remember(value, isGroupChat) { if (isGroupChat) mentionPattern.find(value) else null }

    val mentionQuery =
        remember(mentionMatch) {
            mentionMatch?.groupValues?.getOrNull(1)?.lowercase(Locale.ROOT).orEmpty()
        }

    val shouldShowMentionSuggestions = remember(mentionMatch, isGroupChat) { isGroupChat && mentionMatch != null }

    val mentionSuggestions =
        remember(
            value,
            mentionCandidates,
            mentionQuery,
            shouldShowMentionSuggestions
        ) {
            if (!shouldShowMentionSuggestions) {
                emptyList()
            } else {
                val mentionedInText =
                    mentionedPattern
                        .findAll(value)
                        .mapNotNull { match ->
                            match.groupValues.getOrNull(1)?.takeIf { it.isNotBlank() }?.lowercase(Locale.ROOT)
                        }
                        .toSet()

                val result = mutableListOf<MentionCandidate>()

                mentionCandidates.forEach { candidate ->
                    val normalized = candidate.username.trim().trimStart('@').lowercase(Locale.ROOT)
                    if (normalized.isBlank()) return@forEach
                    if (!normalized.startsWith(mentionQuery, ignoreCase = true)) return@forEach
                    if (mentionedInText.contains(normalized)) return@forEach
                    if (result.any { it.username.equals(normalized, ignoreCase = true) }) return@forEach
                    result.add(candidate.copy(username = normalized))
                }
                result
            }
        }

    // Close keyboard when user is blocked
    LaunchedEffect(isBlocked) {
        if (isBlocked) {
            val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm.hideSoftInputFromWindow(view.windowToken, 0)
            focusManager.clearFocus(force = true)
        }
    }

    fun hideKeyboardCompletely() {
        val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(view.windowToken, 0)
        focusManager.clearFocus(force = true)
    }

    fun toggleEmojiPicker() {
        if (suppressKeyboard) return

        val currentTime = System.currentTimeMillis()
        val timeSinceLastToggle = currentTime - lastToggleTime

        if (timeSinceLastToggle < toggleCooldownMs) {
            return
        }

        lastToggleTime = currentTime
        val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager

        if (coordinator.isEmojiVisible) {
            // EMOJI → KEYBOARD
            coordinator.requestShowKeyboard(
                showKeyboard = {
                    editTextView?.let { editText ->
                        editText.requestFocus()
                        @Suppress("DEPRECATION")
                        imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT)
                    }
                },
                hideEmoji = { onToggleEmojiPicker(false) }
            )
        } else if (coordinator.isKeyboardVisible || coordinator.keyboardHeight > 0.dp) {
            // KEYBOARD → EMOJI (клавиатура открыта)
            coordinator.requestShowEmoji(
                hideKeyboard = { imm.hideSoftInputFromWindow(view.windowToken, 0) },
                showEmoji = { onToggleEmojiPicker(true) }
            )
        } else {
            // Клавиатура НЕ открыта → открываем emoji напрямую
            // Устанавливаем высоту из сохранённой или дефолт
            if (coordinator.emojiHeight == 0.dp) {
                val savedPx = com.rosetta.messenger.ui.components.KeyboardHeightProvider
                    .getSavedKeyboardHeight(context)
                if (savedPx > 0) {
                    coordinator.emojiHeight = with(density) { savedPx.toDp() }
                } else {
                    coordinator.emojiHeight = 300.dp // разумный дефолт
                }
            }
            coordinator.isEmojiBoxVisible = true
            coordinator.openEmojiOnly(
                showEmoji = { onToggleEmojiPicker(true) }
            )
        }
    }

    fun handleSend() {
        if (value.isNotBlank() || hasReply) {
            isSending = true
            onSend()
            scope.launch {
                delay(150)
                isSending = false
            }
        }
    }

    fun onSelectMention(mention: MentionCandidate) {
        val mentionToken = "@${mention.username} "
        val updated =
            if (mentionPattern.containsMatchIn(value)) {
                mentionPattern.replace(value, mentionToken)
            } else {
                "$value$mentionToken"
            }
        onValueChange(updated)
        editTextView?.requestFocus()
    }

    Column(modifier = Modifier.fillMaxWidth().graphicsLayer { clip = false }) {
        if (isBlocked) {
            // BLOCKED CHAT FOOTER
            Column(modifier = Modifier.fillMaxWidth().background(backgroundColor)) {
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(0.5.dp)
                        .background(
                            if (isDarkTheme) Color.White.copy(alpha = 0.1f)
                            else Color.Black.copy(alpha = 0.08f)
                        )
                )

                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = 12.dp, vertical = 16.dp)
                        .padding(bottom = 20.dp)
                        .then(
                            if (hasNativeNavigationBar) Modifier.navigationBarsPadding()
                            else Modifier
                        ),
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.Center
                ) {
                    Icon(
                        painter = TelegramIcons.Block,
                        contentDescription = null,
                        tint = Color(0xFFFF6B6B),
                        modifier = Modifier.size(20.dp)
                    )
                    Spacer(modifier = Modifier.width(8.dp))
                    Text(
                        text = "You need to unblock user to send messages.",
                        fontSize = 14.sp,
                        color = secondaryTextColor,
                        textAlign = androidx.compose.ui.text.style.TextAlign.Center
                    )
                }
            }
        } else {
            Column(modifier = Modifier.fillMaxWidth().graphicsLayer { clip = false }) {
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(0.5.dp)
                        .background(
                            if (isDarkTheme) Color.White.copy(alpha = 0.1f)
                            else Color.Black.copy(alpha = 0.08f)
                        )
                )

                val shouldAddNavBarPadding =
                    hasNativeNavigationBar &&
                        !isKeyboardVisible &&
                        !coordinator.isEmojiBoxVisible

                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .background(color = backgroundColor)
                        .padding(
                            bottom = if (isKeyboardVisible || coordinator.isEmojiBoxVisible) 0.dp else 16.dp
                        )
                        .then(if (shouldAddNavBarPadding) Modifier.navigationBarsPadding() else Modifier)
                ) {
                    AnimatedVisibility(
                        visible = mentionSuggestions.isNotEmpty(),
                        enter = fadeIn(animationSpec = tween(120)) + expandVertically(animationSpec = tween(120)),
                        exit = fadeOut(animationSpec = tween(100)) + shrinkVertically(animationSpec = tween(100))
                    ) {
                        val mentionCardShape = RoundedCornerShape(14.dp)
                        val mentionCardColor = if (isDarkTheme) Color(0xFF272829) else Color.White
                        val mentionBorderColor =
                            if (isDarkTheme) Color(0xFF1C1D1F) else Color(0xFFF0F0F2)
                        val mentionDividerColor =
                            if (isDarkTheme) Color(0xFF1C1D1F) else Color(0xFFF5F5F5)
                        val mentionPrimaryText = if (isDarkTheme) Color.White else Color(0xFF222222)
                        val mentionSecondaryText = if (isDarkTheme) Color.White.copy(alpha = 0.47f) else Color(0xFF676B70)

                        Box(
                            modifier =
                                Modifier
                                    .fillMaxWidth()
                                    .padding(horizontal = 10.dp, vertical = 5.dp)
                                    .shadow(
                                        elevation = if (isDarkTheme) 6.dp else 3.dp,
                                        shape = mentionCardShape,
                                        clip = false
                                    )
                                    .clip(mentionCardShape)
                                    .background(color = mentionCardColor)
                                    .border(
                                        width = 1.dp,
                                        color = mentionBorderColor,
                                        shape = mentionCardShape
                                    )
                        ) {
                            LazyColumn(
                                modifier =
                                    Modifier
                                        .fillMaxWidth()
                                        .heightIn(max = 196.dp)
                                        .padding(vertical = 2.dp)
                            ) {
                                items(
                                    mentionSuggestions,
                                    key = { candidate ->
                                        if (candidate.publicKey.isNotBlank()) candidate.publicKey else candidate.username
                                    }
                                ) { candidate ->
                                    Column {
                                        Row(
                                            modifier =
                                                Modifier
                                                    .fillMaxWidth()
                                                    .clickable { onSelectMention(candidate) }
                                                    .padding(horizontal = 10.dp, vertical = 7.dp),
                                            verticalAlignment = Alignment.CenterVertically
                                        ) {
                                            if (candidate.publicKey.isNotBlank()) {
                                                AvatarImage(
                                                    publicKey = candidate.publicKey,
                                                    avatarRepository = avatarRepository,
                                                    size = 34.dp,
                                                    isDarkTheme = isDarkTheme,
                                                    displayName = candidate.title
                                                )
                                            } else {
                                                val fallbackColor = PrimaryBlue
                                                val fallbackText =
                                                    candidate.title.firstOrNull()?.uppercaseChar()?.toString() ?: "A"
                                                Box(
                                                    modifier =
                                                        Modifier
                                                            .size(34.dp)
                                                            .clip(CircleShape)
                                                            .background(fallbackColor),
                                                    contentAlignment = Alignment.Center
                                                ) {
                                                    Text(
                                                        text = fallbackText,
                                                        color = Color.White,
                                                        fontSize = 12.sp,
                                                        fontWeight = FontWeight.Bold
                                                    )
                                                }
                                            }

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

                                            val titleText = candidate.title.ifBlank { candidate.username }
                                            val usernameText = "@${candidate.username}"
                                            val showInlineUsername = candidate.username.isNotBlank()

                                            Row(
                                                modifier = Modifier.weight(1f),
                                                verticalAlignment = Alignment.CenterVertically
                                            ) {
                                                Text(
                                                    text = titleText,
                                                    fontSize = 14.sp,
                                                    fontWeight = FontWeight.Medium,
                                                    color = mentionPrimaryText,
                                                    maxLines = 1,
                                                    overflow = TextOverflow.Ellipsis,
                                                    modifier = Modifier.weight(1f, fill = false)
                                                )
                                                if (showInlineUsername) {
                                                    Spacer(modifier = Modifier.width(8.dp))
                                                    Text(
                                                        text = usernameText,
                                                        fontSize = 13.sp,
                                                        color = mentionSecondaryText,
                                                        maxLines = 1,
                                                        overflow = TextOverflow.Ellipsis,
                                                        modifier = Modifier.alpha(0.95f)
                                                    )
                                                }
                                            }
                                        }

                                        if (candidate != mentionSuggestions.last()) {
                                            Box(
                                                modifier =
                                                    Modifier
                                                        .fillMaxWidth()
                                                        .padding(start = 52.dp)
                                                        .height(0.5.dp)
                                                        .background(mentionDividerColor)
                                            )
                                        }
                                    }
                                }
                            }
                        }
                    }

                    // REPLY PANEL
                    AnimatedVisibility(
                        visible = hasReply,
                        enter = fadeIn(animationSpec = tween(200, easing = FastOutSlowInEasing)) +
                                expandVertically(
                                    animationSpec = spring(
                                        dampingRatio = Spring.DampingRatioMediumBouncy,
                                        stiffness = Spring.StiffnessMedium
                                    ),
                                    expandFrom = Alignment.Bottom
                                ),
                        exit = fadeOut(animationSpec = tween(150, easing = FastOutLinearInEasing)) +
                                shrinkVertically(
                                    animationSpec = tween(150, easing = FastOutLinearInEasing),
                                    shrinkTowards = Alignment.Bottom
                                )
                    ) {
                        val panelReplyMessages =
                            if (liveReplyMessages.isNotEmpty()) liveReplyMessages
                            else animatedReplyMessages
                        val panelIsForwardMode =
                            if (liveReplyMessages.isNotEmpty()) isForwardMode
                            else animatedForwardMode

                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .clickable {
                                    if (panelReplyMessages.isNotEmpty()) {
                                        onReplyClick(panelReplyMessages.first().messageId)
                                    }
                                }
                                .background(backgroundColor)
                                .padding(horizontal = 12.dp, vertical = 8.dp),
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Box(
                                modifier = Modifier
                                    .width(3.dp)
                                    .height(32.dp)
                                    .background(PrimaryBlue, androidx.compose.foundation.shape.RoundedCornerShape(1.5.dp))
                            )
                            Spacer(modifier = Modifier.width(10.dp))
                            Column(modifier = Modifier.weight(1f)) {
                                val replyTargetName =
                                    panelReplyMessages.firstOrNull()?.let { reply ->
                                        if (reply.isOutgoing) {
                                            "You"
                                        } else {
                                            reply.senderName.ifBlank { chatTitle }
                                        }
                                    } ?: "You"
                                Text(
                                    text = if (panelIsForwardMode)
                                        "Forward message${if (panelReplyMessages.size > 1) "s" else ""}"
                                    else
                                        "Reply to $replyTargetName",
                                    fontSize = 13.sp,
                                    fontWeight = FontWeight.SemiBold,
                                    color = PrimaryBlue,
                                    maxLines = 1
                                )
                                Spacer(modifier = Modifier.height(2.dp))
                                if (panelReplyMessages.isNotEmpty()) {
                                    val msg = panelReplyMessages.first()
                                    val hasImageAttachment = msg.attachments.any { 
                                        it.type == AttachmentType.IMAGE
                                    }
                                    AppleEmojiText(
                                        text = if (panelReplyMessages.size == 1) {
                                            if (msg.text.isEmpty() && hasImageAttachment) {
                                                "Photo"
                                            } else {
                                                val shortText = msg.text.take(40)
                                                if (shortText.length < msg.text.length) "$shortText..." else shortText
                                            }
                                        } else "${panelReplyMessages.size} messages",
                                        fontSize = 13.sp,
                                        color = if (isDarkTheme) Color.White.copy(alpha = 0.6f)
                                        else Color.Black.copy(alpha = 0.5f),
                                        maxLines = 1,
                                        overflow = android.text.TextUtils.TruncateAt.END,
                                        enableLinks = false
                                    )
                                }
                            }
                            
                            // 🔥 Превью изображения (как в Telegram)
                            if (panelReplyMessages.size == 1) {
                                val msg = panelReplyMessages.first()
                                val imageAttachment = msg.attachments.find { 
                                    it.type == AttachmentType.IMAGE
                                }
                                if (imageAttachment != null) {
                                    Spacer(modifier = Modifier.width(8.dp))
                                    ReplyImagePreview(
                                        attachment = imageAttachment,
                                        modifier = Modifier.size(36.dp),
                                        senderPublicKey = msg.publicKey.ifEmpty {
                                            if (msg.isOutgoing) myPublicKey else opponentPublicKey
                                        },
                                        recipientPrivateKey = myPrivateKey
                                    )
                                    Spacer(modifier = Modifier.width(4.dp))
                                }
                            }
                            
                            Box(
                                modifier = Modifier
                                    .size(32.dp)
                                    .clickable(
                                        interactionSource = remember { MutableInteractionSource() },
                                        indication = null,
                                        onClick = {
                                            if (panelIsForwardMode && panelReplyMessages.isNotEmpty()) {
                                                val sourceMessages =
                                                    if (replyMessages.isNotEmpty()) replyMessages
                                                    else panelReplyMessages
                                                forwardCancelDialogCount = sourceMessages.size
                                                forwardCancelDialogMessages = sourceMessages
                                                showForwardCancelDialog = true
                                            } else {
                                                onCloseReply()
                                            }
                                        }
                                    ),
                                contentAlignment = Alignment.Center
                            ) {
                                Icon(
                                    painter = TelegramIcons.Close,
                                    contentDescription = "Cancel",
                                    tint = if (isDarkTheme) Color.White.copy(alpha = 0.5f)
                                    else Color.Black.copy(alpha = 0.4f),
                                    modifier = Modifier.size(18.dp)
                                )
                            }
                        }
                    }

                    // INPUT ROW
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .heightIn(min = 48.dp)
                            .padding(horizontal = 12.dp, vertical = 8.dp),
                        verticalAlignment = Alignment.Bottom
                    ) {
                        IconButton(
                            onClick = onAttachClick,
                            modifier = Modifier.size(40.dp)
                        ) {
                            Icon(
                                painter = TelegramIcons.Attach,
                                contentDescription = "Attach",
                                tint = if (isDarkTheme) Color(0xFF8E8E93).copy(alpha = 0.6f)
                                else Color(0xFF8E8E93).copy(alpha = 0.6f),
                                modifier = Modifier.size(24.dp)
                            )
                        }

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

                        Box(
                            modifier = Modifier
                                .weight(1f)
                                .heightIn(min = 40.dp, max = 150.dp)
                                .background(color = backgroundColor)
                                .padding(horizontal = 12.dp, vertical = 8.dp),
                            contentAlignment = Alignment.TopStart
                        ) {
                            AppleEmojiTextField(
                                value = value,
                                onValueChange = { newValue -> onValueChange(newValue) },
                                textColor = textColor,
                                textSize = 16f,
                                hint = "Type message...",
                                hintColor = if (isDarkTheme) Color(0xFF8E8E93) else Color(0xFF8E8E93),
                                modifier = Modifier.fillMaxWidth(),
                                requestFocus = hasReply,
                                onViewCreated = { view -> editTextView = view },
                                onFocusChanged = { hasFocus ->
                                    if (hasFocus && showEmojiPicker) {
                                        onToggleEmojiPicker(false)
                                    }
                                }
                            )
                        }

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

                        IconButton(
                            onClick = { toggleEmojiPicker() },
                            modifier = Modifier.size(40.dp)
                        ) {
                            Icon(
                                painter = if (showEmojiPicker) TelegramIcons.Keyboard
                                else TelegramIcons.Smile,
                                contentDescription = "Emoji",
                                tint = if (isDarkTheme) Color(0xFF8E8E93).copy(alpha = 0.6f)
                                else Color(0xFF8E8E93).copy(alpha = 0.6f),
                                modifier = Modifier.size(24.dp)
                            )
                        }

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

                        AnimatedVisibility(
                            visible = canSend || isSending,
                            enter = scaleIn(tween(150)) + fadeIn(tween(150)),
                            exit = scaleOut(tween(100)) + fadeOut(tween(100))
                        ) {
                            IconButton(
                                onClick = { handleSend() },
                                modifier = Modifier.size(40.dp)
                            ) {
                                Icon(
                                    imageVector = TelegramSendIcon,
                                    contentDescription = "Send",
                                    tint = PrimaryBlue,
                                    modifier = Modifier.size(24.dp)
                                )
                            }
                        }
                    }
                }
            }
        }

        if (showForwardCancelDialog) {
            val titleText =
                if (forwardCancelDialogCount == 1) "1 message"
                else "$forwardCancelDialogCount messages"
            val bodyText =
                "What would you like to do with $titleText from your chat with ${chatTitle.ifBlank { "this user" }}?"
            val popupInteraction = remember { MutableInteractionSource() }
            val cardInteraction = remember { MutableInteractionSource() }
            val dividerColor = if (isDarkTheme) Color(0xFF3A3A3C) else Color(0xFFE5E5EA)
            val cardColor = if (isDarkTheme) Color(0xFF2C2C2E) else Color.White
            val bodyColor = if (isDarkTheme) Color(0xFFD1D1D6) else Color(0xFF3C3C43)

            Popup(
                alignment = Alignment.Center,
                onDismissRequest = {
                    showForwardCancelDialog = false
                    forwardCancelDialogMessages = emptyList()
                },
                properties =
                    PopupProperties(
                        focusable = false,
                        dismissOnBackPress = true,
                        dismissOnClickOutside = true,
                        clippingEnabled = false
                    )
            ) {
                Box(
                    modifier =
                        Modifier
                            .fillMaxSize()
                            .background(Color.Black.copy(alpha = 0.36f))
                            .clickable(
                                interactionSource = popupInteraction,
                                indication = null
                            ) { showForwardCancelDialog = false },
                    contentAlignment = Alignment.Center
                ) {
                    Surface(
                        modifier =
                            Modifier
                                .fillMaxWidth(0.88f)
                                .widthIn(max = 360.dp)
                                .clip(RoundedCornerShape(16.dp))
                                .clickable(
                                    interactionSource = cardInteraction,
                                    indication = null
                                ) {},
                        color = cardColor,
                        shadowElevation = 18.dp
                    ) {
                        Column(modifier = Modifier.fillMaxWidth()) {
                            Spacer(modifier = Modifier.height(18.dp))
                            Text(
                                text = titleText,
                                fontSize = 22.sp,
                                fontWeight = FontWeight.Bold,
                                color = if (isDarkTheme) Color.White else Color.Black,
                                modifier = Modifier.padding(horizontal = 20.dp)
                            )
                            Spacer(modifier = Modifier.height(10.dp))
                            Text(
                                text = bodyText,
                                fontSize = 16.sp,
                                lineHeight = 21.sp,
                                color = bodyColor,
                                modifier = Modifier.padding(horizontal = 20.dp)
                            )
                            Spacer(modifier = Modifier.height(14.dp))
                            Divider(thickness = 0.5.dp, color = dividerColor)
                            TextButton(
                                onClick = {
                                    showForwardCancelDialog = false
                                    val panelMessages =
                                        if (replyMessages.isNotEmpty()) {
                                            replyMessages
                                        } else if (forwardCancelDialogMessages.isNotEmpty()) {
                                            forwardCancelDialogMessages
                                        } else if (liveReplyMessages.isNotEmpty()) {
                                            liveReplyMessages
                                        } else {
                                            animatedReplyMessages
                                        }
                                    onShowForwardOptions(panelMessages)
                                    forwardCancelDialogMessages = emptyList()
                                },
                                modifier = Modifier.fillMaxWidth().height(52.dp)
                            ) {
                                Text(
                                    text = "Show forwarding options",
                                    fontSize = 18.sp,
                                    fontWeight = FontWeight.Medium,
                                    color = PrimaryBlue
                                )
                            }
                            TextButton(
                                onClick = {
                                    showForwardCancelDialog = false
                                    forwardCancelDialogMessages = emptyList()
                                    onCloseReply()
                                },
                                modifier = Modifier.fillMaxWidth().height(52.dp)
                            ) {
                                Text(
                                    text = "Cancel Forwarding",
                                    fontSize = 18.sp,
                                    fontWeight = FontWeight.Medium,
                                    color = Color(0xFFFF5D73)
                                )
                            }
                            Spacer(modifier = Modifier.height(6.dp))
                        }
                    }
                }
            }
        }

        // EMOJI PICKER
        if (!isBlocked) {
            AnimatedKeyboardTransition(
                coordinator = coordinator,
                showEmojiPicker = showEmojiPicker
            ) {
                OptimizedEmojiPicker(
                    isVisible = true,
                    isDarkTheme = isDarkTheme,
                    onEmojiSelected = { emoji -> onValueChange(value + emoji) },
                    onClose = { toggleEmojiPicker() },
                    modifier = Modifier.fillMaxWidth()
                )
            }
        }
    }
}
