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

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.WindowInsetsSides
import androidx.compose.foundation.layout.fillMaxSize
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.Modifier
import androidx.compose.ui.unit.dp
import com.seven.ikar.kotlin.core.model.PrivacySettingsDto
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,
    onRefreshClick: () -> Unit,
    onBlockedUsersClick: () -> Unit,
    onExceptionsClick: () -> Unit,
    onUpdate: ((PrivacySettingsDto) -> PrivacySettingsDto) -> 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 = "Конфиденциальность и безопасность", 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)) {
                        onUpdate { it.copy(phoneNumberVisibility = nextVisibility(it.phoneNumberVisibility)) }
                    }
                    IkarRowDivider()
                    PrivacyRow("Последняя активность и онлайн", privacyValueLabel(settings.lastSeenVisibility)) {
                        onUpdate { it.copy(lastSeenVisibility = nextVisibility(it.lastSeenVisibility)) }
                    }
                    IkarRowDivider()
                    PrivacyRow("Фотографии профиля", privacyValueLabel(settings.profilePhotoVisibility)) {
                        onUpdate { it.copy(profilePhotoVisibility = nextVisibility(it.profilePhotoVisibility)) }
                    }
                    IkarRowDivider()
                    PrivacyRow("Заблокированные пользователи", "${settings.blockedUserIds.size}") {
                        onBlockedUsersClick()
                    }
                    IkarRowDivider()
                    PrivacyRow("Исключения", "${settings.alwaysAllowUserIds.size + settings.neverAllowUserIds.size}") {
                        onExceptionsClick()
                    }
                }

                IkarSectionCard {
                    IkarSectionTitle("Безопасность", modifier = Modifier.padding(bottom = 8.dp))
                    PrivacyRow("Код-пароль", if (settings.passcodeLockEnabled) "включено" else "выключено") {
                        onUpdate { it.copy(passcodeLockEnabled = !it.passcodeLockEnabled) }
                    }
                    IkarRowDivider()
                    PrivacyRow("Предпросмотр сообщений", if (settings.showMessagePreview) "включено" else "выключено") {
                        onUpdate { it.copy(showMessagePreview = !it.showMessagePreview) }
                    }
                }
            }
            TextButton(enabled = !state.isSaving, onClick = onRefreshClick) {
                Text(if (state.isSaving) "Сохранение..." else "Обновить")
            }
        }
    }
}

@Composable
private fun PrivacyRow(
    title: String,
    value: String,
    onClick: () -> Unit
) {
    IkarSettingRow(
        title = title,
        subtitle = "Сейчас: $value",
        onClick = onClick,
        leading = {
            Text(value.take(1).uppercase(), color = TelegramInkMuted)
        }
    )
}

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