package com.seven.ikar.kotlin.feature.chats

import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.WindowInsetsSides
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.only
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.safeDrawing
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Archive
import androidx.compose.material.icons.outlined.CheckCircle
import androidx.compose.material.icons.outlined.Close
import androidx.compose.material.icons.outlined.Delete
import androidx.compose.material.icons.outlined.Edit
import androidx.compose.material.icons.outlined.Image
import androidx.compose.material.icons.outlined.NotificationsOff
import androidx.compose.material.icons.outlined.PlayArrow
import androidx.compose.material.icons.outlined.PushPin
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Checkbox
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.nestedscroll.NestedScrollConnection
import androidx.compose.ui.input.nestedscroll.NestedScrollSource
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalDensity
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.seven.ikar.kotlin.core.model.AttachmentDto
import com.seven.ikar.kotlin.core.model.AttachmentKind
import com.seven.ikar.kotlin.core.model.ChatSummaryDto
import com.seven.ikar.kotlin.core.model.ChatType
import com.seven.ikar.kotlin.core.model.StoryDto
import com.seven.ikar.kotlin.core.network.ServerConfig
import com.seven.ikar.kotlin.core.settings.ChatListLayoutOption
import com.seven.ikar.kotlin.core.settings.ChatSettingsSnapshot
import com.seven.ikar.kotlin.feature.share.PendingExternalShare
import com.seven.ikar.kotlin.ui.AuthenticatedAsyncImage
import com.seven.ikar.kotlin.ui.AvatarView
import com.seven.ikar.kotlin.ui.IkarFab
import com.seven.ikar.kotlin.ui.IkarFloatingMainMenu
import com.seven.ikar.kotlin.ui.IkarMainMenuTab
import com.seven.ikar.kotlin.ui.IkarRowDivider
import com.seven.ikar.kotlin.ui.IkarScreenSurface
import com.seven.ikar.kotlin.ui.IkarSearchCard
import com.seven.ikar.kotlin.ui.IkarSectionCard
import com.seven.ikar.kotlin.ui.chatPreview
import com.seven.ikar.kotlin.ui.theme.TelegramBlue
import com.seven.ikar.kotlin.ui.theme.TelegramInkMuted

@Composable
fun ChatsScreen(
    state: ChatsUiState,
    chatSettings: ChatSettingsSnapshot,
    onChatClick: (ChatSummaryDto) -> Unit,
    onChatSelectionClick: (ChatSummaryDto) -> Unit,
    onChatLongPress: (ChatSummaryDto) -> Unit,
    onClearSelection: () -> Unit,
    onSendSelectedChatsClick: () -> Unit,
    onDismissPendingShare: () -> Unit,
    onDeleteSelectedClick: () -> Unit,
    onPinSelectedChatsClick: () -> Unit,
    onArchiveSelectedChatsClick: () -> Unit,
    onMuteSelectedChatsClick: () -> Unit,
    onDismissDeleteDialog: () -> Unit,
    onDeleteForEveryoneChanged: (Boolean) -> Unit,
    onConfirmDeleteSelected: () -> Unit,
    onLogoutClick: () -> Unit,
    onRefreshClick: () -> Unit,
    onProfileClick: () -> Unit,
    onContactsClick: () -> Unit,
    onDiscoverClick: () -> Unit,
    onComposeStoryClick: () -> Unit,
    onStoryClick: (StoryDto) -> Unit,
    onSettingsClick: () -> Unit,
    onNotificationsClick: () -> Unit,
    onGlobalSearchClick: () -> Unit,
    onQueryChanged: (String) -> Unit
) {
    val isRealtimeConnected = !state.isLoading || state.chats.isNotEmpty()
    val previewMaxLines = if (chatSettings.chatListLayout == ChatListLayoutOption.ThreeLine) 2 else 1
    val chatListState = rememberLazyListState()
    var isStoriesHeaderVisible by remember { mutableStateOf(false) }
    var storyHeaderDragOffset by remember { mutableStateOf(0f) }
    val canToggleStoriesHeader = !state.isSelectionMode && !state.isShareMode
    val storyHeaderDragThresholdPx = with(LocalDensity.current) { 42.dp.toPx() }

    LaunchedEffect(canToggleStoriesHeader) {
        if (!canToggleStoriesHeader) {
            isStoriesHeaderVisible = false
            storyHeaderDragOffset = 0f
        }
    }

    val storyHeaderNestedScrollConnection = remember(
        canToggleStoriesHeader,
        chatListState,
        storyHeaderDragThresholdPx
    ) {
        object : NestedScrollConnection {
            override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
                if (!canToggleStoriesHeader || source != NestedScrollSource.UserInput) {
                    return Offset.Zero
                }

                val isChatListAtTop = chatListState.firstVisibleItemIndex == 0 &&
                    chatListState.firstVisibleItemScrollOffset == 0
                when {
                    available.y > 0f && !isStoriesHeaderVisible && isChatListAtTop -> {
                        storyHeaderDragOffset += available.y
                        if (storyHeaderDragOffset >= storyHeaderDragThresholdPx) {
                            isStoriesHeaderVisible = true
                            storyHeaderDragOffset = 0f
                        }
                    }

                    available.y < 0f && isStoriesHeaderVisible -> {
                        storyHeaderDragOffset += available.y
                        if (storyHeaderDragOffset <= -storyHeaderDragThresholdPx) {
                            isStoriesHeaderVisible = false
                            storyHeaderDragOffset = 0f
                        }
                    }

                    else -> {
                        storyHeaderDragOffset = 0f
                    }
                }

                return Offset.Zero
            }
        }
    }

    IkarScreenSurface(modifier = Modifier.fillMaxSize()) {
        Column(
            modifier = Modifier
                .fillMaxSize()
                .windowInsetsPadding(WindowInsets.safeDrawing.only(WindowInsetsSides.Vertical))
                .nestedScroll(storyHeaderNestedScrollConnection)
        ) {
            Column(
                modifier = Modifier.padding(start = 18.dp, top = 16.dp, end = 18.dp, bottom = 12.dp),
                verticalArrangement = Arrangement.spacedBy(12.dp)
            ) {
                when {
                    state.isSelectionMode && state.isShareMode -> {
                        ShareSelectionHeader(
                            selectedChatsCount = state.selectedChatsCount,
                            isSendingShare = state.isSendingShare,
                            onClearSelection = onClearSelection,
                            onSendSelectedChatsClick = onSendSelectedChatsClick
                        )
                    }

                    state.isSelectionMode -> {
                        SelectionHeader(
                            selectedChatsCount = state.selectedChatsCount,
                            isDeleteEnabled = !state.isDeletingSelected,
                            onClearSelection = onClearSelection,
                            onPinSelectedChatsClick = onPinSelectedChatsClick,
                            onArchiveSelectedChatsClick = onArchiveSelectedChatsClick,
                            onMuteSelectedChatsClick = onMuteSelectedChatsClick,
                            onDeleteSelectedClick = onDeleteSelectedClick
                        )
                    }

                    else -> {
                        if (isStoriesHeaderVisible) {
                            StoriesTray(
                                stories = state.stories,
                                accessToken = state.session?.accessToken,
                                currentUserId = state.session?.user?.id,
                                onComposeStoryClick = onComposeStoryClick,
                                onStoryClick = onStoryClick
                            )
                        } else {
                            ChatsBrandHeader(
                                isRealtimeConnected = isRealtimeConnected,
                                stories = state.stories,
                                accessToken = state.session?.accessToken,
                                currentUserId = state.session?.user?.id,
                                onStoriesClick = { isStoriesHeaderVisible = true }
                            )
                        }
                    }
                }

                IkarSearchCard(
                    value = state.query,
                    onValueChange = onQueryChanged,
                    placeholder = "Поиск чатов"
                )

                TextButton(onClick = onGlobalSearchClick) {
                    Text("Глобальный поиск: сообщения, медиа, файлы и ссылки")
                }

                state.pendingShare?.let { pendingShare ->
                    PendingShareCard(
                        pendingShare = pendingShare,
                        isSendingShare = state.isSendingShare,
                        onDismiss = onDismissPendingShare
                    )
                }

                state.errorMessage?.let {
                    Text(it, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall)
                }
            }

            Box(modifier = Modifier.weight(1f).fillMaxWidth()) {
                LazyColumn(
                    state = chatListState,
                    modifier = Modifier.fillMaxSize(),
                    verticalArrangement = Arrangement.spacedBy(0.dp)
                ) {
                    if (state.chats.isEmpty()) {
                        item {
                            Column(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(horizontal = 24.dp, vertical = 48.dp),
                                horizontalAlignment = Alignment.CenterHorizontally,
                                verticalArrangement = Arrangement.spacedBy(8.dp)
                            ) {
                                Text("Пока нет чатов", style = MaterialTheme.typography.headlineMedium)
                                Text(
                                    if (state.isShareMode) {
                                        "Поделиться пока некуда: сначала создайте хотя бы один чат."
                                    } else {
                                        "Найдите пользователя или откройте новый чат."
                                    },
                                    color = TelegramInkMuted,
                                    style = MaterialTheme.typography.bodyMedium
                                )
                            }
                        }
                    } else {
                        items(state.chats, key = { it.chat.id }) { chatItem ->
                            ChatListRow(
                                chatItem = chatItem,
                                currentUserId = state.session?.user?.id,
                                accessToken = state.session?.accessToken,
                                previewMaxLines = previewMaxLines,
                                onClick = {
                                    if (state.isSelectionMode) {
                                        onChatSelectionClick(chatItem.chat)
                                    } else {
                                        onChatClick(chatItem.chat)
                                    }
                                },
                                onLongClick = { onChatLongPress(chatItem.chat) }
                            )
                        }
                    }
                    item { Box(modifier = Modifier.padding(bottom = 132.dp)) }
                }

                if (!state.isSelectionMode && !state.isShareMode) {
                    IkarFab(
                        icon = Icons.Outlined.Edit,
                        contentDescription = "Новое сообщение",
                        modifier = Modifier
                            .align(Alignment.BottomEnd)
                            .padding(end = 20.dp, bottom = 126.dp),
                        onClick = onDiscoverClick
                    )
                }
            }
        }

        IkarFloatingMainMenu(
            selectedTab = IkarMainMenuTab.Chats,
            modifier = Modifier
                .align(Alignment.BottomCenter)
                .padding(horizontal = 8.dp, vertical = 18.dp),
            onChatsClick = {},
            onContactsClick = onContactsClick,
            onSettingsClick = onSettingsClick,
            onProfileClick = onProfileClick
        )

        if (state.isDeleteDialogVisible) {
            DeleteChatsDialog(
                selectedChatsCount = state.selectedChatsCount,
                showDeleteForEveryoneOption = state.showDeleteForEveryoneOption,
                deleteForEveryone = state.deleteForEveryone,
                isDeletingSelected = state.isDeletingSelected,
                onDismiss = onDismissDeleteDialog,
                onDeleteForEveryoneChanged = onDeleteForEveryoneChanged,
                onConfirmDeleteSelected = onConfirmDeleteSelected
            )
        }
    }
}

@Composable
private fun ChatsBrandHeader(
    isRealtimeConnected: Boolean,
    stories: List<StoryDto>,
    accessToken: String?,
    currentUserId: String?,
    onStoriesClick: () -> Unit
) {
    Row(
        horizontalArrangement = Arrangement.spacedBy(12.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        StoriesClusterButton(
            stories = stories,
            accessToken = accessToken,
            currentUserId = currentUserId,
            onClick = onStoriesClick
        )
        Column(verticalArrangement = Arrangement.spacedBy(0.dp)) {
            Text(
                text = if (isRealtimeConnected) "ИКАР" else "Соединение...",
                style = MaterialTheme.typography.displayMedium.copy(
                    letterSpacing = if (isRealtimeConnected) 3.sp else 0.sp
                ),
                color = TelegramBlue
            )
            Text("Чаты", style = MaterialTheme.typography.bodySmall, color = TelegramInkMuted)
        }
    }
}

@Composable
private fun StoriesClusterButton(
    stories: List<StoryDto>,
    accessToken: String?,
    currentUserId: String?,
    onClick: () -> Unit
) {
    val previewStories = stories.take(3)
    val placeholderColors = listOf(
        TelegramBlue,
        Color(0xFF7C4DFF),
        Color(0xFF00A884)
    )

    Box(
        modifier = Modifier
            .width(58.dp)
            .height(36.dp)
            .clickable(onClick = onClick),
        contentAlignment = Alignment.CenterStart
    ) {
        repeat(3) { index ->
            val story = previewStories.getOrNull(index)
            Box(
                modifier = Modifier
                    .padding(start = (index * 13).dp)
                    .size(30.dp)
                    .clip(CircleShape)
                    .background(placeholderColors[index].copy(alpha = if (story == null) 0.18f else 1f))
                    .border(2.dp, Color.White, CircleShape)
                    .padding(2.dp)
                    .clip(CircleShape),
                contentAlignment = Alignment.Center
            ) {
                if (story != null) {
                    val title = if (story.author.id == currentUserId) "Моя" else story.author.displayName
                    val previewUrl = ServerConfig.normalizeMediaUrl(
                        story.attachments.firstOrNull { it.contentType.startsWith("image/", ignoreCase = true) }?.downloadPath
                    )
                    if (previewUrl != null) {
                        AuthenticatedAsyncImage(
                            imageUrl = previewUrl,
                            accessToken = accessToken,
                            contentDescription = title,
                            modifier = Modifier.fillMaxSize(),
                            contentScale = ContentScale.Crop
                        )
                    } else {
                        AvatarView(
                            imageUrl = ServerConfig.normalizeMediaUrl(story.author.avatarPath),
                            title = title,
                            accessToken = accessToken,
                            size = 26.dp
                        )
                    }
                }
            }
        }
    }
}

@Composable
private fun StoriesTray(
    stories: List<StoryDto>,
    accessToken: String?,
    currentUserId: String?,
    onComposeStoryClick: () -> Unit,
    onStoryClick: (StoryDto) -> Unit
) {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(bottom = 2.dp),
        verticalArrangement = Arrangement.spacedBy(0.dp)
    ) {
        LazyRow(
            horizontalArrangement = Arrangement.spacedBy(12.dp),
            modifier = Modifier.fillMaxWidth()
        ) {
            item {
                StoryBubble(
                    title = "Моя",
                    avatarUrl = null,
                    previewUrl = null,
                    accessToken = accessToken,
                    viewed = false,
                    onClick = onComposeStoryClick,
                    modifier = Modifier.padding(start = 18.dp)
                )
            }

            items(stories, key = { it.id }) { story ->
                StoryBubble(
                    title = if (story.author.id == currentUserId) "Моя" else story.author.displayName,
                    avatarUrl = ServerConfig.normalizeMediaUrl(story.author.avatarPath),
                    previewUrl = ServerConfig.normalizeMediaUrl(
                        story.attachments.firstOrNull { it.contentType.startsWith("image/") }?.downloadPath
                    ),
                    accessToken = accessToken,
                    viewed = story.viewedByMe || story.author.id == currentUserId,
                    onClick = { onStoryClick(story) }
                )
            }

            item {
                Spacer(modifier = Modifier.width(6.dp))
            }
        }
    }
}

@Composable
private fun StoryBubble(
    title: String,
    avatarUrl: String?,
    previewUrl: String?,
    accessToken: String?,
    viewed: Boolean,
    onClick: () -> Unit,
    modifier: Modifier = Modifier
) {
    Column(
        modifier = modifier
            .width(74.dp)
            .clickable(onClick = onClick),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.spacedBy(6.dp)
    ) {
        Box(
            modifier = Modifier
                .size(62.dp)
                .clip(CircleShape)
                .border(
                    width = 2.dp,
                    color = if (viewed) Color(0xFFD8DEE6) else TelegramBlue,
                    shape = CircleShape
                )
                .padding(3.dp)
                .clip(CircleShape),
            contentAlignment = Alignment.Center
        ) {
            if (previewUrl != null) {
                AuthenticatedAsyncImage(
                    imageUrl = previewUrl,
                    accessToken = accessToken,
                    contentDescription = title,
                    modifier = Modifier.fillMaxSize(),
                    contentScale = androidx.compose.ui.layout.ContentScale.Crop
                )
            } else {
                AvatarView(
                    imageUrl = avatarUrl,
                    title = title,
                    accessToken = accessToken,
                    size = 56.dp
                )
            }
        }
        Text(
            title,
            style = MaterialTheme.typography.bodySmall,
            maxLines = 1,
            overflow = TextOverflow.Ellipsis
        )
    }
}

@Composable
private fun ShareSelectionHeader(
    selectedChatsCount: Int,
    isSendingShare: Boolean,
    onClearSelection: () -> Unit,
    onSendSelectedChatsClick: () -> Unit
) {
    Row(
        modifier = Modifier.fillMaxWidth(),
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.spacedBy(14.dp)
    ) {
        Icon(
            imageVector = Icons.Outlined.Close,
            contentDescription = "Снять выделение",
            tint = TelegramInkMuted,
            modifier = Modifier.clickable(enabled = !isSendingShare, onClick = onClearSelection)
        )

        Column(
            modifier = Modifier.weight(1f),
            verticalArrangement = Arrangement.spacedBy(2.dp)
        ) {
            Text(
                text = selectionCountLabel(selectedChatsCount),
                style = MaterialTheme.typography.titleLarge,
                fontWeight = FontWeight.SemiBold
            )
            Text(
                text = "Можно отправить в выбранные чаты",
                style = MaterialTheme.typography.bodySmall,
                color = TelegramInkMuted
            )
        }

        TextButton(
            enabled = !isSendingShare,
            onClick = onSendSelectedChatsClick
        ) {
            Text(
                text = if (isSendingShare) "Отправка..." else "Отправить",
                color = if (isSendingShare) TelegramInkMuted else TelegramBlue
            )
        }
    }
}

@Composable
private fun SelectionHeader(
    selectedChatsCount: Int,
    isDeleteEnabled: Boolean,
    onClearSelection: () -> Unit,
    onPinSelectedChatsClick: () -> Unit,
    onArchiveSelectedChatsClick: () -> Unit,
    onMuteSelectedChatsClick: () -> Unit,
    onDeleteSelectedClick: () -> Unit
) {
    Row(
        modifier = Modifier.fillMaxWidth(),
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.spacedBy(14.dp)
    ) {
        Icon(
            imageVector = Icons.Outlined.Close,
            contentDescription = "Снять выделение",
            tint = TelegramInkMuted,
            modifier = Modifier.clickable(onClick = onClearSelection)
        )

        Column(
            modifier = Modifier.weight(1f),
            verticalArrangement = Arrangement.spacedBy(2.dp)
        ) {
            Text(
                text = selectionCountLabel(selectedChatsCount),
                style = MaterialTheme.typography.titleLarge,
                fontWeight = FontWeight.SemiBold
            )
            Text(
                text = "Можно удалить выбранные чаты",
                style = MaterialTheme.typography.bodySmall,
                color = TelegramInkMuted
            )
        }

        Icon(
            imageVector = Icons.Outlined.PushPin,
            contentDescription = "Закрепить выбранные чаты",
            tint = TelegramBlue,
            modifier = Modifier.clickable(onClick = onPinSelectedChatsClick)
        )

        Icon(
            imageVector = Icons.Outlined.Archive,
            contentDescription = "Архивировать выбранные чаты",
            tint = TelegramBlue,
            modifier = Modifier.clickable(onClick = onArchiveSelectedChatsClick)
        )

        Icon(
            imageVector = Icons.Outlined.NotificationsOff,
            contentDescription = "Отключить уведомления в выбранных чатах",
            tint = TelegramBlue,
            modifier = Modifier.clickable(onClick = onMuteSelectedChatsClick)
        )

        Icon(
            imageVector = Icons.Outlined.Delete,
            contentDescription = "Удалить выбранные чаты",
            tint = if (isDeleteEnabled) MaterialTheme.colorScheme.error else TelegramInkMuted,
            modifier = Modifier.clickable(enabled = isDeleteEnabled, onClick = onDeleteSelectedClick)
        )
    }
}

@Composable
private fun PendingShareCard(
    pendingShare: PendingExternalShare,
    isSendingShare: Boolean,
    onDismiss: () -> Unit
) {
    IkarSectionCard {
        Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.spacedBy(12.dp),
                verticalAlignment = Alignment.Top
            ) {
                Column(
                    modifier = Modifier.weight(1f),
                    verticalArrangement = Arrangement.spacedBy(2.dp)
                ) {
                    Text(
                        text = if (isSendingShare) "Отправка..." else "Будет отправлено",
                        style = MaterialTheme.typography.labelLarge,
                        color = TelegramBlue
                    )
                    Text(
                        text = if (isSendingShare) {
                            "Подождите, отправка уже выполняется."
                        } else {
                            "Коснитесь чата, чтобы отправить сразу. Удерживайте, чтобы выбрать несколько."
                        },
                        style = MaterialTheme.typography.bodySmall,
                        color = TelegramInkMuted
                    )
                }
                Icon(
                    imageVector = Icons.Outlined.Close,
                    contentDescription = "Отменить поделиться",
                    tint = TelegramInkMuted,
                    modifier = Modifier.clickable(enabled = !isSendingShare, onClick = onDismiss)
                )
            }

            pendingShare.text?.takeIf { it.isNotBlank() }?.let { sharedText ->
                Text(
                    text = sharedText,
                    style = MaterialTheme.typography.bodyMedium,
                    maxLines = 3,
                    overflow = TextOverflow.Ellipsis
                )
            }

            if (pendingShare.attachments.isNotEmpty()) {
                Text(
                    text = pendingShareAttachmentSummary(pendingShare),
                    style = MaterialTheme.typography.bodySmall,
                    color = TelegramInkMuted
                )
                pendingShare.attachments.take(3).forEach { attachment ->
                    Text(
                        text = attachment.fileName,
                        style = MaterialTheme.typography.bodyMedium,
                        maxLines = 1,
                        overflow = TextOverflow.Ellipsis
                    )
                }
            }
        }
    }
}

@Composable
private fun DeleteChatsDialog(
    selectedChatsCount: Int,
    showDeleteForEveryoneOption: Boolean,
    deleteForEveryone: Boolean,
    isDeletingSelected: Boolean,
    onDismiss: () -> Unit,
    onDeleteForEveryoneChanged: (Boolean) -> Unit,
    onConfirmDeleteSelected: () -> Unit
) {
    AlertDialog(
        onDismissRequest = {
            if (!isDeletingSelected) {
                onDismiss()
            }
        },
        title = {
            Text(deleteDialogTitle(selectedChatsCount))
        },
        text = {
            Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
                Text(
                    text = deleteDialogMessage(selectedChatsCount),
                    color = TelegramInkMuted
                )
                if (showDeleteForEveryoneOption) {
                    Row(
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.spacedBy(10.dp)
                    ) {
                        Checkbox(
                            checked = deleteForEveryone,
                            enabled = !isDeletingSelected,
                            onCheckedChange = onDeleteForEveryoneChanged
                        )
                        Text(
                            text = "Также удалить чат для собеседника",
                            style = MaterialTheme.typography.bodyMedium
                        )
                    }
                }
            }
        },
        confirmButton = {
            TextButton(
                enabled = !isDeletingSelected,
                onClick = onConfirmDeleteSelected
            ) {
                Text("Удалить", color = MaterialTheme.colorScheme.error)
            }
        },
        dismissButton = {
            TextButton(
                enabled = !isDeletingSelected,
                onClick = onDismiss
            ) {
                Text("Отмена")
            }
        }
    )
}

@Composable
@OptIn(ExperimentalFoundationApi::class)
private fun ChatListRow(
    chatItem: ChatListItemUiState,
    currentUserId: String?,
    accessToken: String?,
    previewMaxLines: Int,
    onClick: () -> Unit,
    onLongClick: () -> Unit
) {
    val chat = chatItem.chat
    val avatarUser = if (chat.type == ChatType.Direct) {
        chat.participants.firstOrNull { it.id != currentUserId } ?: chat.participants.firstOrNull()
    } else {
        null
    }
    val avatarUrl = ServerConfig.normalizeMediaUrl(avatarUser?.avatarPath)
    val rowBackground = if (chatItem.isSelected) {
        TelegramBlue.copy(alpha = 0.12f)
    } else {
        Color.Transparent
    }

    Column {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 8.dp, vertical = 2.dp)
                .clip(MaterialTheme.shapes.large)
                .background(rowBackground)
                .combinedClickable(onClick = onClick, onLongClick = onLongClick)
                .padding(horizontal = 8.dp, vertical = 10.dp),
            horizontalArrangement = Arrangement.spacedBy(14.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            AvatarView(
                imageUrl = avatarUrl,
                title = chatItem.resolvedTitle,
                size = 56.dp
            )

            Column(
                modifier = Modifier.weight(1f),
                verticalArrangement = Arrangement.spacedBy(3.dp)
            ) {
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(12.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(
                        text = chatItem.resolvedTitle,
                        modifier = Modifier.weight(1f),
                        style = MaterialTheme.typography.titleLarge,
                        maxLines = 1,
                        overflow = TextOverflow.Ellipsis
                    )
                    if (chatItem.lastActivityLabel.isNotBlank()) {
                        Text(
                            text = chatItem.lastActivityLabel,
                            style = MaterialTheme.typography.bodySmall,
                            color = TelegramInkMuted,
                            maxLines = 1
                        )
                    }
                }
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(8.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    ChatLastMessagePreview(
                        chat = chat,
                        accessToken = accessToken,
                        modifier = Modifier.weight(1f),
                        maxLines = previewMaxLines
                    )
                    if (chat.unreadCount > 0) {
                        Box(
                            modifier = Modifier
                                .background(TelegramBlue, CircleShape)
                                .padding(horizontal = 8.dp, vertical = 4.dp),
                            contentAlignment = Alignment.Center
                        ) {
                            Text(
                                text = chat.unreadCount.toString(),
                                color = Color.White,
                                style = MaterialTheme.typography.labelMedium,
                                fontWeight = FontWeight.SemiBold,
                                maxLines = 1
                            )
                        }
                    }
                }
            }

            if (chatItem.isSelected) {
                Spacer(modifier = Modifier.width(4.dp))
                Icon(
                    imageVector = Icons.Outlined.CheckCircle,
                    contentDescription = "Чат выбран",
                    tint = TelegramBlue
                )
            }
        }
        IkarRowDivider(startIndent = 86.dp)
    }
}

@Composable
private fun ChatLastMessagePreview(
    chat: ChatSummaryDto,
    accessToken: String?,
    modifier: Modifier = Modifier,
    maxLines: Int
) {
    val attachment = chat.lastMessageAttachment
    when {
        attachment?.isChatPreviewImage() == true -> {
            Row(
                modifier = modifier,
                horizontalArrangement = Arrangement.spacedBy(6.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                val imageUrl = ServerConfig.normalizeMediaUrl(attachment.downloadPath)
                Box(
                    modifier = Modifier
                        .size(18.dp)
                        .clip(RoundedCornerShape(4.dp))
                        .background(TelegramBlue.copy(alpha = 0.12f)),
                    contentAlignment = Alignment.Center
                ) {
                    if (imageUrl != null) {
                        AuthenticatedAsyncImage(
                            imageUrl = imageUrl,
                            accessToken = accessToken,
                            contentDescription = "Фотография",
                            modifier = Modifier.fillMaxSize(),
                            contentScale = ContentScale.Crop
                        )
                    } else {
                        Icon(
                            imageVector = Icons.Outlined.Image,
                            contentDescription = null,
                            tint = TelegramInkMuted,
                            modifier = Modifier.size(14.dp)
                        )
                    }
                }
                Text(
                    text = "фотография",
                    modifier = Modifier.weight(1f),
                    style = MaterialTheme.typography.bodySmall,
                    color = TelegramInkMuted,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis
                )
            }
        }

        attachment?.isChatPreviewVoiceNote() == true -> {
            Row(
                modifier = modifier,
                horizontalArrangement = Arrangement.spacedBy(6.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Icon(
                    imageVector = Icons.Outlined.PlayArrow,
                    contentDescription = null,
                    tint = TelegramInkMuted,
                    modifier = Modifier.size(16.dp)
                )
                Text(
                    text = "голосовое сообщение",
                    modifier = Modifier.weight(1f),
                    style = MaterialTheme.typography.bodySmall,
                    color = TelegramInkMuted,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis
                )
            }
        }

        else -> {
            Text(
                text = chatPreview(chat),
                modifier = modifier,
                style = MaterialTheme.typography.bodySmall,
                color = TelegramInkMuted,
                maxLines = maxLines,
                overflow = TextOverflow.Ellipsis
            )
        }
    }
}

private fun AttachmentDto.isChatPreviewImage(): Boolean =
    contentType.startsWith("image/", ignoreCase = true) ||
        fileName.endsWith(".jpg", ignoreCase = true) ||
        fileName.endsWith(".jpeg", ignoreCase = true) ||
        fileName.endsWith(".png", ignoreCase = true) ||
        fileName.endsWith(".webp", ignoreCase = true) ||
        fileName.endsWith(".gif", ignoreCase = true)

private fun AttachmentDto.isChatPreviewVoiceNote(): Boolean =
    kind == AttachmentKind.VoiceNote ||
        contentType.startsWith("audio/", ignoreCase = true)

private fun selectionCountLabel(selectedChatsCount: Int): String = when {
    selectedChatsCount % 10 == 1 && selectedChatsCount % 100 != 11 -> "Выбран $selectedChatsCount чат"
    selectedChatsCount % 10 in 2..4 && selectedChatsCount % 100 !in 12..14 -> "Выбрано $selectedChatsCount чата"
    else -> "Выбрано $selectedChatsCount чатов"
}

private fun deleteDialogTitle(selectedChatsCount: Int): String =
    if (selectedChatsCount == 1) "Удалить чат?" else "Удалить выбранные чаты?"

private fun deleteDialogMessage(selectedChatsCount: Int): String =
    if (selectedChatsCount == 1) {
        "Чат исчезнет из вашего списка после подтверждения."
    } else {
        "Выбранные чаты исчезнут из вашего списка после подтверждения."
    }

private fun pendingShareAttachmentSummary(pendingShare: PendingExternalShare): String = when (pendingShare.attachments.size) {
    0 -> ""
    1 -> "1 файл"
    2, 3, 4 -> "${pendingShare.attachments.size} файла"
    else -> "${pendingShare.attachments.size} файлов"
}
