package com.seven.ikar.kotlin.feature.chatinfo

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
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.only
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.safeDrawing
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Checkbox
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.seven.ikar.kotlin.core.model.ChatInviteLinkDto
import com.seven.ikar.kotlin.core.model.ChatTopicDto
import com.seven.ikar.kotlin.core.model.ChatType
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.IkarSectionTitle
import com.seven.ikar.kotlin.ui.IkarSimpleHeader
import com.seven.ikar.kotlin.ui.theme.TelegramBlue
import com.seven.ikar.kotlin.ui.theme.TelegramDanger
import com.seven.ikar.kotlin.ui.theme.TelegramInkMuted

@Composable
fun ChatInfoScreen(
    state: ChatInfoUiState,
    onBackClick: () -> Unit,
    onRefreshClick: () -> Unit,
    onMembersClick: () -> Unit,
    onSearchClick: () -> Unit,
    onInviteTitleChanged: (String) -> Unit,
    onInviteJoinRequestChanged: (Boolean) -> Unit,
    onCreateInviteClick: () -> Unit,
    onRevokeInviteClick: (ChatInviteLinkDto) -> Unit,
    onTopicTitleChanged: (String) -> Unit,
    onCreateTopicClick: () -> Unit
) {
    val info = state.info
    IkarScreenSurface(modifier = Modifier.fillMaxSize()) {
        Column(
            modifier = Modifier
                .fillMaxSize()
                .windowInsetsPadding(WindowInsets.safeDrawing.only(WindowInsetsSides.Vertical))
                .verticalScroll(rememberScrollState())
                .padding(horizontal = 18.dp, vertical = 16.dp),
            verticalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            IkarSimpleHeader(
                title = info?.chat?.title?.ifBlank { "Информация о чате" } ?: "Информация о чате",
                onBackClick = onBackClick
            )

            state.errorMessage?.let {
                Text(it, color = TelegramDanger, style = MaterialTheme.typography.bodySmall)
            }
            if (state.isLoading && info == null) {
                CircularProgressIndicator(color = TelegramBlue)
            }

            if (info != null) {
                IkarSectionCard {
                    IkarSectionTitle("Обзор", modifier = Modifier.padding(bottom = 8.dp))
                    Text(info.chat.type.label(), style = MaterialTheme.typography.bodyMedium, color = TelegramInkMuted)
                    Text(info.channelAudienceText(), style = MaterialTheme.typography.titleMedium)
                    if (info.chat.type == ChatType.Channel && info.adminCount > 0) {
                        Text("${info.adminCount} ${russianPlural(info.adminCount, "администратор", "администратора", "администраторов")}", style = MaterialTheme.typography.bodySmall, color = TelegramInkMuted)
                    }
                    val description = info.description ?: info.chat.description
                    if (!description.isNullOrBlank()) {
                        Text(description, style = MaterialTheme.typography.bodyMedium)
                    }
                    if (!info.publicUsername.isNullOrBlank()) {
                        Text("@${info.publicUsername}", color = TelegramBlue)
                    }
                    Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                        TextButton(onClick = onMembersClick) { Text("Участники") }
                        TextButton(onClick = onSearchClick) { Text("Поиск") }
                        TextButton(onClick = onRefreshClick) { Text("Обновить") }
                    }
                }

                IkarSectionCard {
                    IkarSectionTitle("Общие материалы", modifier = Modifier.padding(bottom = 8.dp))
                    InfoStatRow("Медиа", info.mediaCount)
                    InfoStatRow("Файлы", info.fileCount)
                    InfoStatRow("Ссылки", info.linkCount)
                    InfoStatRow("Голосовые", info.voiceCount)
                    InfoStatRow("Закреплённые", info.pinnedCount)
                }

                IkarSectionCard {
                    IkarSectionTitle("Пригласительные ссылки", modifier = Modifier.padding(bottom = 8.dp))
                    IkarSearchCard(
                        value = state.inviteTitle,
                        onValueChange = onInviteTitleChanged,
                        placeholder = "Название ссылки"
                    )
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.spacedBy(8.dp),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Checkbox(
                            checked = state.inviteCreatesJoinRequest,
                            onCheckedChange = onInviteJoinRequestChanged,
                            enabled = !state.isSaving
                        )
                        Column(modifier = Modifier.weight(1f)) {
                            Text("Требовать одобрение администратора", style = MaterialTheme.typography.bodyMedium)
                            Text(
                                "Новые пользователи попадут в заявки на вступление, а не войдут сразу.",
                                style = MaterialTheme.typography.bodySmall,
                                color = TelegramInkMuted
                            )
                        }
                    }
                    TextButton(enabled = !state.isSaving, onClick = onCreateInviteClick) {
                        Text(if (state.isSaving) "Сохранение..." else "Создать ссылку")
                    }
                    if (info.inviteLinks.isEmpty()) {
                        Text("Пригласительных ссылок пока нет.", style = MaterialTheme.typography.bodySmall, color = TelegramInkMuted)
                    }
                    info.inviteLinks.forEachIndexed { index, link ->
                        InviteLinkRow(link = link, onRevokeClick = { onRevokeInviteClick(link) })
                        if (index != info.inviteLinks.lastIndex) {
                            IkarRowDivider()
                        }
                    }
                }

                IkarSectionCard {
                    IkarSectionTitle("Темы", modifier = Modifier.padding(bottom = 8.dp))
                    IkarSearchCard(
                        value = state.topicTitle,
                        onValueChange = onTopicTitleChanged,
                        placeholder = "Новая тема"
                    )
                    TextButton(enabled = !state.isSaving, onClick = onCreateTopicClick) {
                        Text(if (state.isSaving) "Сохранение..." else "Создать тему")
                    }
                    info.topics.forEachIndexed { index, topic ->
                        TopicRow(topic)
                        if (index != info.topics.lastIndex) {
                            IkarRowDivider()
                        }
                    }
                }
            }
        }
    }
}

@Composable
private fun InfoStatRow(label: String, value: Int) {
    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.CenterVertically
    ) {
        Text(label, style = MaterialTheme.typography.bodyMedium)
        Text(value.toString(), style = MaterialTheme.typography.titleMedium, color = TelegramBlue)
    }
}

@Composable
private fun InviteLinkRow(
    link: ChatInviteLinkDto,
    onRevokeClick: () -> Unit
) {
    Column(
        modifier = Modifier.padding(vertical = 10.dp),
        verticalArrangement = Arrangement.spacedBy(4.dp)
    ) {
        Text(link.title ?: "Пригласительная ссылка", style = MaterialTheme.typography.titleMedium)
        Text(
            text = link.link,
            style = MaterialTheme.typography.bodySmall,
            color = if (link.isRevoked) TelegramInkMuted else TelegramBlue,
            maxLines = 1,
            overflow = TextOverflow.Ellipsis
        )
        Text(
            text = when {
                link.isRevoked -> "Отозвана"
                link.createsJoinRequest -> "Требует одобрения"
                else -> "Мгновенный вход"
            },
            style = MaterialTheme.typography.bodySmall,
            color = if (link.isRevoked) TelegramDanger else TelegramInkMuted
        )
        if (!link.isRevoked) {
            TextButton(onClick = onRevokeClick) { Text("Отозвать") }
        }
    }
}

@Composable
private fun TopicRow(topic: ChatTopicDto) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 10.dp),
        horizontalArrangement = Arrangement.spacedBy(10.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        Text(topic.icon, style = MaterialTheme.typography.titleLarge)
        Column(modifier = Modifier.weight(1f)) {
            Text(topic.title, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold)
            Text("${topic.messageCount} сообщений", style = MaterialTheme.typography.bodySmall, color = TelegramInkMuted)
        }
    }
}

private fun ChatType.label(): String = when (this) {
    ChatType.Direct -> "Личный чат"
    ChatType.Group -> "Группа"
    ChatType.Channel -> "Канал"
}

private fun com.seven.ikar.kotlin.core.model.ChatInfoDto.channelAudienceText(): String {
    if (chat.type != ChatType.Channel) {
        return "${chat.participants.size} участников"
    }

    val count = when {
        subscriberCount > 0 -> subscriberCount
        chat.subscriberCount > 0 -> chat.subscriberCount
        else -> chat.participants.size
    }
    return "$count ${russianPlural(count, "подписчик", "подписчика", "подписчиков")}"
}

private fun russianPlural(count: Int, one: String, few: String, many: String): String {
    val value = kotlin.math.abs(count) % 100
    val lastDigit = value % 10
    if (value in 11..14) {
        return many
    }

    return when (lastDigit) {
        1 -> one
        in 2..4 -> few
        else -> many
    }
}
