package ru.forbion.f7cloud.feature.mail

import android.app.Activity
import android.app.DatePickerDialog
import android.app.TimePickerDialog
import android.widget.Toast
import androidx.activity.compose.BackHandler
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.interaction.MutableInteractionSource
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.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Popup
import androidx.compose.ui.window.PopupProperties
import coil.compose.AsyncImage
import ru.forbion.f7cloud.core.auth.AuthSession
import ru.forbion.f7cloud.core.designsystem.F7Colors
import ru.forbion.f7cloud.core.designsystem.f7SwipeFromRightToDismiss
import java.time.LocalDateTime

@Composable
fun MailComposeScreen(
    session: AuthSession,
    launch: MailComposeLaunch,
    vm: MailComposeViewModel,
    onClose: () -> Unit,
    onUnauthorized: () -> Unit,
    modifier: Modifier = Modifier,
) {
    val state by vm.state.collectAsState()
    val context = LocalContext.current
    val editor = remember { MailRichTextEditorController() }
    val base = session.serverUrl.trimEnd('/')
    val pickAttachmentsLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.OpenMultipleDocuments(),
    ) { uris ->
        if (uris.isNotEmpty()) {
            vm.addAttachmentsFromUris(context, session, uris, onUnauthorized)
        }
    }
    val filesPickerLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.StartActivityForResult(),
    ) { result ->
        if (result.resultCode == Activity.RESULT_OK) {
            result.data?.let { data ->
                vm.handleFilesPickResult(data, session, editor, onUnauthorized)
            }
        } else {
            vm.cancelFilesPick()
        }
    }

    LaunchedEffect(session.serverUrl, session.username) {
        vm.initContacts(session)
    }

    LaunchedEffect(state.finished) {
        if (state.finished) {
            Toast.makeText(context, "Письмо отправлено", Toast.LENGTH_SHORT).show()
            onClose()
        }
    }

    LaunchedEffect(launch.initialBodyHtml) {
        if (launch.initialBodyHtml.isNotBlank()) {
            editor.setHtml(launch.initialBodyHtml)
        }
    }

    LaunchedEffect(state.error) {
        state.error?.let { Toast.makeText(context, it, Toast.LENGTH_SHORT).show() }
    }

    val composeNavigateBack: () -> Boolean = {
        navigateMailComposeBack(
            state = MailComposeBackStackState(
                attachmentMenuOpen = state.attachmentMenuOpen,
                sendLaterMenuOpen = state.sendLaterMenuOpen,
                moreMenuOpen = state.moreMenuOpen,
                toolbarVisible = state.toolbarVisible,
            ),
            closeAttachmentMenu = { vm.setAttachmentMenuOpen(false) },
            closeSendLaterMenu = { vm.setSendLaterMenuOpen(false) },
            closeMoreMenu = { vm.setMoreMenuOpen(false) },
            closeToolbar = { vm.toggleToolbar() },
            closeScreen = onClose,
        )
    }

    BackHandler { composeNavigateBack() }

    Column(
        modifier = modifier
            .fillMaxSize()
            .background(F7Colors.Surface)
            .f7SwipeFromRightToDismiss(onDismiss = { composeNavigateBack() }),
    ) {
        MailComposeHeader(
            senderLabel = vm.senderLabel,
            title = when (launch.mode) {
                MailComposeMode.REPLY -> "Ответить на сообщение"
                MailComposeMode.REPLY_ALL -> "Ответить всем"
                MailComposeMode.FORWARD -> "Переслать сообщение"
                MailComposeMode.NEW -> "Новое сообщение"
            },
            serverUrl = session.serverUrl,
            onClose = onClose,
        )
        MailRecipientComposeField(
            label = "Кому:",
            value = state.to,
            onValueChange = vm::setTo,
            suggestions = if (state.activeRecipientField == MailRecipientField.TO) {
                state.recipientSuggestions
            } else {
                emptyList()
            },
            showSuggestions = state.activeRecipientField == MailRecipientField.TO,
            onSuggestionClick = { vm.selectSuggestion(MailRecipientField.TO, it) },
            onDismissSuggestions = vm::dismissSuggestions,
            trailingIconUrl = "$base/themes/forbion/images/mail/nav-chevron-down-gray.svg",
            onTrailingClick = vm::toggleCcBcc,
        )
        if (state.showCcBcc) {
            MailRecipientComposeField(
                label = "Копия:",
                value = state.cc,
                onValueChange = vm::setCc,
                suggestions = if (state.activeRecipientField == MailRecipientField.CC) {
                    state.recipientSuggestions
                } else {
                    emptyList()
                },
                showSuggestions = state.activeRecipientField == MailRecipientField.CC,
                onSuggestionClick = { vm.selectSuggestion(MailRecipientField.CC, it) },
                onDismissSuggestions = vm::dismissSuggestions,
            )
            MailRecipientComposeField(
                label = "Скрытая копия:",
                value = state.bcc,
                onValueChange = vm::setBcc,
                suggestions = if (state.activeRecipientField == MailRecipientField.BCC) {
                    state.recipientSuggestions
                } else {
                    emptyList()
                },
                showSuggestions = state.activeRecipientField == MailRecipientField.BCC,
                onSuggestionClick = { vm.selectSuggestion(MailRecipientField.BCC, it) },
                onDismissSuggestions = vm::dismissSuggestions,
            )
        }
        MailComposeField(
            label = "Тема сообщения",
            value = state.subject,
            onValueChange = vm::setSubject,
        )
        if (state.attachments.isNotEmpty()) {
            MailComposeAttachmentsRow(
                serverUrl = session.serverUrl,
                attachments = state.attachments,
                onRemove = vm::removeAttachment,
            )
        }
        Box(
            modifier = Modifier
                .weight(1f)
                .fillMaxWidth()
                .padding(horizontal = 12.dp)
                .clip(RoundedCornerShape(8.dp))
                .border(1.dp, F7Colors.Border, RoundedCornerShape(8.dp))
                .background(Color.White),
        ) {
            MailRichTextEditor(
                modifier = Modifier.fillMaxSize(),
                controller = editor,
            )
            Box(
                modifier = Modifier
                    .align(Alignment.BottomEnd)
                    .padding(10.dp),
            ) {
                if (state.attachmentMenuOpen) {
                    MailComposeAttachmentMenu(
                        serverUrl = session.serverUrl,
                        onUploadFromDevice = {
                            vm.setAttachmentMenuOpen(false)
                            pickAttachmentsLauncher.launch(arrayOf("*/*"))
                        },
                        onPickFromFiles = {
                            vm.prepareFilesPick(MailFilesPickMode.ATTACHMENT)
                            vm.filesPickIntent(context, session)?.let(filesPickerLauncher::launch)
                        },
                        onAddShareLink = {
                            vm.prepareFilesPick(MailFilesPickMode.SHARE_LINK)
                            vm.filesPickIntent(context, session)?.let(filesPickerLauncher::launch)
                        },
                        onDismiss = { vm.setAttachmentMenuOpen(false) },
                    )
                }
                Box(
                    modifier = Modifier
                        .size(32.dp)
                        .clickable(
                            enabled = !state.uploadingAttachments,
                            interactionSource = remember { MutableInteractionSource() },
                            indication = null,
                            onClick = { vm.setAttachmentMenuOpen(!state.attachmentMenuOpen) },
                        ),
                    contentAlignment = Alignment.Center,
                ) {
                    if (state.uploadingAttachments) {
                        CircularProgressIndicator(
                            modifier = Modifier.size(18.dp),
                            color = F7Colors.Primary,
                            strokeWidth = 2.dp,
                        )
                    } else {
                        AsyncImage(
                            model = "$base/themes/forbion/images/mail/file-up-gray.svg",
                            contentDescription = "Вложение",
                            modifier = Modifier.size(20.dp),
                            contentScale = ContentScale.Fit,
                        )
                    }
                }
            }
        }
        Spacer(Modifier.height(8.dp))
        if (state.toolbarVisible) {
            MailComposeFormattingToolbar(
                serverUrl = session.serverUrl,
                onCommand = { command, value -> editor.exec(command, value) },
            )
        }
        MailComposeBottomBar(
            serverUrl = session.serverUrl,
            sending = state.sending,
            moreMenuOpen = state.moreMenuOpen,
            sendLaterMenuOpen = state.sendLaterMenuOpen,
            requestMdn = state.requestMdn,
            sendLaterOptions = vm.sendLaterOptions,
            selectedSendPreset = state.selectedSendPreset,
            customSendAt = state.customSendAt,
            onToggleToolbar = vm::toggleToolbar,
            onMoreMenuOpenChange = vm::setMoreMenuOpen,
            onSendLaterMenuOpenChange = vm::setSendLaterMenuOpen,
            onToggleRequestMdn = vm::toggleRequestMdn,
            onSelectSendPreset = vm::selectSendPreset,
            onCustomSendAtChange = vm::setCustomSendAt,
            onSend = { vm.send(session, editor, onUnauthorized) },
        )
    }
}

@Composable
private fun MailComposeHeader(
    senderLabel: String,
    title: String,
    serverUrl: String,
    onClose: () -> Unit,
) {
    val base = serverUrl.trimEnd('/')
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .background(F7Colors.Surface)
            .padding(bottom = 8.dp),
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 12.dp, vertical = 12.dp),
            verticalAlignment = Alignment.CenterVertically,
        ) {
            Box(
                modifier = Modifier
                    .size(40.dp)
                    .clip(CircleShape)
                    .clickable(onClick = onClose),
                contentAlignment = Alignment.Center,
            ) {
                AsyncImage(
                    model = "$base/themes/forbion/images/mail/arrow-back-gray.svg",
                    contentDescription = "Назад",
                    modifier = Modifier.size(20.dp),
                    contentScale = ContentScale.Fit,
                )
            }
            Column(modifier = Modifier.weight(1f).padding(horizontal = 8.dp)) {
                Text(
                    title,
                    style = MaterialTheme.typography.bodyLarge,
                    fontWeight = FontWeight.SemiBold,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis,
                )
                Spacer(Modifier.height(2.dp))
                Text(
                    senderLabel,
                    style = MaterialTheme.typography.bodySmall,
                    color = F7Colors.TextSecondary,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis,
                )
            }
            Box(
                modifier = Modifier
                    .size(40.dp)
                    .clip(CircleShape)
                    .clickable(onClick = onClose),
                contentAlignment = Alignment.Center,
            ) {
                AsyncImage(
                    model = "$base/themes/forbion/images/mail/close-icon-gray.svg",
                    contentDescription = "Закрыть",
                    modifier = Modifier.size(18.dp),
                    contentScale = ContentScale.Fit,
                )
            }
        }
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .height(1.dp)
                .background(F7Colors.Border.copy(alpha = 0.5f)),
        )
    }
}

@Composable
private fun MailComposeAttachmentsRow(
    serverUrl: String,
    attachments: List<MailComposeAttachment>,
    onRemove: (Int) -> Unit,
) {
    val base = serverUrl.trimEnd('/')
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 12.dp, vertical = 4.dp),
    ) {
        Text(
            "Вложения: ${attachments.size}",
            style = MaterialTheme.typography.labelMedium,
            color = F7Colors.TextSecondary,
        )
        Spacer(Modifier.height(6.dp))
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .horizontalScroll(rememberScrollState()),
            horizontalArrangement = Arrangement.spacedBy(8.dp),
        ) {
            attachments.forEach { attachment ->
                Row(
                    modifier = Modifier
                        .clip(RoundedCornerShape(100.dp))
                        .background(F7Colors.PrimaryLight)
                        .border(1.dp, F7Colors.Border, RoundedCornerShape(100.dp))
                        .padding(start = 10.dp, end = 6.dp, top = 6.dp, bottom = 6.dp),
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.spacedBy(6.dp),
                ) {
                    AsyncImage(
                        model = when (attachment.type) {
                            MailComposeAttachmentType.CLOUD ->
                                "$base/themes/forbion/images/mail/folder-add-black.svg"
                            MailComposeAttachmentType.LOCAL ->
                                "$base/themes/forbion/images/mail/file-up-gray.svg"
                        },
                        contentDescription = null,
                        modifier = Modifier.size(14.dp),
                        contentScale = ContentScale.Fit,
                    )
                    Text(
                        attachment.fileName,
                        maxLines = 1,
                        overflow = TextOverflow.Ellipsis,
                        fontSize = 13.sp,
                        modifier = Modifier.widthIn(max = 180.dp),
                    )
                    AsyncImage(
                        model = "$base/themes/forbion/images/mail/close-icon-gray.svg",
                        contentDescription = "Удалить",
                        modifier = Modifier
                            .size(14.dp)
                            .clickable { onRemove(attachment.id) },
                        contentScale = ContentScale.Fit,
                    )
                }
            }
        }
    }
}

@Composable
private fun MailComposeField(
    label: String,
    value: String,
    onValueChange: (String) -> Unit,
    trailingIconUrl: String? = null,
    onTrailingClick: (() -> Unit)? = null,
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 12.dp, vertical = 4.dp)
            .clip(RoundedCornerShape(8.dp))
            .border(1.dp, F7Colors.Border, RoundedCornerShape(8.dp))
            .background(Color.White)
            .padding(horizontal = 12.dp, vertical = 10.dp),
        verticalAlignment = Alignment.CenterVertically,
    ) {
        BasicTextField(
            value = value,
            onValueChange = onValueChange,
            modifier = Modifier.weight(1f),
            textStyle = TextStyle(fontSize = 14.sp, lineHeight = 20.sp, color = F7Colors.TextPrimary),
            cursorBrush = SolidColor(F7Colors.Primary),
            decorationBox = { inner ->
                if (value.isEmpty()) {
                    Text(label, color = F7Colors.TextSecondary, fontSize = 14.sp)
                }
                inner()
            },
        )
        if (trailingIconUrl != null && onTrailingClick != null) {
            AsyncImage(
                model = trailingIconUrl,
                contentDescription = null,
                modifier = Modifier
                    .size(16.dp)
                    .clickable(onClick = onTrailingClick),
                contentScale = ContentScale.Fit,
            )
        }
    }
}

@Composable
private fun MailComposeFormattingToolbar(
    serverUrl: String,
    onCommand: (String, String?) -> Unit,
) {
    val base = serverUrl.trimEnd('/')
    val scroll = rememberScrollState()
    val row1 = listOf(
        ToolbarAction("bold", "$base/themes/forbion/images/mail/text-bold-black.svg"),
        ToolbarAction("italic", "$base/themes/forbion/images/mail/text-italic-black.svg"),
        ToolbarAction("underline", "$base/themes/forbion/images/mail/text-color-black.svg"),
        ToolbarAction("strikeThrough", "$base/themes/forbion/images/mail/text-cross-out-black.svg"),
        ToolbarAction("insertUnorderedList", "$base/themes/forbion/images/mail/text-ul-black.svg"),
        ToolbarAction("insertOrderedList", "$base/themes/forbion/images/mail/text-ol-black.svg"),
        ToolbarAction("justifyLeft", "$base/themes/forbion/images/mail/text-left-black.svg"),
    )
    val row2 = listOf(
        ToolbarAction("formatBlock", "$base/themes/forbion/images/mail/text-editor-font-black.svg", "p"),
        ToolbarAction("indent", "$base/themes/forbion/images/mail/text-kov-black.svg"),
        ToolbarAction("outdent", "$base/themes/forbion/images/mail/text-upper-black.svg"),
        ToolbarAction("removeFormat", "$base/themes/forbion/images/mail/clear-icon-black.svg"),
        ToolbarAction("undo", "$base/themes/forbion/images/mail/arrow-back-gray.svg"),
        ToolbarAction("redo", "$base/themes/forbion/images/mail/reply-left-gray.svg"),
    )
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 12.dp)
            .shadow(1.dp, RoundedCornerShape(8.dp), spotColor = F7Colors.Border)
            .clip(RoundedCornerShape(8.dp))
            .border(1.dp, F7Colors.Border, RoundedCornerShape(8.dp))
            .background(Color(0xFFFDFDFD))
            .padding(4.dp),
        verticalArrangement = Arrangement.spacedBy(6.dp),
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .horizontalScroll(scroll),
            horizontalArrangement = Arrangement.spacedBy(8.dp),
        ) {
            row1.forEach { action ->
                ToolbarIcon(action, onCommand)
            }
        }
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .horizontalScroll(rememberScrollState()),
            horizontalArrangement = Arrangement.spacedBy(8.dp),
        ) {
            row2.forEach { action ->
                ToolbarIcon(action, onCommand)
            }
        }
    }
}

private data class ToolbarAction(
    val command: String,
    val iconUrl: String,
    val value: String? = null,
)

@Composable
private fun ToolbarIcon(
    action: ToolbarAction,
    onCommand: (String, String?) -> Unit,
) {
    Box(
        modifier = Modifier
            .size(32.dp)
            .clip(RoundedCornerShape(6.dp))
            .clickable { onCommand(action.command, action.value) },
        contentAlignment = Alignment.Center,
    ) {
        AsyncImage(
            model = action.iconUrl,
            contentDescription = null,
            modifier = Modifier.size(18.dp),
            contentScale = ContentScale.Fit,
        )
    }
}

@Composable
private fun MailComposeBottomBar(
    serverUrl: String,
    sending: Boolean,
    moreMenuOpen: Boolean,
    sendLaterMenuOpen: Boolean,
    requestMdn: Boolean,
    sendLaterOptions: List<MailSendLaterOption>,
    selectedSendPreset: MailSendLaterPreset,
    customSendAt: LocalDateTime,
    onToggleToolbar: () -> Unit,
    onMoreMenuOpenChange: (Boolean) -> Unit,
    onSendLaterMenuOpenChange: (Boolean) -> Unit,
    onToggleRequestMdn: () -> Unit,
    onSelectSendPreset: (MailSendLaterPreset) -> Unit,
    onCustomSendAtChange: (LocalDateTime) -> Unit,
    onSend: () -> Unit,
) {
    val base = serverUrl.trimEnd('/')
    val context = LocalContext.current
    Box {
        if (moreMenuOpen) {
            MailComposeMoreMenu(
                serverUrl = serverUrl,
                requestMdn = requestMdn,
                onToggleRequestMdn = onToggleRequestMdn,
                onSendLaterClick = {
                    onMoreMenuOpenChange(false)
                    onSendLaterMenuOpenChange(true)
                },
                onDismiss = { onMoreMenuOpenChange(false) },
            )
        }
        if (sendLaterMenuOpen) {
            MailComposeSendLaterMenu(
                options = sendLaterOptions,
                selectedPreset = selectedSendPreset,
                customSendAt = customSendAt,
                onSelectPreset = onSelectSendPreset,
                onCustomSendAtChange = onCustomSendAtChange,
                onDismiss = { onSendLaterMenuOpenChange(false) },
            )
        }
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .background(F7Colors.Surface)
                .padding(horizontal = 12.dp, vertical = 10.dp),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.spacedBy(10.dp),
        ) {
            Box(
                modifier = Modifier
                    .size(40.dp)
                    .clip(RoundedCornerShape(100.dp))
                    .clickable(onClick = onToggleToolbar),
                contentAlignment = Alignment.Center,
            ) {
                AsyncImage(
                    model = "$base/themes/forbion/images/format-size-icon.svg",
                    contentDescription = "Форматирование",
                    modifier = Modifier.size(22.dp),
                    contentScale = ContentScale.Fit,
                )
            }
            Box(
                modifier = Modifier
                    .size(40.dp)
                    .clip(RoundedCornerShape(100.dp))
                    .clickable { onMoreMenuOpenChange(!moreMenuOpen) },
                contentAlignment = Alignment.Center,
            ) {
                AsyncImage(
                    model = "$base/themes/forbion/images/mail/dots-icon-black.svg",
                    contentDescription = "Ещё",
                    modifier = Modifier.size(20.dp),
                    contentScale = ContentScale.Fit,
                )
            }
            Box(
                modifier = Modifier
                    .weight(1f)
                    .height(44.dp)
                    .shadow(4.dp, RoundedCornerShape(100.dp), spotColor = F7Colors.Primary.copy(alpha = 0.2f))
                    .clip(RoundedCornerShape(100.dp))
                    .background(
                        Brush.linearGradient(
                            listOf(F7Colors.PrimaryGradientStart, F7Colors.PrimaryGradientEnd),
                        ),
                    )
                    .border(1.dp, F7Colors.Primary.copy(alpha = 0.22f), RoundedCornerShape(100.dp))
                    .clickable(enabled = !sending, onClick = onSend),
                contentAlignment = Alignment.Center,
            ) {
                if (sending) {
                    CircularProgressIndicator(
                        modifier = Modifier.size(20.dp),
                        color = Color.White,
                        strokeWidth = 2.dp,
                    )
                } else {
                    Row(
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.spacedBy(8.dp),
                    ) {
                        AsyncImage(
                            model = "$base/themes/forbion/images/mail/send-message-white.svg",
                            contentDescription = null,
                            modifier = Modifier.size(18.dp),
                            contentScale = ContentScale.Fit,
                        )
                        Text(
                            "Отправить",
                            color = Color.White,
                            fontWeight = FontWeight.SemiBold,
                            fontSize = 15.sp,
                        )
                    }
                }
            }
        }
    }
}

@Composable
private fun MailComposeAttachmentMenu(
    serverUrl: String,
    onUploadFromDevice: () -> Unit,
    onPickFromFiles: () -> Unit,
    onAddShareLink: () -> Unit,
    onDismiss: () -> Unit,
) {
    val base = serverUrl.trimEnd('/')
    Popup(
        alignment = Alignment.BottomEnd,
        onDismissRequest = onDismiss,
        properties = PopupProperties(focusable = true),
    ) {
        Column(
            modifier = Modifier
                .padding(end = 4.dp, bottom = 40.dp)
                .width(320.dp)
                .clip(RoundedCornerShape(12.dp))
                .background(Color.White)
                .border(1.dp, F7Colors.Border, RoundedCornerShape(12.dp))
                .padding(vertical = 6.dp),
        ) {
            MailComposeMenuRow(
                iconUrl = "$base/themes/forbion/images/mail/file-up-gray.svg",
                title = "Загрузить файл с телефона",
                onClick = onUploadFromDevice,
            )
            MailComposeMenuRow(
                iconUrl = "$base/themes/forbion/images/mail/folder-add-black.svg",
                title = "Из приложения «Файлы»",
                onClick = onPickFromFiles,
            )
            MailComposeMenuRow(
                iconUrl = "$base/themes/forbion/images/mail/sharing-icon-black.svg",
                title = "Добавить ссылку для общего доступа из Файлов",
                onClick = onAddShareLink,
            )
        }
    }
}

@Composable
private fun MailComposeMoreMenu(
    serverUrl: String,
    requestMdn: Boolean,
    onToggleRequestMdn: () -> Unit,
    onSendLaterClick: () -> Unit,
    onDismiss: () -> Unit,
) {
    val base = serverUrl.trimEnd('/')
    Popup(
        alignment = Alignment.BottomStart,
        onDismissRequest = onDismiss,
        properties = PopupProperties(focusable = true),
    ) {
        Column(
            modifier = Modifier
                .padding(start = 12.dp, bottom = 72.dp)
                .width(300.dp)
                .clip(RoundedCornerShape(12.dp))
                .background(Color.White)
                .border(1.dp, F7Colors.Border, RoundedCornerShape(12.dp))
                .padding(vertical = 6.dp),
        ) {
            MailComposeMenuRow(
                iconUrl = "$base/themes/forbion/images/send-clock-icon.svg",
                title = "Отправить позже",
                onClick = onSendLaterClick,
            )
            MailComposeMenuRow(
                iconUrl = if (requestMdn) {
                    "$base/themes/forbion/images/mail/checkbox-checked-green.svg"
                } else {
                    "$base/themes/forbion/images/mail/checkbox-outline-gray.svg"
                },
                title = "Запросить подтверждение прочтения",
                onClick = onToggleRequestMdn,
            )
        }
    }
}

@Composable
private fun MailComposeSendLaterMenu(
    options: List<MailSendLaterOption>,
    selectedPreset: MailSendLaterPreset,
    customSendAt: LocalDateTime,
    onSelectPreset: (MailSendLaterPreset) -> Unit,
    onCustomSendAtChange: (LocalDateTime) -> Unit,
    onDismiss: () -> Unit,
) {
    val context = LocalContext.current
    Popup(
        alignment = Alignment.BottomStart,
        onDismissRequest = onDismiss,
        properties = PopupProperties(focusable = true),
    ) {
        Column(
            modifier = Modifier
                .padding(start = 12.dp, bottom = 72.dp)
                .width(320.dp)
                .clip(RoundedCornerShape(12.dp))
                .background(Color.White)
                .border(1.dp, F7Colors.Border, RoundedCornerShape(12.dp))
                .padding(12.dp)
                .verticalScroll(rememberScrollState()),
        ) {
            Text("Отправить позже", fontWeight = FontWeight.SemiBold)
            Spacer(Modifier.height(8.dp))
            options.forEach { option ->
                val selected = option.preset == selectedPreset
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .clip(RoundedCornerShape(8.dp))
                        .background(if (selected) F7Colors.PrimaryLight else Color.Transparent)
                        .clickable { onSelectPreset(option.preset) }
                        .padding(horizontal = 8.dp, vertical = 8.dp),
                ) {
                    Row(verticalAlignment = Alignment.CenterVertically) {
                        Box(
                            modifier = Modifier
                                .size(18.dp)
                                .clip(RoundedCornerShape(100.dp))
                                .border(
                                    2.dp,
                                    if (selected) F7Colors.Primary else F7Colors.Border,
                                    RoundedCornerShape(100.dp),
                                )
                                .background(if (selected) F7Colors.Primary.copy(alpha = 0.15f) else Color.Transparent),
                        )
                        Spacer(Modifier.width(10.dp))
                        Text(option.title, fontSize = 14.sp)
                    }
                    if (option.preset == MailSendLaterPreset.CUSTOM && selected) {
                        Spacer(Modifier.height(8.dp))
                        val formatted = MailComposeSchedule.formatCustom(customSendAt)
                        Box(
                            modifier = Modifier
                                .fillMaxWidth()
                                .clip(RoundedCornerShape(8.dp))
                                .border(1.dp, F7Colors.Border, RoundedCornerShape(8.dp))
                                .clickable {
                                    val date = customSendAt.toLocalDate()
                                    DatePickerDialog(
                                        context,
                                        { _, year, month, day ->
                                            val updatedDate = java.time.LocalDate.of(year, month + 1, day)
                                            TimePickerDialog(
                                                context,
                                                { _, hour, minute ->
                                                    onCustomSendAtChange(
                                                        LocalDateTime.of(updatedDate, java.time.LocalTime.of(hour, minute)),
                                                    )
                                                },
                                                customSendAt.hour,
                                                customSendAt.minute,
                                                true,
                                            ).show()
                                        },
                                        date.year,
                                        date.monthValue - 1,
                                        date.dayOfMonth,
                                    ).show()
                                }
                                .padding(horizontal = 12.dp, vertical = 10.dp),
                        ) {
                            Text(formatted, fontSize = 14.sp)
                        }
                    }
                }
            }
        }
    }
}

@Composable
private fun MailComposeMenuRow(
    iconUrl: String,
    title: String,
    onClick: () -> Unit,
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .clickable(onClick = onClick)
            .padding(horizontal = 14.dp, vertical = 12.dp),
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.spacedBy(12.dp),
    ) {
        AsyncImage(
            model = iconUrl,
            contentDescription = null,
            modifier = Modifier.size(18.dp),
            contentScale = ContentScale.Fit,
        )
        Text(title, fontSize = 14.sp, lineHeight = 18.sp)
    }
}
