package com.seven.ikar.kotlin.feature.privacy

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.AlertDialog
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Block
import androidx.compose.material.icons.outlined.Image
import androidx.compose.material.icons.outlined.Lock
import androidx.compose.material.icons.outlined.Phone
import androidx.compose.material.icons.outlined.Schedule
import androidx.compose.material.icons.outlined.Security
import androidx.compose.material.icons.outlined.Visibility
import androidx.compose.material3.Icon
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.ui.unit.dp
import com.seven.ikar.kotlin.core.model.PrivacySettingsDto
import com.seven.ikar.kotlin.core.model.UserSummaryDto
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.IkarSectionCard
import com.seven.ikar.kotlin.ui.IkarSectionTitle
import com.seven.ikar.kotlin.ui.IkarSettingRow
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 PrivacySecurityScreen(
    state: PrivacySecurityUiState,
    onBackClick: () -> Unit,
    onUpdate: ((PrivacySettingsDto) -> PrivacySettingsDto) -> Unit,
    onUserSearchQueryChanged: (String) -> Unit,
    onBlockUser: (UserSummaryDto) -> Unit,
    onUnblockUser: (String) -> Unit,
    onAlwaysAllowUser: (UserSummaryDto) -> Unit,
    onNeverAllowUser: (UserSummaryDto) -> Unit,
    onRemoveAlwaysAllow: (String) -> Unit,
    onRemoveNeverAllow: (String) -> Unit,
    onEnablePasscode: (String, String) -> Unit,
    onDisablePasscode: (String) -> Unit
) {
    var passcodeDialogMode by remember { mutableStateOf<PasscodeDialogMode?>(null) }
    var listDialogMode by remember { mutableStateOf<PrivacyListDialogMode?>(null) }
    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 = "Конфиденциальность и безопасность", onBackClick = onBackClick)
            state.errorMessage?.let {
                Text(it, color = TelegramDanger, style = MaterialTheme.typography.bodySmall)
            }
            if (state.isLoading && state.settings == null) {
                CircularProgressIndicator(color = TelegramBlue)
            }
            val settings = state.settings
            if (settings != null) {
                IkarSectionCard {
                    IkarSectionTitle("Конфиденциальность", modifier = Modifier.padding(bottom = 8.dp))
                    PrivacyRow("Номер телефона", privacyValueLabel(settings.phoneNumberVisibility), Icons.Outlined.Phone) {
                        onUpdate { it.copy(phoneNumberVisibility = nextVisibility(it.phoneNumberVisibility)) }
                    }
                    IkarRowDivider()
                    PrivacyRow("Последняя активность и онлайн", privacyValueLabel(settings.lastSeenVisibility), Icons.Outlined.Schedule) {
                        onUpdate { it.copy(lastSeenVisibility = nextVisibility(it.lastSeenVisibility)) }
                    }
                    IkarRowDivider()
                    PrivacyRow("Фотографии профиля", privacyValueLabel(settings.profilePhotoVisibility), Icons.Outlined.Image) {
                        onUpdate { it.copy(profilePhotoVisibility = nextVisibility(it.profilePhotoVisibility)) }
                    }
                    IkarRowDivider()
                    PrivacyRow("Заблокированные пользователи", "${settings.blockedUserIds.size}", Icons.Outlined.Block) {
                        listDialogMode = PrivacyListDialogMode.Blocked
                    }
                    IkarRowDivider()
                    PrivacyRow("Исключения", "${settings.alwaysAllowUserIds.size + settings.neverAllowUserIds.size}", Icons.Outlined.Security) {
                        listDialogMode = PrivacyListDialogMode.Exceptions
                    }
                }

                IkarSectionCard {
                    IkarSectionTitle("Безопасность", modifier = Modifier.padding(bottom = 8.dp))
                    PrivacyRow("Код-пароль", if (settings.passcodeLockEnabled) "включено" else "выключено", Icons.Outlined.Lock) {
                        passcodeDialogMode = if (settings.passcodeLockEnabled) {
                            PasscodeDialogMode.Disable
                        } else {
                            PasscodeDialogMode.Enable
                        }
                    }
                    IkarRowDivider()
                    PrivacyRow("Предпросмотр сообщений", if (settings.showMessagePreview) "включено" else "выключено", Icons.Outlined.Visibility) {
                        onUpdate { it.copy(showMessagePreview = !it.showMessagePreview) }
                    }
                }
            }
        }
    }

    passcodeDialogMode?.let { mode ->
        PasscodeDialog(
            mode = mode,
            isSaving = state.isSaving,
            onDismiss = { passcodeDialogMode = null },
            onEnable = { passcode, confirmation ->
                onEnablePasscode(passcode, confirmation)
                passcodeDialogMode = null
            },
            onDisable = { passcode ->
                onDisablePasscode(passcode)
                passcodeDialogMode = null
            }
        )
    }

    listDialogMode?.let { mode ->
        PrivacyUsersDialog(
            mode = mode,
            state = state,
            onDismiss = { listDialogMode = null },
            onUserSearchQueryChanged = onUserSearchQueryChanged,
            onBlockUser = onBlockUser,
            onUnblockUser = onUnblockUser,
            onAlwaysAllowUser = onAlwaysAllowUser,
            onNeverAllowUser = onNeverAllowUser,
            onRemoveAlwaysAllow = onRemoveAlwaysAllow,
            onRemoveNeverAllow = onRemoveNeverAllow
        )
    }
}

private enum class PasscodeDialogMode {
    Enable,
    Disable
}

private enum class PrivacyListDialogMode {
    Blocked,
    Exceptions
}

@Composable
private fun PasscodeDialog(
    mode: PasscodeDialogMode,
    isSaving: Boolean,
    onDismiss: () -> Unit,
    onEnable: (String, String) -> Unit,
    onDisable: (String) -> Unit
) {
    var passcode by remember(mode) { mutableStateOf("") }
    var confirmation by remember(mode) { mutableStateOf("") }
    val isEnable = mode == PasscodeDialogMode.Enable
    val canConfirm = if (isEnable) {
        passcode.length >= 4 && confirmation.length >= 4
    } else {
        passcode.length >= 4
    }

    AlertDialog(
        onDismissRequest = {
            if (!isSaving) {
                onDismiss()
            }
        },
        title = { Text(if (isEnable) "Включить код-пароль" else "Отключить код-пароль") },
        text = {
            Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
                OutlinedTextField(
                    value = passcode,
                    onValueChange = { passcode = it.filter(Char::isDigit).take(12) },
                    singleLine = true,
                    visualTransformation = PasswordVisualTransformation(),
                    keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.NumberPassword),
                    label = { Text(if (isEnable) "Новый код" else "Текущий код") }
                )
                if (isEnable) {
                    OutlinedTextField(
                        value = confirmation,
                        onValueChange = { confirmation = it.filter(Char::isDigit).take(12) },
                        singleLine = true,
                        visualTransformation = PasswordVisualTransformation(),
                        keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.NumberPassword),
                        label = { Text("Повторите код") }
                    )
                }
                Text(
                    text = "Используйте 4-12 цифр.",
                    style = MaterialTheme.typography.bodySmall,
                    color = TelegramInkMuted
                )
            }
        },
        confirmButton = {
            TextButton(
                enabled = !isSaving && canConfirm,
                onClick = {
                    if (isEnable) {
                        onEnable(passcode, confirmation)
                    } else {
                        onDisable(passcode)
                    }
                }
            ) {
                Text(if (isEnable) "Включить" else "Отключить")
            }
        },
        dismissButton = {
            TextButton(enabled = !isSaving, onClick = onDismiss) {
                Text("Отмена")
            }
        }
    )
}

@Composable
private fun PrivacyUsersDialog(
    mode: PrivacyListDialogMode,
    state: PrivacySecurityUiState,
    onDismiss: () -> Unit,
    onUserSearchQueryChanged: (String) -> Unit,
    onBlockUser: (UserSummaryDto) -> Unit,
    onUnblockUser: (String) -> Unit,
    onAlwaysAllowUser: (UserSummaryDto) -> Unit,
    onNeverAllowUser: (UserSummaryDto) -> Unit,
    onRemoveAlwaysAllow: (String) -> Unit,
    onRemoveNeverAllow: (String) -> Unit
) {
    val settings = state.settings ?: return
    AlertDialog(
        onDismissRequest = onDismiss,
        title = {
            Text(
                when (mode) {
                    PrivacyListDialogMode.Blocked -> "Заблокированные пользователи"
                    PrivacyListDialogMode.Exceptions -> "Исключения"
                }
            )
        },
        text = {
            Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
                OutlinedTextField(
                    value = state.userSearchQuery,
                    onValueChange = onUserSearchQueryChanged,
                    singleLine = true,
                    label = { Text("Поиск пользователя") }
                )
                if (state.isSearchingUsers) {
                    CircularProgressIndicator(color = TelegramBlue)
                }
                state.userSearchResults.take(8).forEach { user ->
                    when (mode) {
                        PrivacyListDialogMode.Blocked -> PrivacyUserResultRow(
                            user = user,
                            primaryActionLabel = if (settings.blockedUserIds.contains(user.id)) "Уже заблокирован" else "Заблокировать",
                            primaryEnabled = !settings.blockedUserIds.contains(user.id) && !state.isSaving,
                            onPrimaryClick = { onBlockUser(user) }
                        )

                        PrivacyListDialogMode.Exceptions -> PrivacyUserResultRow(
                            user = user,
                            primaryActionLabel = "Всегда",
                            primaryEnabled = !settings.alwaysAllowUserIds.contains(user.id) && !state.isSaving,
                            onPrimaryClick = { onAlwaysAllowUser(user) },
                            secondaryActionLabel = "Никогда",
                            secondaryEnabled = !settings.neverAllowUserIds.contains(user.id) && !state.isSaving,
                            onSecondaryClick = { onNeverAllowUser(user) }
                        )
                    }
                }
                when (mode) {
                    PrivacyListDialogMode.Blocked -> PrivacyIdList(
                        title = "Сейчас заблокированы",
                        userIds = settings.blockedUserIds,
                        users = settings.blockedUsers,
                        removeLabel = "Разблокировать",
                        isSaving = state.isSaving,
                        onRemove = onUnblockUser
                    )

                    PrivacyListDialogMode.Exceptions -> {
                        PrivacyIdList(
                            title = "Всегда разрешать",
                            userIds = settings.alwaysAllowUserIds,
                            users = settings.alwaysAllowUsers,
                            removeLabel = "Убрать",
                            isSaving = state.isSaving,
                            onRemove = onRemoveAlwaysAllow
                        )
                        PrivacyIdList(
                            title = "Никогда не разрешать",
                            userIds = settings.neverAllowUserIds,
                            users = settings.neverAllowUsers,
                            removeLabel = "Убрать",
                            isSaving = state.isSaving,
                            onRemove = onRemoveNeverAllow
                        )
                    }
                }
            }
        },
        confirmButton = {
            TextButton(onClick = onDismiss) {
                Text("Закрыть")
            }
        }
    )
}

@Composable
private fun PrivacyUserResultRow(
    user: UserSummaryDto,
    primaryActionLabel: String,
    primaryEnabled: Boolean,
    onPrimaryClick: () -> Unit,
    secondaryActionLabel: String? = null,
    secondaryEnabled: Boolean = false,
    onSecondaryClick: (() -> Unit)? = null
) {
    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        Column(modifier = Modifier.weight(1f)) {
            Text(user.displayName, style = MaterialTheme.typography.bodyMedium)
            Text("@${user.username}", style = MaterialTheme.typography.bodySmall, color = TelegramInkMuted)
        }
        TextButton(enabled = primaryEnabled, onClick = onPrimaryClick) {
            Text(primaryActionLabel)
        }
        if (secondaryActionLabel != null && onSecondaryClick != null) {
            TextButton(enabled = secondaryEnabled, onClick = onSecondaryClick) {
                Text(secondaryActionLabel)
            }
        }
    }
}

@Composable
private fun PrivacyIdList(
    title: String,
    userIds: List<String>,
    users: List<UserSummaryDto>,
    removeLabel: String,
    isSaving: Boolean,
    onRemove: (String) -> Unit
) {
    val usersById = remember(users) { users.associateBy { it.id } }
    Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
        Text(title, style = MaterialTheme.typography.labelLarge, color = TelegramBlue)
        if (userIds.isEmpty()) {
            Text("Список пуст.", style = MaterialTheme.typography.bodySmall, color = TelegramInkMuted)
        } else {
            userIds.take(20).forEach { userId ->
                PrivacySavedUserRow(
                    userId = userId,
                    user = usersById[userId],
                    removeLabel = removeLabel,
                    isSaving = isSaving,
                    onRemove = onRemove
                )
            }
        }
    }
}

@Composable
private fun PrivacySavedUserRow(
    userId: String,
    user: UserSummaryDto?,
    removeLabel: String,
    isSaving: Boolean,
    onRemove: (String) -> Unit
) {
    val title = user?.displayName?.takeIf { it.isNotBlank() }
        ?: user?.username?.takeIf { it.isNotBlank() }?.let { "@$it" }
        ?: userId.take(8)
    val subtitle = user?.username?.takeIf { it.isNotBlank() }?.let { "@$it" }
        ?: user?.phoneNumber?.takeIf { !it.isNullOrBlank() }
        ?: userId
    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        AvatarView(
            imageUrl = user?.avatarPath,
            title = title,
            size = 36.dp
        )
        Column(modifier = Modifier.weight(1f)) {
            Text(
                title,
                style = MaterialTheme.typography.bodyMedium,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis
            )
            Text(
                subtitle,
                style = MaterialTheme.typography.bodySmall,
                color = TelegramInkMuted,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis
            )
        }
        TextButton(enabled = !isSaving, onClick = { onRemove(userId) }) {
            Text(removeLabel)
        }
    }
}

@Composable
private fun PrivacyRow(
    title: String,
    value: String,
    icon: ImageVector,
    onClick: (() -> Unit)? = null
) {
    IkarSettingRow(
        title = title,
        subtitle = "Сейчас: $value",
        onClick = onClick,
        leading = {
            Icon(icon, contentDescription = null, tint = TelegramInkMuted)
        }
    )
}

private fun privacyValueLabel(value: String): String = when (value.lowercase()) {
    "everyone" -> "все"
    "contacts" -> "контакты"
    "nobody" -> "никто"
    "enabled" -> "включено"
    "disabled" -> "выключено"
    else -> value
}
