package com.seven.ikar.kotlin.feature.members

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.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.ChatJoinRequestDto
import com.seven.ikar.kotlin.core.model.ChatJoinRequestStatus
import com.seven.ikar.kotlin.core.model.ChatMemberDto
import com.seven.ikar.kotlin.core.model.ChatMemberRole
import com.seven.ikar.kotlin.core.model.ModerationLogDto
import com.seven.ikar.kotlin.core.model.ModerationLogTargetType
import com.seven.ikar.kotlin.core.model.UserSummaryDto
import com.seven.ikar.kotlin.ui.AvatarView
import com.seven.ikar.kotlin.ui.IkarSearchCard
import com.seven.ikar.kotlin.ui.IkarRowDivider
import com.seven.ikar.kotlin.ui.IkarScreenSurface
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.formatLastActivity
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 ChatMembersScreen(
    state: ChatMembersUiState,
    onBackClick: () -> Unit,
    onRefreshClick: () -> Unit,
    onToggleAdmin: (ChatMemberDto) -> Unit,
    onToggleCanPost: (ChatMemberDto) -> Unit,
    onToggleCanPin: (ChatMemberDto) -> Unit,
    onToggleCanDelete: (ChatMemberDto) -> Unit,
    onToggleCanInvite: (ChatMemberDto) -> Unit,
    onMemberSearchChanged: (String) -> Unit,
    onAddMember: (UserSummaryDto) -> Unit,
    onAddAdmin: (UserSummaryDto) -> Unit,
    onApproveJoinRequest: (ChatJoinRequestDto) -> Unit,
    onDeclineJoinRequest: (ChatJoinRequestDto) -> Unit
) {
    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 = state.chat?.title?.ifBlank { "Участники" } ?: "Участники",
                onBackClick = onBackClick
            )

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

            if (state.isLoading && state.chat == null) {
                CircularProgressIndicator(color = TelegramBlue)
            }

            if (state.canAddMembers) {
                IkarSectionCard {
                    IkarSectionTitle("Добавить участника или бота", modifier = Modifier.padding(bottom = 8.dp))
                    IkarSearchCard(
                        value = state.memberSearchQuery,
                        onValueChange = onMemberSearchChanged,
                        placeholder = "Имя, username или бот"
                    )
                    if (state.isMemberSearchLoading) {
                        CircularProgressIndicator(color = TelegramBlue)
                    }
                    if (state.memberSearchQuery.trim().length >= 2 &&
                        !state.isMemberSearchLoading &&
                        state.memberSearchResults.isEmpty()
                    ) {
                        Text("Подходящих пользователей или ботов не найдено.", style = MaterialTheme.typography.bodySmall, color = TelegramInkMuted)
                    }
                    state.memberSearchResults.forEachIndexed { index, user ->
                        AddMemberCandidateRow(
                            user = user,
                            isAdding = state.addingUserIds.contains(user.id),
                            onAddMember = { onAddMember(user) },
                            onAddAdmin = { onAddAdmin(user) }
                        )
                        if (index != state.memberSearchResults.lastIndex) {
                            IkarRowDivider(startIndent = 58.dp)
                        }
                    }
                }
            }

            if (state.canManageMembers) {
                IkarSectionCard {
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        IkarSectionTitle("Заявки на вступление")
                        if (state.isAdminPanelLoading) {
                            CircularProgressIndicator(color = TelegramBlue)
                        }
                    }
                    val pendingRequests = state.joinRequests.filter { it.status == ChatJoinRequestStatus.Pending }
                    val resolvedRequests = state.joinRequests.filterNot { it.status == ChatJoinRequestStatus.Pending }
                    val displayedRequests = pendingRequests + resolvedRequests
                    if (state.joinRequests.isEmpty()) {
                        Text("Заявок на вступление пока нет.", style = MaterialTheme.typography.bodySmall, color = TelegramInkMuted)
                    }
                    displayedRequests.forEachIndexed { index, request ->
                        JoinRequestRow(
                            request = request,
                            isResolving = state.resolvingJoinRequestIds.contains(request.id),
                            onApproveClick = { onApproveJoinRequest(request) },
                            onDeclineClick = { onDeclineJoinRequest(request) }
                        )
                        if (index != displayedRequests.lastIndex) {
                            IkarRowDivider(startIndent = 58.dp)
                        }
                    }
                }
            }

            IkarSectionCard {
                IkarSectionTitle(
                    text = if (state.canManageMembers) "Участники и права" else "Участники",
                    modifier = Modifier.padding(bottom = 8.dp)
                )
                val members = state.chat?.members.orEmpty()
                members.forEachIndexed { index, member ->
                    MemberPermissionRow(
                        member = member,
                        canManage = state.canManageMembers && !member.isOwner,
                        isUpdating = state.updatingUserIds.contains(member.user.id),
                        onToggleAdmin = { onToggleAdmin(member) },
                        onToggleCanPost = { onToggleCanPost(member) },
                        onToggleCanPin = { onToggleCanPin(member) },
                        onToggleCanDelete = { onToggleCanDelete(member) },
                        onToggleCanInvite = { onToggleCanInvite(member) }
                    )
                    if (index != members.lastIndex) {
                        IkarRowDivider(startIndent = 58.dp)
                    }
                }
            }

            if (state.canManageMembers) {
                IkarSectionCard {
                    IkarSectionTitle("Журнал модерации", modifier = Modifier.padding(bottom = 8.dp))
                    if (state.moderationLog.isEmpty()) {
                        Text("Событий модерации пока нет.", style = MaterialTheme.typography.bodySmall, color = TelegramInkMuted)
                    }
                    state.moderationLog.forEachIndexed { index, entry ->
                        ModerationLogRow(entry)
                        if (index != state.moderationLog.lastIndex) {
                            IkarRowDivider()
                        }
                    }
                }
            }

            TextButton(onClick = onRefreshClick) {
                Text("Обновить")
            }
        }
    }
}

@Composable
private fun AddMemberCandidateRow(
    user: UserSummaryDto,
    isAdding: Boolean,
    onAddMember: () -> Unit,
    onAddAdmin: () -> Unit
) {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 10.dp),
        verticalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.spacedBy(12.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            AvatarView(
                imageUrl = user.avatarPath,
                title = user.displayName,
                size = 46.dp
            )
            Column(modifier = Modifier.weight(1f)) {
                Text(
                    text = user.displayName.ifBlank { "@${user.username}" },
                    style = MaterialTheme.typography.titleMedium,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis
                )
                Text(
                    text = if (user.isBot) "бот · @${user.username}" else "@${user.username}",
                    style = MaterialTheme.typography.bodySmall,
                    color = TelegramInkMuted,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis
                )
            }
        }
        Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
            TextButton(enabled = !isAdding, onClick = onAddMember) {
                Text(if (isAdding) "Добавление..." else "Добавить")
            }
            TextButton(enabled = !isAdding, onClick = onAddAdmin) {
                Text("Добавить админом", color = TelegramBlue)
            }
        }
    }
}

@Composable
private fun JoinRequestRow(
    request: ChatJoinRequestDto,
    isResolving: Boolean,
    onApproveClick: () -> Unit,
    onDeclineClick: () -> Unit
) {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 10.dp),
        verticalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.spacedBy(12.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            AvatarView(
                imageUrl = request.user.avatarPath,
                title = request.user.displayName,
                size = 46.dp
            )
            Column(modifier = Modifier.weight(1f)) {
                Text(
                    text = request.user.displayName.ifBlank { "@${request.user.username}" },
                    style = MaterialTheme.typography.titleMedium,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis
                )
                Text(
                    text = "Запрос: ${formatLastActivity(request.requestedAt)} - ${joinRequestStatusLabel(request.status)}",
                    style = MaterialTheme.typography.bodySmall,
                    color = TelegramInkMuted
                )
            }
        }
        if (request.status == ChatJoinRequestStatus.Pending) {
            Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                TextButton(enabled = !isResolving, onClick = onApproveClick) {
                    Text(if (isResolving) "Обработка..." else "Одобрить")
                }
                TextButton(enabled = !isResolving, onClick = onDeclineClick) {
                    Text("Отклонить", color = TelegramDanger)
                }
            }
        } else {
            val resolvedBy = request.resolvedBy?.displayName?.takeIf { it.isNotBlank() }
                ?: request.resolvedBy?.username
            Text(
                text = listOfNotNull(request.resolvedAt?.let { "Решено: ${formatLastActivity(it)}" }, resolvedBy?.let { "кем: $it" })
                    .joinToString(" - "),
                style = MaterialTheme.typography.bodySmall,
                color = TelegramInkMuted
            )
        }
    }
}

@Composable
private fun MemberPermissionRow(
    member: ChatMemberDto,
    canManage: Boolean,
    isUpdating: Boolean,
    onToggleAdmin: () -> Unit,
    onToggleCanPost: () -> Unit,
    onToggleCanPin: () -> Unit,
    onToggleCanDelete: () -> Unit,
    onToggleCanInvite: () -> Unit
) {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 10.dp),
        verticalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.spacedBy(12.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            AvatarView(
                imageUrl = member.user.avatarPath,
                title = member.user.displayName,
                size = 46.dp
            )
            Column(modifier = Modifier.weight(1f)) {
                Text(
                    text = member.user.displayName.ifBlank { "@${member.user.username}" },
                    style = MaterialTheme.typography.titleMedium,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis
                )
                Text(
                    text = roleLabel(member),
                    style = MaterialTheme.typography.bodySmall,
                    color = TelegramInkMuted
                )
            }
            if (canManage) {
                TextButton(enabled = !isUpdating, onClick = onToggleAdmin) {
                    Text(if (member.role == ChatMemberRole.Admin) "Сделать участником" else "Сделать администратором")
                }
            }
        }

        if (canManage) {
            Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
                PermissionChip("публикации", member.permissions.canPostMessages, isUpdating, onToggleCanPost)
                PermissionChip("закрепление", member.permissions.canPinMessages, isUpdating, onToggleCanPin)
                PermissionChip("удаление", member.permissions.canDeleteMessages, isUpdating, onToggleCanDelete)
                PermissionChip("приглашения", member.permissions.canInviteUsers, isUpdating, onToggleCanInvite)
            }
        }
    }
}

@Composable
private fun ModerationLogRow(entry: ModerationLogDto) {
    Column(
        modifier = Modifier.padding(vertical = 10.dp),
        verticalArrangement = Arrangement.spacedBy(4.dp)
    ) {
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(
                text = moderationActionLabel(entry.action),
                style = MaterialTheme.typography.titleSmall,
                fontWeight = FontWeight.SemiBold
            )
            Text(
                text = formatLastActivity(entry.createdAt),
                style = MaterialTheme.typography.bodySmall,
                color = TelegramInkMuted
            )
        }
        Text(
            text = "${entry.actorDisplayName} - ${moderationTargetLabel(entry.targetType)}",
            style = MaterialTheme.typography.bodySmall,
            color = TelegramInkMuted,
            maxLines = 1,
            overflow = TextOverflow.Ellipsis
        )
        entry.reason?.takeIf { it.isNotBlank() }?.let { reason ->
            Text(reason, style = MaterialTheme.typography.bodySmall)
        }
    }
}

@Composable
private fun PermissionChip(
    label: String,
    checked: Boolean,
    disabled: Boolean,
    onClick: () -> Unit
) {
    TextButton(enabled = !disabled, onClick = onClick) {
        Text(
            text = "$label: ${if (checked) "вкл" else "выкл"}",
            color = if (checked) TelegramBlue else TelegramInkMuted,
            fontWeight = if (checked) FontWeight.SemiBold else FontWeight.Normal
        )
    }
}

private fun roleLabel(member: ChatMemberDto): String = when {
    member.isOwner || member.role == ChatMemberRole.Owner -> "владелец"
    member.role == ChatMemberRole.Admin -> "администратор"
    else -> "участник"
}

private fun joinRequestStatusLabel(status: ChatJoinRequestStatus): String = when (status) {
    ChatJoinRequestStatus.Pending -> "ожидает"
    ChatJoinRequestStatus.Approved -> "одобрена"
    ChatJoinRequestStatus.Declined -> "отклонена"
}

private fun moderationTargetLabel(targetType: ModerationLogTargetType): String = when (targetType) {
    ModerationLogTargetType.Chat -> "чат"
    ModerationLogTargetType.Message -> "сообщение"
    ModerationLogTargetType.User -> "участник"
    ModerationLogTargetType.InviteLink -> "пригласительная ссылка"
    ModerationLogTargetType.JoinRequest -> "заявка на вступление"
    ModerationLogTargetType.Story -> "история"
}

private fun moderationActionLabel(action: String): String = when (action) {
    "chat.security.updated" -> "Настройки безопасности чата обновлены"
    "invite_link.joined" -> "Вход по пригласительной ссылке"
    "join_request.created" -> "Заявка на вступление создана"
    "join_request.approved" -> "Заявка на вступление одобрена"
    "join_request.declined" -> "Заявка на вступление отклонена"
    "member.added" -> "Участник добавлен"
    "member.admin.added" -> "Администратор добавлен"
    "member.permissions.updated" -> "Права участника обновлены"
    "message.deleted" -> "Сообщение удалено"
    "message.pinned" -> "Сообщение закреплено"
    "message.unpinned" -> "Сообщение откреплено"
    else -> action.replace('.', ' ').replace('_', ' ')
}
