package com.seven.ikar.kotlin.feature.share

import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.seven.ikar.kotlin.core.contacts.DiscoverUserItem
import com.seven.ikar.kotlin.ui.AvatarView
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.IkarSimpleHeader
import com.seven.ikar.kotlin.ui.formatDiscoverPresence
import com.seven.ikar.kotlin.ui.formatPresenceColor
import com.seven.ikar.kotlin.ui.theme.TelegramBlue
import com.seven.ikar.kotlin.ui.theme.TelegramInkMuted

@Composable
fun ShareTargetScreen(
    state: ShareTargetUiState,
    onBackClick: () -> Unit,
    onQueryChanged: (String) -> Unit,
    onChatClick: (ShareChatTargetItemUiState) -> Unit,
    onUserClick: (DiscoverUserItem) -> Unit
) {
    IkarScreenSurface(modifier = Modifier.fillMaxSize()) {
        Column(
            modifier = Modifier
                .fillMaxSize()
                .statusBarsPadding()
                .navigationBarsPadding()
        ) {
            Column(
                modifier = Modifier.padding(start = 18.dp, top = 16.dp, end = 18.dp, bottom = 12.dp),
                verticalArrangement = Arrangement.spacedBy(12.dp)
            ) {
                IkarSimpleHeader(title = "Поделиться", onBackClick = onBackClick)

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

                SharePreviewCard(state.payload)

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

            IkarSectionCard(
                modifier = Modifier
                    .weight(1f)
                    .padding(horizontal = 18.dp)
                    .padding(bottom = 18.dp),
                padding = PaddingValues(0.dp)
            ) {
                LazyColumn {
                    if (state.isLoading && state.chats.isEmpty() && state.contacts.isEmpty()) {
                        item {
                            Row(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(horizontal = 24.dp, vertical = 32.dp),
                                horizontalArrangement = Arrangement.Center,
                                verticalAlignment = Alignment.CenterVertically
                            ) {
                                CircularProgressIndicator()
                            }
                        }
                    }

                    if (state.chats.isNotEmpty()) {
                        item {
                            SectionLabel("Чаты")
                        }
                        items(state.chats, key = { it.chat.id }) { item ->
                            ShareChatRow(item = item, onClick = { onChatClick(item) })
                        }
                    }

                    if (state.contacts.isNotEmpty()) {
                        item {
                            SectionLabel("Контакты")
                        }
                        items(state.contacts, key = { it.id }) { item ->
                            ShareContactRow(item = item, onClick = { onUserClick(item) })
                        }
                    }

                    if (!state.isLoading && state.chats.isEmpty() && state.contacts.isEmpty()) {
                        item {
                            Column(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(horizontal = 24.dp, vertical = 28.dp),
                                horizontalAlignment = Alignment.CenterHorizontally,
                                verticalArrangement = Arrangement.spacedBy(8.dp)
                            ) {
                                Text("Подходящих получателей нет", style = MaterialTheme.typography.headlineMedium)
                                Text(
                                    "Уточните поиск или откройте доступ к контактам.",
                                    color = TelegramInkMuted,
                                    style = MaterialTheme.typography.bodyMedium
                                )
                            }
                        }
                    }
                }
            }
        }
    }
}

@Composable
private fun SharePreviewCard(payload: PendingExternalShare) {
    IkarSectionCard {
        Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
            Text(
                text = "Будет отправлено",
                style = MaterialTheme.typography.labelLarge,
                color = TelegramBlue
            )
            payload.text?.takeIf { it.isNotBlank() }?.let { sharedText ->
                Text(
                    text = sharedText,
                    style = MaterialTheme.typography.bodyMedium,
                    maxLines = 3,
                    overflow = TextOverflow.Ellipsis
                )
            }
            if (payload.attachments.isNotEmpty()) {
                Text(
                    text = attachmentSummary(payload),
                    style = MaterialTheme.typography.bodySmall,
                    color = TelegramInkMuted
                )
                payload.attachments.take(3).forEach { attachment ->
                    Text(
                        text = attachment.fileName,
                        style = MaterialTheme.typography.bodyMedium,
                        maxLines = 1,
                        overflow = TextOverflow.Ellipsis
                    )
                }
            }
        }
    }
}

@Composable
private fun SectionLabel(text: String) {
    Text(
        text = text,
        modifier = Modifier.padding(start = 18.dp, top = 16.dp, end = 18.dp, bottom = 8.dp),
        style = MaterialTheme.typography.labelLarge,
        color = TelegramBlue
    )
}

@Composable
private fun ShareChatRow(
    item: ShareChatTargetItemUiState,
    onClick: () -> Unit
) {
    Column {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .clickable(onClick = onClick)
                .padding(horizontal = 18.dp, vertical = 12.dp),
            horizontalArrangement = Arrangement.spacedBy(14.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            AvatarView(imageUrl = null, title = item.resolvedTitle, size = 54.dp)
            Column(
                modifier = Modifier.weight(1f),
                verticalArrangement = Arrangement.spacedBy(3.dp)
            ) {
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.spacedBy(12.dp)
                ) {
                    Text(
                        text = item.resolvedTitle,
                        modifier = Modifier.weight(1f),
                        style = MaterialTheme.typography.titleLarge,
                        maxLines = 1,
                        overflow = TextOverflow.Ellipsis
                    )
                    if (item.lastActivityLabel.isNotBlank()) {
                        Text(
                            text = item.lastActivityLabel,
                            style = MaterialTheme.typography.bodySmall,
                            color = TelegramInkMuted,
                            maxLines = 1
                        )
                    }
                }
                Text(
                    text = item.preview,
                    style = MaterialTheme.typography.bodySmall,
                    color = TelegramInkMuted,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis
                )
            }
        }
        IkarRowDivider(startIndent = 86.dp)
    }
}

@Composable
private fun ShareContactRow(
    item: DiscoverUserItem,
    onClick: () -> Unit
) {
    Column {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .clickable(onClick = onClick)
                .padding(horizontal = 18.dp, vertical = 12.dp),
            horizontalArrangement = Arrangement.spacedBy(14.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            AvatarView(imageUrl = item.avatarUrl, title = item.displayName, size = 54.dp)
            Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(3.dp)) {
                Text(
                    text = item.displayName,
                    style = MaterialTheme.typography.titleLarge,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis
                )
                val secondaryText = item.secondaryLine.ifBlank { formatDiscoverPresence(item) }
                Text(
                    text = secondaryText,
                    style = MaterialTheme.typography.bodySmall,
                    color = if (item.secondaryLine.isBlank()) formatPresenceColor(item) else TelegramInkMuted,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis
                )
            }
        }
        IkarRowDivider(startIndent = 86.dp)
    }
}

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