package ru.forbion.f7cloud.feature.mail

import android.content.Intent
import android.net.Uri
import android.provider.Settings
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Checkbox
import androidx.compose.material3.CheckboxDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Switch
import androidx.compose.material3.SwitchDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import ru.forbion.f7cloud.core.designsystem.F7Colors
import ru.forbion.f7cloud.core.designsystem.F7SecondaryButton
import ru.forbion.f7cloud.core.designsystem.f7SwipeFromRightToDismiss

private val MailSettingsCard = Color(0xFFFDFDFD)
private val MailSettingsAccountCard = Color(0xFFE8F5E0)

@Composable
fun MailSettingsSheet(
    visible: Boolean,
    serverUrl: String,
    accounts: List<MailAccount>,
    mailboxes: List<MailMailbox>,
    appSettings: MailAppSettings?,
    appSettingsLoading: Boolean,
    appSettingsSaving: Boolean,
    editingAccountId: Int?,
    accountSettings: MailAccountSettings?,
    accountSettingsLoading: Boolean,
    accountSettingsSaving: Boolean,
    onLoadAppSettings: () -> Unit,
    onAccountClick: (Int) -> Unit,
    onAccountSettingsBack: () -> Unit,
    onSaveAccountSettings: (MailAccountSettings) -> Unit,
    onShowThreadedChange: (Boolean) -> Unit,
    onHighlightExternalChange: (Boolean) -> Unit,
    onRemoveTrustedSender: (MailTrustedSender) -> Unit,
    onCreateTextBlock: (String, String) -> Unit,
    onDeleteTextBlock: (Int) -> Unit,
    onDismiss: () -> Unit,
    onSwipeBack: () -> Unit = onDismiss,
    onOpenSieveFilters: ((Int) -> Unit)? = null,
) {
    if (!visible) return
    LaunchedEffect(visible, editingAccountId) {
        if (visible && editingAccountId == null) {
            onLoadAppSettings()
        }
    }
    Dialog(
        onDismissRequest = onDismiss,
        properties = DialogProperties(usePlatformDefaultWidth = false),
    ) {
        Surface(
            modifier = Modifier
                .fillMaxSize()
                .f7SwipeFromRightToDismiss(onDismiss = onSwipeBack),
            color = F7Colors.Surface,
        ) {
            if (editingAccountId != null) {
                MailAccountSettingsScreen(
                    settings = accountSettings,
                    loading = accountSettingsLoading,
                    saving = accountSettingsSaving,
                    mailboxes = mailboxes.filter { it.accountId == editingAccountId },
                    onBack = onAccountSettingsBack,
                    onSave = onSaveAccountSettings,
                    onOpenSieveFilters = onOpenSieveFilters?.let { open ->
                        { open(editingAccountId) }
                    },
                )
            } else {
                MailAppSettingsScreen(
                    serverUrl = serverUrl,
                    accounts = accounts,
                    appSettings = appSettings,
                    loading = appSettingsLoading,
                    saving = appSettingsSaving,
                    onAccountClick = onAccountClick,
                    onShowThreadedChange = onShowThreadedChange,
                    onHighlightExternalChange = onHighlightExternalChange,
                    onRemoveTrustedSender = onRemoveTrustedSender,
                    onCreateTextBlock = onCreateTextBlock,
                    onDeleteTextBlock = onDeleteTextBlock,
                    onDismiss = onDismiss,
                )
            }
        }
    }
}

@Composable
private fun MailAppSettingsScreen(
    serverUrl: String,
    accounts: List<MailAccount>,
    appSettings: MailAppSettings?,
    loading: Boolean,
    saving: Boolean,
    onAccountClick: (Int) -> Unit,
    onShowThreadedChange: (Boolean) -> Unit,
    onHighlightExternalChange: (Boolean) -> Unit,
    onRemoveTrustedSender: (MailTrustedSender) -> Unit,
    onCreateTextBlock: (String, String) -> Unit,
    onDeleteTextBlock: (Int) -> Unit,
    onDismiss: () -> Unit,
) {
    val context = LocalContext.current
    val baseUrl = serverUrl.trimEnd('/')
    var textBlockDialogOpen by remember { mutableStateOf(false) }
    var textBlockTitle by remember { mutableStateOf("") }
    var textBlockContent by remember { mutableStateOf("") }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(20.dp),
    ) {
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically,
        ) {
            Text(
                "Параметры эл. почты",
                style = MaterialTheme.typography.titleLarge,
                fontWeight = FontWeight.SemiBold,
                color = F7Colors.TextPrimary,
            )
            IconButton(onClick = onDismiss) {
                Text("✕", style = MaterialTheme.typography.titleMedium)
            }
        }
        Spacer(Modifier.height(16.dp))
        if (loading && appSettings == null) {
            Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
                CircularProgressIndicator(color = F7Colors.Primary)
            }
            return
        }
        Column(
            modifier = Modifier
                .weight(1f)
                .verticalScroll(rememberScrollState()),
            verticalArrangement = Arrangement.spacedBy(20.dp),
        ) {
            MailSettingsSectionTitle("Основные")
            F7SecondaryButton(
                text = "Установить как почтовое приложение по умолчанию",
                onClick = {
                    runCatching {
                        context.startActivity(Intent(Settings.ACTION_MANAGE_DEFAULT_APPS_SETTINGS))
                    }.onFailure {
                        val intent = Intent(Intent.ACTION_VIEW, Uri.parse("mailto:"))
                        context.startActivity(Intent.createChooser(intent, "Почтовое приложение"))
                    }
                },
                modifier = Modifier.fillMaxWidth(),
            )
            MailSettingsFormGroup(
                label = "Параметры учётной записи",
            ) {
                if (accounts.isEmpty()) {
                    Text(
                        "Учётные записи не найдены",
                        color = F7Colors.TextSecondary,
                        style = MaterialTheme.typography.bodyMedium,
                        modifier = Modifier.padding(vertical = 8.dp),
                    )
                } else {
                    accounts.forEach { account ->
                        MailSettingsAccountRow(
                            email = account.email.ifBlank { account.name },
                            subtitle = account.name.takeIf { it.isNotBlank() && it != account.email },
                            onClick = { onAccountClick(account.id) },
                        )
                    }
                }
                if (appSettings?.allowNewAccounts != false) {
                    F7SecondaryButton(
                        text = "Добавить учётную запись",
                        onClick = {
                            val url = "$baseUrl/index.php/apps/mail/setup"
                            context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)))
                        },
                        modifier = Modifier.fillMaxWidth(),
                    )
                }
            }

            MailSettingsSectionTitle("Внешний вид")
            MailSettingsSwitchCard(
                label = "Показать все сообщения в ветке",
                description = "Если выключено, будет показано только выбранное сообщение",
                checked = appSettings?.showThreaded == true,
                enabled = !saving,
                onCheckedChange = onShowThreadedChange,
            )

            MailSettingsSectionTitle("Текстовые шаблоны")
            Text(
                "Повторно используемые фрагменты текста, которые можно вставлять в письма",
                style = MaterialTheme.typography.bodySmall,
                color = F7Colors.TextSecondary,
            )
            appSettings?.textBlocks.orEmpty().forEach { block ->
                MailSettingsListRow(
                    title = block.title,
                    subtitle = block.preview.ifBlank { block.content.replace(Regex("<[^>]+>"), " ").trim() },
                    onDelete = { onDeleteTextBlock(block.id) },
                )
            }
            F7SecondaryButton(
                text = "Новый текстовый блок",
                onClick = { textBlockDialogOpen = true },
                modifier = Modifier.fillMaxWidth(),
            )

            MailSettingsSectionTitle("Конфиденциальность")
            MailSettingsFormGroup(label = "Всегда показывать изображения из") {
                val senders = appSettings?.trustedSenders.orEmpty()
                if (senders.isEmpty()) {
                    Text(
                        "Сейчас нет доверенных отправителей.",
                        style = MaterialTheme.typography.bodyMedium,
                        color = F7Colors.TextSecondary,
                        modifier = Modifier.padding(vertical = 8.dp),
                    )
                } else {
                    senders.forEach { sender ->
                        MailSettingsListRow(
                            title = sender.email,
                            subtitle = if (sender.type == "domain") "домен" else "адрес",
                            onDelete = { onRemoveTrustedSender(sender) },
                        )
                    }
                }
            }

            MailSettingsSectionTitle("Безопасность")
            MailSettingsSwitchCard(
                label = "Выделять внешние адреса",
                description = "Управляйте внутренними адресами и доменами, чтобы контакты оставались без пометки",
                checked = appSettings?.highlightExternalAddresses == true,
                enabled = !saving,
                onCheckedChange = onHighlightExternalChange,
            )
            MailSettingsFormGroup(label = "S/MIME") {
                F7SecondaryButton(
                    text = "Управление сертификатами",
                    onClick = {
                        val url = "$baseUrl/index.php/apps/mail"
                        context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)))
                    },
                    modifier = Modifier.fillMaxWidth(),
                )
            }
        }
        if (saving) {
            Spacer(Modifier.height(8.dp))
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.Center,
            ) {
                CircularProgressIndicator(
                    modifier = Modifier.height(20.dp),
                    color = F7Colors.Primary,
                    strokeWidth = 2.dp,
                )
            }
        }
    }

    if (textBlockDialogOpen) {
        Dialog(onDismissRequest = { textBlockDialogOpen = false }) {
            Surface(
                shape = RoundedCornerShape(16.dp),
                color = F7Colors.Surface,
            ) {
                Column(modifier = Modifier.padding(20.dp)) {
                    Text(
                        "Новый текстовый блок",
                        style = MaterialTheme.typography.titleMedium,
                        fontWeight = FontWeight.SemiBold,
                    )
                    Spacer(Modifier.height(12.dp))
                    MailSettingsTextArea(
                        label = "Название",
                        value = textBlockTitle,
                        onValueChange = { textBlockTitle = it },
                        minHeight = 48.dp,
                    )
                    Spacer(Modifier.height(8.dp))
                    MailSettingsTextArea(
                        label = "Содержимое",
                        value = textBlockContent,
                        onValueChange = { textBlockContent = it },
                    )
                    Spacer(Modifier.height(16.dp))
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.spacedBy(8.dp),
                    ) {
                        F7SecondaryButton(
                            text = "Отмена",
                            onClick = {
                                textBlockDialogOpen = false
                                textBlockTitle = ""
                                textBlockContent = ""
                            },
                            modifier = Modifier.weight(1f),
                        )
                        Box(
                            modifier = Modifier
                                .weight(1f)
                                .clip(RoundedCornerShape(100.dp))
                                .background(F7Colors.Primary)
                                .clickable(
                                    enabled = textBlockTitle.isNotBlank() && textBlockContent.isNotBlank(),
                                ) {
                                    onCreateTextBlock(textBlockTitle.trim(), textBlockContent.trim())
                                    textBlockDialogOpen = false
                                    textBlockTitle = ""
                                    textBlockContent = ""
                                }
                                .padding(vertical = 12.dp),
                            contentAlignment = Alignment.Center,
                        ) {
                            Text(
                                "OK",
                                color = F7Colors.TextOnPrimary,
                                fontWeight = FontWeight.SemiBold,
                            )
                        }
                    }
                }
            }
        }
    }
}

@Composable
private fun MailSettingsSectionTitle(title: String) {
    Text(
        title,
        style = MaterialTheme.typography.titleMedium,
        fontWeight = FontWeight.SemiBold,
        color = F7Colors.TextPrimary,
    )
}

@Composable
private fun MailSettingsFormGroup(
    label: String,
    content: @Composable () -> Unit,
) {
    Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
        Text(
            label,
            style = MaterialTheme.typography.labelLarge,
            fontWeight = FontWeight.SemiBold,
            color = F7Colors.TextPrimary,
        )
        Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
            content()
        }
    }
}

@Composable
private fun MailSettingsAccountRow(
    email: String,
    subtitle: String?,
    onClick: () -> Unit,
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .clip(RoundedCornerShape(12.dp))
            .background(MailSettingsAccountCard)
            .clickable(onClick = onClick)
            .padding(horizontal = 16.dp, vertical = 14.dp),
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.SpaceBetween,
    ) {
        Column(modifier = Modifier.weight(1f)) {
            Text(
                email,
                style = MaterialTheme.typography.bodyLarge,
                fontWeight = FontWeight.Medium,
            )
            if (!subtitle.isNullOrBlank()) {
                Text(
                    subtitle,
                    style = MaterialTheme.typography.bodySmall,
                    color = F7Colors.TextSecondary,
                )
            }
        }
        Text("›", color = F7Colors.TextSecondary)
    }
}

@Composable
private fun MailSettingsSwitchCard(
    label: String,
    description: String? = null,
    checked: Boolean,
    enabled: Boolean = true,
    onCheckedChange: (Boolean) -> Unit,
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .clip(RoundedCornerShape(12.dp))
            .background(MailSettingsCard)
            .border(1.dp, F7Colors.Border, RoundedCornerShape(12.dp))
            .clickable(enabled = enabled) { onCheckedChange(!checked) }
            .padding(horizontal = 14.dp, vertical = 12.dp),
        verticalAlignment = Alignment.CenterVertically,
    ) {
        Column(modifier = Modifier.weight(1f)) {
            Text(label, style = MaterialTheme.typography.bodyMedium, color = F7Colors.TextPrimary)
            if (!description.isNullOrBlank()) {
                Spacer(Modifier.height(4.dp))
                Text(description, style = MaterialTheme.typography.bodySmall, color = F7Colors.TextSecondary)
            }
        }
        Switch(
            checked = checked,
            onCheckedChange = onCheckedChange,
            enabled = enabled,
            colors = SwitchDefaults.colors(
                checkedThumbColor = Color.White,
                checkedTrackColor = F7Colors.Primary,
            ),
        )
    }
}

@Composable
private fun MailSettingsListRow(
    title: String,
    subtitle: String? = null,
    onDelete: () -> Unit,
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .clip(RoundedCornerShape(12.dp))
            .background(MailSettingsCard)
            .border(1.dp, F7Colors.Border, RoundedCornerShape(12.dp))
            .padding(start = 14.dp, end = 4.dp, top = 10.dp, bottom = 10.dp),
        verticalAlignment = Alignment.CenterVertically,
    ) {
        Column(modifier = Modifier.weight(1f)) {
            Text(
                title,
                style = MaterialTheme.typography.bodyMedium,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis,
            )
            if (!subtitle.isNullOrBlank()) {
                Text(
                    subtitle,
                    style = MaterialTheme.typography.bodySmall,
                    color = F7Colors.TextSecondary,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis,
                )
            }
        }
        IconButton(onClick = onDelete) {
            Text("✕", color = F7Colors.TextSecondary)
        }
    }
}

@Composable
private fun MailAccountSettingsScreen(
    settings: MailAccountSettings?,
    loading: Boolean,
    saving: Boolean,
    mailboxes: List<MailMailbox>,
    onBack: () -> Unit,
    onSave: (MailAccountSettings) -> Unit,
    onOpenSieveFilters: (() -> Unit)? = null,
) {
    var draft by remember { mutableStateOf<MailAccountSettings?>(null) }
    LaunchedEffect(settings) {
        if (settings != null) draft = settings
    }
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(20.dp),
    ) {
        Row(
            modifier = Modifier.fillMaxWidth(),
            verticalAlignment = Alignment.CenterVertically,
        ) {
            IconButton(onClick = onBack) {
                Text("‹", style = MaterialTheme.typography.headlineSmall)
            }
            Text(
                "Параметры учётной записи",
                style = MaterialTheme.typography.titleLarge,
                fontWeight = FontWeight.SemiBold,
                color = F7Colors.TextPrimary,
                modifier = Modifier.weight(1f),
            )
        }
        if (loading || draft == null) {
            Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
                CircularProgressIndicator(color = F7Colors.Primary)
            }
            return
        }
        Column(
            modifier = Modifier
                .weight(1f)
                .verticalScroll(rememberScrollState()),
            verticalArrangement = Arrangement.spacedBy(12.dp),
        ) {
            MailSettingsInfoRow("Email", draft!!.email)
            if (draft!!.name.isNotBlank()) {
                MailSettingsInfoRow("Имя", draft!!.name)
            }
            if (!draft!!.imapHost.isNullOrBlank()) {
                MailSettingsInfoRow("IMAP", draft!!.imapHost.orEmpty())
            }
            if (!draft!!.smtpHost.isNullOrBlank()) {
                MailSettingsInfoRow("SMTP", draft!!.smtpHost.orEmpty())
            }
            draft!!.quotaPercentage?.let { quota ->
                MailSettingsInfoRow("Квота", "$quota%")
            }
            onOpenSieveFilters?.let { open ->
                // Sieve-фильтры (паритет живого веба)
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .clip(RoundedCornerShape(10.dp))
                        .background(F7Colors.SurfaceMuted)
                        .clickable(onClick = open)
                        .padding(horizontal = 12.dp, vertical = 10.dp),
                    verticalAlignment = Alignment.CenterVertically,
                ) {
                    Text(
                        "Фильтры",
                        modifier = Modifier.weight(1f),
                        style = MaterialTheme.typography.bodyMedium,
                        fontWeight = FontWeight.Medium,
                        color = F7Colors.TextPrimary,
                    )
                    Text("›", style = MaterialTheme.typography.titleMedium, color = F7Colors.TextSecondary)
                }
            }
            MailSettingsTextArea(
                label = "Подпись",
                value = draft!!.signature,
                onValueChange = { draft = draft!!.copy(signature = it) },
            )
            MailSettingsMailboxPicker(
                label = "Черновики",
                mailboxes = mailboxes,
                selectedId = draft!!.draftsMailboxId,
                onSelected = { draft = draft!!.copy(draftsMailboxId = it) },
            )
            MailSettingsMailboxPicker(
                label = "Отправленные",
                mailboxes = mailboxes,
                selectedId = draft!!.sentMailboxId,
                onSelected = { draft = draft!!.copy(sentMailboxId = it) },
            )
            MailSettingsMailboxPicker(
                label = "Корзина",
                mailboxes = mailboxes,
                selectedId = draft!!.trashMailboxId,
                onSelected = { draft = draft!!.copy(trashMailboxId = it) },
            )
            MailSettingsMailboxPicker(
                label = "Архив",
                mailboxes = mailboxes,
                selectedId = draft!!.archiveMailboxId,
                onSelected = { draft = draft!!.copy(archiveMailboxId = it) },
            )
            MailSettingsMailboxPicker(
                label = "Спам",
                mailboxes = mailboxes,
                selectedId = draft!!.junkMailboxId,
                onSelected = { draft = draft!!.copy(junkMailboxId = it) },
            )
            MailSettingsToggleRow(
                label = "Искать в теле письма",
                checked = draft!!.searchBody,
                onCheckedChange = { draft = draft!!.copy(searchBody = it) },
            )
            MailSettingsToggleRow(
                label = "Приоритетные входящие",
                checked = draft!!.classificationEnabled,
                onCheckedChange = { draft = draft!!.copy(classificationEnabled = it) },
            )
            MailSettingsToggleRow(
                label = "Подпись над цитатой",
                checked = draft!!.signatureAboveQuote,
                onCheckedChange = { draft = draft!!.copy(signatureAboveQuote = it) },
            )
            MailSettingsToggleRow(
                label = "Создавать события из приглашений",
                checked = draft!!.imipCreate,
                onCheckedChange = { draft = draft!!.copy(imipCreate = it) },
            )
        }
        Spacer(Modifier.height(12.dp))
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .clip(RoundedCornerShape(100.dp))
                .background(F7Colors.Primary)
                .clickable(enabled = !saving) { onSave(draft!!) }
                .padding(vertical = 14.dp),
            horizontalArrangement = Arrangement.Center,
        ) {
            if (saving) {
                CircularProgressIndicator(
                    modifier = Modifier.height(20.dp),
                    color = F7Colors.TextOnPrimary,
                    strokeWidth = 2.dp,
                )
            } else {
                Text(
                    "Сохранить",
                    style = MaterialTheme.typography.labelLarge,
                    fontWeight = FontWeight.SemiBold,
                    color = F7Colors.TextOnPrimary,
                )
            }
        }
    }
}

@Composable
private fun MailSettingsInfoRow(label: String, value: String) {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .clip(RoundedCornerShape(12.dp))
            .background(MailSettingsCard)
            .border(1.dp, F7Colors.Border, RoundedCornerShape(12.dp))
            .padding(horizontal = 14.dp, vertical = 12.dp),
    ) {
        Text(label, style = MaterialTheme.typography.labelMedium, color = F7Colors.TextSecondary)
        Spacer(Modifier.height(4.dp))
        Text(value, style = MaterialTheme.typography.bodyMedium, color = F7Colors.TextPrimary)
    }
}

@Composable
private fun MailSettingsTextArea(
    label: String,
    value: String,
    onValueChange: (String) -> Unit,
    minHeight: androidx.compose.ui.unit.Dp = 80.dp,
) {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .clip(RoundedCornerShape(12.dp))
            .background(MailSettingsCard)
            .border(1.dp, F7Colors.Border, RoundedCornerShape(12.dp))
            .padding(horizontal = 14.dp, vertical = 12.dp),
    ) {
        Text(label, style = MaterialTheme.typography.labelMedium, color = F7Colors.TextSecondary)
        Spacer(Modifier.height(6.dp))
        androidx.compose.foundation.text.BasicTextField(
            value = value,
            onValueChange = onValueChange,
            modifier = Modifier
                .fillMaxWidth()
                .heightIn(min = minHeight),
            textStyle = MaterialTheme.typography.bodyMedium.copy(color = F7Colors.TextPrimary),
        )
    }
}

@Composable
private fun MailSettingsToggleRow(
    label: String,
    checked: Boolean,
    onCheckedChange: (Boolean) -> Unit,
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .clip(RoundedCornerShape(12.dp))
            .background(MailSettingsCard)
            .border(1.dp, F7Colors.Border, RoundedCornerShape(12.dp))
            .clickable { onCheckedChange(!checked) }
            .padding(horizontal = 8.dp, vertical = 4.dp),
        verticalAlignment = Alignment.CenterVertically,
    ) {
        Checkbox(
            checked = checked,
            onCheckedChange = onCheckedChange,
            colors = CheckboxDefaults.colors(checkedColor = F7Colors.Primary),
        )
        Text(
            label,
            style = MaterialTheme.typography.bodyMedium,
            color = F7Colors.TextPrimary,
            modifier = Modifier.weight(1f),
        )
    }
}

@Composable
private fun MailSettingsMailboxPicker(
    label: String,
    mailboxes: List<MailMailbox>,
    selectedId: Int?,
    onSelected: (Int?) -> Unit,
) {
    var expanded by remember { mutableStateOf(false) }
    val selectedName = mailboxes.firstOrNull { it.id == selectedId }?.displayName ?: "Не выбрано"
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .clip(RoundedCornerShape(12.dp))
            .background(MailSettingsCard)
            .border(1.dp, F7Colors.Border, RoundedCornerShape(12.dp))
            .clickable { expanded = true }
            .padding(horizontal = 14.dp, vertical = 12.dp),
    ) {
        Text(label, style = MaterialTheme.typography.labelMedium, color = F7Colors.TextSecondary)
        Spacer(Modifier.height(4.dp))
        Text(
            selectedName,
            style = MaterialTheme.typography.bodyMedium,
            color = F7Colors.TextPrimary,
            maxLines = 1,
            overflow = TextOverflow.Ellipsis,
        )
        DropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) {
            DropdownMenuItem(
                text = { Text("Не выбрано") },
                onClick = {
                    onSelected(null)
                    expanded = false
                },
            )
            mailboxes.forEach { mailbox ->
                DropdownMenuItem(
                    text = { Text(mailbox.displayName) },
                    onClick = {
                        onSelected(mailbox.id)
                        expanded = false
                    },
                )
            }
        }
    }
}
