package ru.forbion.f7cloud.feature.tasks

import androidx.compose.animation.animateContentSize
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.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
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.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Surface
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.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.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import coil.compose.AsyncImage
import ru.forbion.f7cloud.core.designsystem.F7Colors
import ru.forbion.f7cloud.core.designsystem.F7OutlinedField
import ru.forbion.f7cloud.core.designsystem.F7PrimaryButton
import ru.forbion.f7cloud.core.designsystem.F7SecondaryButton
import ru.forbion.f7cloud.core.designsystem.f7SwipeFromRightToDismiss

private val TasksFieldBg = Color(0xFFFDFDFD)
private val TasksHeadingBg = Color(0xFFF5F5F5)
private val TasksTagBg = Color(0xFFDAEDD6)
private val TasksTagText = Color(0xFF28A413)

internal fun tasksAsset(serverUrl: String, path: String): String =
    "${serverUrl.trimEnd('/')}/themes/forbion/images/tasks/$path"

internal fun themesAsset(serverUrl: String, path: String): String =
    "${serverUrl.trimEnd('/')}/themes/forbion/images/$path"

private fun Modifier.tasksFieldShadow(): Modifier = shadow(
    elevation = 1.dp,
    shape = RoundedCornerShape(4.dp),
    ambientColor = F7Colors.Border,
    spotColor = F7Colors.Border,
)

@Composable
fun TasksToolbar(
    serverUrl: String,
    createExpanded: Boolean,
    createText: String,
    saving: Boolean,
    onCreateTextChange: (String) -> Unit,
    onCreateExpand: () -> Unit,
    onCreateCollapse: () -> Unit,
    onCreateSubmit: () -> Unit,
    onFilterClick: () -> Unit,
    onSortClick: () -> Unit,
    onMoreClick: () -> Unit,
    modifier: Modifier = Modifier,
) {
    Row(
        modifier = modifier
            .fillMaxWidth()
            .padding(bottom = 8.dp)
            .animateContentSize(),
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.spacedBy(8.dp),
    ) {
        Box(
            modifier = Modifier
                .then(
                    if (createExpanded) {
                        Modifier
                            .weight(1f)
                            .height(40.dp)
                            .clip(RoundedCornerShape(8.dp))
                            .background(TasksFieldBg)
                            .tasksFieldShadow()
                    } else {
                        Modifier.size(40.dp)
                    },
                ),
        ) {
            if (createExpanded) {
                Row(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(horizontal = 12.dp),
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.spacedBy(8.dp),
                ) {
                    AsyncImage(
                        model = tasksAsset(serverUrl, "plus-black.svg"),
                        contentDescription = null,
                        modifier = Modifier.size(16.dp),
                    )
                    BasicTextField(
                        value = createText,
                        onValueChange = onCreateTextChange,
                        modifier = Modifier.weight(1f),
                        singleLine = true,
                        enabled = !saving,
                        textStyle = TextStyle(fontSize = 14.sp, color = F7Colors.TextPrimary),
                        cursorBrush = SolidColor(F7Colors.Primary),
                        keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
                        keyboardActions = KeyboardActions(onDone = { onCreateSubmit() }),
                        decorationBox = { inner ->
                            if (createText.isEmpty()) {
                                Text(
                                    "Создать задачу в календар…",
                                    color = F7Colors.TextSecondary,
                                    fontSize = 14.sp,
                                    maxLines = 1,
                                    overflow = TextOverflow.Ellipsis,
                                )
                            }
                            inner()
                        },
                    )
                }
            } else {
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .clip(CircleShape)
                        .background(
                            Brush.linearGradient(
                                listOf(F7Colors.PrimaryGradientStart, F7Colors.PrimaryGradientEnd),
                            ),
                        )
                        .border(1.dp, F7Colors.Primary.copy(alpha = 0.22f), CircleShape)
                        .clickable(onClick = onCreateExpand),
                    contentAlignment = Alignment.Center,
                ) {
                    AsyncImage(
                        model = tasksAsset(serverUrl, "plus-white.svg"),
                        contentDescription = "Создать",
                        modifier = Modifier.size(16.dp),
                    )
                }
            }
        }

        if (!createExpanded) {
            Spacer(Modifier.weight(1f))
        }

        TasksIconButton(
            serverUrl = serverUrl,
            iconPath = "filters-black.svg",
            contentDescription = "Фильтр",
            onClick = onFilterClick,
        )
        TasksIconButton(
            serverUrl = serverUrl,
            iconPath = "list-lines-16.svg",
            contentDescription = "Сортировка",
            onClick = onSortClick,
        )
        TasksIconButton(
            serverUrl = serverUrl,
            iconPath = "settings-gray.svg",
            contentDescription = "Ещё",
            onClick = onMoreClick,
        )
    }
}

@Composable
private fun TasksIconButton(
    serverUrl: String,
    iconPath: String,
    contentDescription: String,
    onClick: () -> Unit,
) {
    Box(
        modifier = Modifier
            .size(40.dp)
            .clip(CircleShape)
            .background(TasksFieldBg)
            .tasksFieldShadow()
            .clickable(onClick = onClick),
        contentAlignment = Alignment.Center,
    ) {
        AsyncImage(
            model = tasksAsset(serverUrl, iconPath),
            contentDescription = contentDescription,
            modifier = Modifier.size(16.dp),
        )
    }
}

@Composable
fun TasksListNavView(
    serverUrl: String,
    lists: List<TaskListItem>,
    selectedHref: String?,
    onListClick: (TaskListItem) -> Unit,
    modifier: Modifier = Modifier,
) {
    LazyColumn(
        modifier = modifier.fillMaxSize(),
        verticalArrangement = Arrangement.spacedBy(4.dp),
    ) {
        item {
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(bottom = 8.dp)
                    .height(40.dp)
                    .clip(RoundedCornerShape(100.dp))
                    .background(
                        Brush.linearGradient(
                            listOf(F7Colors.PrimaryGradientStart, F7Colors.PrimaryGradientEnd),
                        ),
                    )
                    .padding(horizontal = 16.dp),
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.spacedBy(8.dp),
            ) {
                AsyncImage(
                    model = tasksAsset(serverUrl, "plus-white.svg"),
                    contentDescription = null,
                    modifier = Modifier.size(16.dp),
                )
                Text(
                    "Добавить список",
                    color = F7Colors.TextOnPrimary,
                    fontSize = 14.sp,
                    fontWeight = FontWeight.SemiBold,
                )
            }
        }
        items(lists, key = { it.href }) { list ->
            val active = list.href == selectedHref
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(40.dp)
                    .clip(RoundedCornerShape(8.dp))
                    .background(if (active) F7Colors.PrimaryLight else TasksFieldBg)
                    .then(if (!active) Modifier.tasksFieldShadow() else Modifier)
                    .clickable { onListClick(list) }
                    .padding(horizontal = 12.dp),
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.spacedBy(10.dp),
            ) {
                AsyncImage(
                    model = tasksAsset(serverUrl, if (active) "list-white.svg" else "calendar-black.svg"),
                    contentDescription = null,
                    modifier = Modifier.size(18.dp),
                )
                Text(
                    list.displayName,
                    fontSize = 14.sp,
                    fontWeight = FontWeight.Medium,
                    color = if (active) F7Colors.PrimaryDark else F7Colors.TextPrimary,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis,
                    modifier = Modifier.weight(1f),
                )
            }
        }
    }
}

@Composable
fun TasksGroupHeader(
    title: String,
    accentColor: Color,
    modifier: Modifier = Modifier,
) {
    Row(
        modifier = modifier
            .fillMaxWidth()
            .height(36.dp)
            .clip(RoundedCornerShape(8.dp))
            .background(TasksHeadingBg)
            .padding(horizontal = 4.dp, vertical = 8.dp),
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.spacedBy(8.dp),
    ) {
        Box(
            modifier = Modifier
                .size(16.dp)
                .clip(CircleShape)
                .background(accentColor),
        )
        Text(
            title,
            fontSize = 14.sp,
            fontWeight = FontWeight.Medium,
            color = F7Colors.TextPrimary,
            maxLines = 1,
            overflow = TextOverflow.Ellipsis,
            modifier = Modifier.weight(1f),
        )
    }
}

@Composable
fun TasksRow(
    task: TaskItem,
    serverUrl: String,
    showMeta: Boolean = true,
    onToggleComplete: () -> Unit,
    onOpen: () -> Unit,
    modifier: Modifier = Modifier,
) {
    val hasMeta = showMeta && (task.listName.isNotBlank() || task.percentComplete in 1..99 || task.due.isNotBlank())
    Column(
        modifier = modifier
            .fillMaxWidth()
            .clip(RoundedCornerShape(4.dp))
            .background(TasksFieldBg)
            .tasksFieldShadow()
            .clickable(onClick = onOpen)
            .padding(horizontal = 4.dp, vertical = if (hasMeta) 8.dp else 0.dp)
            .heightIn(min = 48.dp),
        verticalArrangement = Arrangement.spacedBy(2.dp),
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .then(if (!hasMeta) Modifier.height(48.dp) else Modifier),
            verticalAlignment = Alignment.CenterVertically,
        ) {
            TaskCheckbox(
                serverUrl = serverUrl,
                checked = task.isCompleted,
                size = 16.dp,
                onClick = onToggleComplete,
                modifier = Modifier.padding(start = 4.dp, end = 8.dp),
            )
            Text(
                task.summary,
                modifier = Modifier.weight(1f),
                fontSize = 14.sp,
                fontWeight = FontWeight.Medium,
                color = if (task.isCompleted) F7Colors.TextSecondary else F7Colors.TextPrimary,
                textDecoration = if (task.isCompleted) TextDecoration.LineThrough else null,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis,
            )
            Row(
                horizontalArrangement = Arrangement.spacedBy(4.dp),
                verticalAlignment = Alignment.CenterVertically,
                modifier = Modifier.padding(end = 4.dp),
            ) {
                if (task.priority in 1..4) {
                    AsyncImage(
                        model = tasksAsset(serverUrl, "star-green-full.svg"),
                        contentDescription = null,
                        modifier = Modifier.size(16.dp),
                    )
                }
                if (task.due.isNotBlank()) {
                    Text(
                        task.due,
                        fontSize = 12.sp,
                        fontWeight = FontWeight.Medium,
                        color = task.dueDateColor(),
                    )
                }
            }
        }
        if (hasMeta) {
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(start = 28.dp, end = 4.dp),
                verticalAlignment = Alignment.CenterVertically,
            ) {
                if (task.listName.isNotBlank()) {
                    Row(
                        horizontalArrangement = Arrangement.spacedBy(4.dp),
                        verticalAlignment = Alignment.CenterVertically,
                    ) {
                        AsyncImage(
                            model = tasksAsset(serverUrl, "list-lines-16.svg"),
                            contentDescription = null,
                            modifier = Modifier.size(14.dp),
                        )
                        Text(
                            task.listName,
                            fontSize = 12.sp,
                            color = F7Colors.Primary,
                            maxLines = 1,
                            overflow = TextOverflow.Ellipsis,
                        )
                    }
                }
                Spacer(Modifier.weight(1f))
                if (task.percentComplete in 1..99) {
                    Text(
                        "${task.percentComplete}%",
                        fontSize = 12.sp,
                        color = F7Colors.TextSecondary,
                    )
                }
            }
        }
        if (task.isCompleted) {
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(start = 28.dp),
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.spacedBy(6.dp),
            ) {
                Box(
                    modifier = Modifier
                        .size(8.dp)
                        .clip(CircleShape)
                        .border(1.dp, F7Colors.Primary, CircleShape),
                )
                Text("Завершено", fontSize = 12.sp, color = F7Colors.Primary)
            }
        }
    }
}

@Composable
private fun TaskCheckbox(
    serverUrl: String,
    checked: Boolean,
    size: androidx.compose.ui.unit.Dp,
    onClick: () -> Unit,
    modifier: Modifier = Modifier,
) {
    AsyncImage(
        model = if (checked) {
            themesAsset(serverUrl, "checkbox-marked-icon.svg")
        } else {
            tasksAsset(serverUrl, "checkbox-unchecked-24.svg")
        },
        contentDescription = if (checked) "Выполнено" else "Не выполнено",
        modifier = modifier
            .size(size)
            .clickable(onClick = onClick),
    )
}

@Composable
fun TasksEmptyState(
    serverUrl: String,
    loading: Boolean,
    onReload: () -> Unit,
    modifier: Modifier = Modifier,
) {
    Column(
        modifier = modifier
            .fillMaxWidth()
            .padding(vertical = 32.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.spacedBy(12.dp),
    ) {
        AsyncImage(
            model = tasksAsset(serverUrl, "tasks-empty-list-icon.svg"),
            contentDescription = null,
            modifier = Modifier.size(55.dp),
        )
        Text(
            "Задач и событий нет",
            fontSize = 16.sp,
            fontWeight = FontWeight.SemiBold,
            color = F7Colors.TextPrimary,
        )
        Text(
            "Создайте задачу или загрузите список с сервера",
            fontSize = 14.sp,
            color = F7Colors.TextSecondary,
        )
        Box(
            modifier = Modifier
                .padding(top = 8.dp)
                .height(40.dp)
                .clip(RoundedCornerShape(100.dp))
                .background(
                    Brush.linearGradient(
                        listOf(F7Colors.PrimaryGradientStart, F7Colors.PrimaryGradientEnd),
                    ),
                )
                .clickable(enabled = !loading, onClick = onReload)
                .padding(horizontal = 20.dp),
            contentAlignment = Alignment.Center,
        ) {
            if (loading) {
                CircularProgressIndicator(
                    modifier = Modifier.size(18.dp),
                    color = F7Colors.TextOnPrimary,
                    strokeWidth = 2.dp,
                )
            } else {
                Row(
                    horizontalArrangement = Arrangement.spacedBy(8.dp),
                    verticalAlignment = Alignment.CenterVertically,
                ) {
                    AsyncImage(
                        model = tasksAsset(serverUrl, "tasks-upload-white.svg"),
                        contentDescription = null,
                        modifier = Modifier.size(16.dp),
                    )
                    Text("Загрузить", color = F7Colors.TextOnPrimary, fontWeight = FontWeight.SemiBold)
                }
            }
        }
    }
}

@Composable
fun TasksCompletedSection(
    serverUrl: String,
    tasks: List<TaskItem>,
    expanded: Boolean,
    listName: String,
    deleting: Boolean,
    onToggleExpanded: () -> Unit,
    onToggleComplete: (TaskItem) -> Unit,
    onOpen: (TaskItem) -> Unit,
    onDeleteCompleted: () -> Unit,
    modifier: Modifier = Modifier,
) {
    if (tasks.isEmpty()) return
    Column(modifier = modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(4.dp)) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .clickable(onClick = onToggleExpanded)
                .padding(vertical = 8.dp),
            verticalAlignment = Alignment.CenterVertically,
        ) {
            Text(
                "${tasks.size} завершённые задачи",
                fontSize = 14.sp,
                fontWeight = FontWeight.Medium,
                color = F7Colors.TextPrimary,
                modifier = Modifier.weight(1f),
            )
            AsyncImage(
                model = tasksAsset(serverUrl, "chevron-down-16.svg"),
                contentDescription = null,
                modifier = Modifier
                    .size(16.dp)
                    .then(
                        if (!expanded) Modifier else Modifier,
                    ),
            )
        }
        if (expanded) {
            tasks.forEach { task ->
                TasksRow(
                    task = task,
                    serverUrl = serverUrl,
                    showMeta = false,
                    onToggleComplete = { onToggleComplete(task) },
                    onOpen = { onOpen(task) },
                )
            }
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(top = 12.dp),
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.spacedBy(8.dp),
            ) {
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(44.dp)
                        .clip(RoundedCornerShape(100.dp))
                        .background(F7Colors.ErrorBg)
                        .clickable(enabled = !deleting, onClick = onDeleteCompleted),
                    contentAlignment = Alignment.Center,
                ) {
                    if (deleting) {
                        CircularProgressIndicator(
                            modifier = Modifier.size(20.dp),
                            color = F7Colors.Error,
                            strokeWidth = 2.dp,
                        )
                    } else {
                        Row(
                            horizontalArrangement = Arrangement.spacedBy(8.dp),
                            verticalAlignment = Alignment.CenterVertically,
                        ) {
                            AsyncImage(
                                model = tasksAsset(serverUrl, "basket-black.svg"),
                                contentDescription = null,
                                modifier = Modifier.size(16.dp),
                            )
                            Text("Удалить", color = F7Colors.Error, fontWeight = FontWeight.SemiBold)
                        }
                    }
                }
                Text(
                    "Завершённые задачи из списка «$listName» будут удалены",
                    fontSize = 12.sp,
                    color = F7Colors.Error,
                )
            }
        }
    }
}

@Composable
fun TaskDetailSheet(
    visible: Boolean,
    serverUrl: String,
    task: TaskItem?,
    saving: Boolean,
    onDismiss: () -> Unit,
    onSwipeBack: () -> Unit = onDismiss,
    onToggleComplete: () -> Unit,
    onSave: (summary: String, due: String, priority: Int, description: String) -> Unit,
    onDelete: () -> Unit,
) {
    if (!visible || task == null) return
    var summary by remember(task.uid) { mutableStateOf(task.summary) }
    var due by remember(task.uid) { mutableStateOf(TasksRepository.formatDueForInput(task.dueRaw)) }
    var priority by remember(task.uid) { mutableStateOf(task.priority) }
    var description by remember(task.uid) { mutableStateOf(task.description) }
    var tab by remember(task.uid) { mutableStateOf(TaskDetailTab.Details) }
    var confirmDelete by remember { mutableStateOf(false) }

    Dialog(
        onDismissRequest = { if (!saving) onDismiss() },
        properties = DialogProperties(usePlatformDefaultWidth = false),
    ) {
        Surface(
            modifier = Modifier
                .fillMaxSize()
                .f7SwipeFromRightToDismiss(onDismiss = onSwipeBack),
            color = F7Colors.Background,
        ) {
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(horizontal = 10.dp)
                    .padding(top = 40.dp, bottom = 90.dp)
                    .verticalScroll(rememberScrollState()),
                verticalArrangement = Arrangement.spacedBy(12.dp),
            ) {
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(12.dp),
                    verticalAlignment = Alignment.Top,
                ) {
                    TaskCheckbox(
                        serverUrl = serverUrl,
                        checked = task.isCompleted,
                        size = 24.dp,
                        onClick = onToggleComplete,
                    )
                    Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) {
                        BasicTextField(
                            value = summary,
                            onValueChange = { summary = it },
                            modifier = Modifier.fillMaxWidth(),
                            textStyle = TextStyle(
                                fontSize = 18.sp,
                                fontWeight = FontWeight.SemiBold,
                                color = F7Colors.TextPrimary,
                            ),
                            cursorBrush = SolidColor(F7Colors.Primary),
                        )
                        Text(
                            task.listName.ifBlank { "Список" },
                            fontSize = 12.sp,
                            color = F7Colors.TextSecondary,
                        )
                    }
                    IconButton(onClick = { if (!saving) onDismiss() }) {
                        AsyncImage(
                            model = tasksAsset(serverUrl, "close-sidebar-gray.svg"),
                            contentDescription = "Закрыть",
                            modifier = Modifier.size(20.dp),
                        )
                    }
                }

                TaskDetailTabs(
                    serverUrl = serverUrl,
                    selected = tab,
                    onSelect = { tab = it },
                )

                when (tab) {
                    TaskDetailTab.Details -> {
                        TaskSidebarField(
                            serverUrl = serverUrl,
                            iconPath = "calendar-black.svg",
                            label = "Срок",
                            value = due.ifBlank { "Не указан" },
                        )
                        F7OutlinedField(
                            value = due,
                            onValueChange = { due = it },
                            label = "Срок (дд.мм.гггг)",
                        )
                        Text("Приоритет", fontSize = 12.sp, color = F7Colors.TextSecondary)
                        TaskPriorityOption("Без приоритета", 0, priority) { priority = 0 }
                        TaskPriorityOption("Высокий", 1, priority) { priority = 1 }
                        TaskPriorityOption("Средний", 5, priority) { priority = 5 }
                        TaskPriorityOption("Низкий", 9, priority) { priority = 9 }
                        if (task.percentComplete > 0) {
                            TaskSidebarField(
                                serverUrl = serverUrl,
                                iconPath = "sidebar-check-16.svg",
                                label = "Прогресс",
                                value = "${task.percentComplete}%",
                            )
                        }
                    }
                    TaskDetailTab.Notes -> {
                        F7OutlinedField(
                            value = description,
                            onValueChange = { description = it },
                            label = "Заметки",
                            minLines = 8,
                        )
                    }
                }

                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween,
                    verticalAlignment = Alignment.CenterVertically,
                ) {
                    TextButton(onClick = { confirmDelete = true }, enabled = !saving) {
                        Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
                            AsyncImage(
                                model = tasksAsset(serverUrl, "basket-black.svg"),
                                contentDescription = null,
                                modifier = Modifier.size(16.dp),
                            )
                            Text("Удалить", color = F7Colors.Error)
                        }
                    }
                    Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                        F7SecondaryButton(text = "Отмена", onClick = onDismiss, enabled = !saving)
                        F7PrimaryButton(
                            text = if (saving) "…" else "Сохранить",
                            onClick = { onSave(summary, due, priority, description) },
                            enabled = !saving,
                        )
                    }
                }
            }
        }
    }

    if (confirmDelete) {
        AlertDialog(
            onDismissRequest = { confirmDelete = false },
            title = { Text("Удалить задачу?") },
            confirmButton = {
                TextButton(onClick = {
                    confirmDelete = false
                    onDelete()
                }) {
                    Text("Удалить", color = F7Colors.Error)
                }
            },
            dismissButton = {
                TextButton(onClick = { confirmDelete = false }) { Text("Отмена") }
            },
        )
    }
}

private enum class TaskDetailTab { Details, Notes }

@Composable
private fun TaskDetailTabs(
    serverUrl: String,
    selected: TaskDetailTab,
    onSelect: (TaskDetailTab) -> Unit,
) {
    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.spacedBy(8.dp),
    ) {
        TaskDetailTab.entries.forEach { tab ->
            val active = tab == selected
            Row(
                modifier = Modifier
                    .weight(1f)
                    .height(30.dp)
                    .clip(RoundedCornerShape(8.dp))
                    .background(if (active) F7Colors.PrimaryLight else TasksFieldBg)
                    .then(if (!active) Modifier.border(1.dp, F7Colors.Border, RoundedCornerShape(8.dp)) else Modifier)
                    .clickable { onSelect(tab) }
                    .padding(horizontal = 10.dp),
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.spacedBy(6.dp, Alignment.CenterHorizontally),
            ) {
                val icon = when (tab) {
                    TaskDetailTab.Details -> "sidebar-tab-details.svg"
                    TaskDetailTab.Notes -> "sidebar-tab-notes.svg"
                }
                AsyncImage(
                    model = tasksAsset(serverUrl, icon),
                    contentDescription = null,
                    modifier = Modifier.size(16.dp),
                )
                Text(
                    when (tab) {
                        TaskDetailTab.Details -> "Свойства"
                        TaskDetailTab.Notes -> "Заметки"
                    },
                    fontSize = 12.sp,
                    fontWeight = FontWeight.Medium,
                    color = if (active) F7Colors.PrimaryDark else F7Colors.TextSecondary,
                )
            }
        }
    }
}

@Composable
private fun TaskSidebarField(
    serverUrl: String,
    iconPath: String,
    label: String,
    value: String,
) {
    Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
        Row(horizontalArrangement = Arrangement.spacedBy(6.dp), verticalAlignment = Alignment.CenterVertically) {
            AsyncImage(model = tasksAsset(serverUrl, iconPath), contentDescription = null, modifier = Modifier.size(16.dp))
            Text(label, fontSize = 12.sp, color = F7Colors.TextSecondary)
        }
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .height(40.dp)
                .clip(RoundedCornerShape(8.dp))
                .background(TasksFieldBg)
                .border(1.dp, F7Colors.Border, RoundedCornerShape(8.dp))
                .padding(horizontal = 12.dp),
            contentAlignment = Alignment.CenterStart,
        ) {
            Text(value, fontSize = 14.sp, color = F7Colors.TextPrimary, maxLines = 1, overflow = TextOverflow.Ellipsis)
        }
    }
}

@Composable
private fun TaskPriorityOption(
    label: String,
    value: Int,
    selected: Int,
    onSelect: () -> Unit,
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .clickable(onClick = onSelect)
            .padding(vertical = 2.dp),
        verticalAlignment = Alignment.CenterVertically,
    ) {
        RadioButton(selected = selected == value, onClick = onSelect)
        Text(label, modifier = Modifier.padding(start = 4.dp), fontSize = 14.sp)
    }
}

@Composable
fun TasksSettingsSheet(
    visible: Boolean,
    serverUrl: String,
    lists: List<TaskListItem>,
    defaultListHref: String?,
    onDefaultListChange: (String?) -> Unit,
    onDismiss: () -> Unit,
    onSwipeBack: () -> Unit = onDismiss,
) {
    if (!visible) return
    val visibilityOptions = listOf("Показывать", "Скрывать")
  var importantVisible by remember { mutableStateOf(visibilityOptions.first()) }
    var todayVisible by remember { mutableStateOf(visibilityOptions.first()) }
    var weekVisible by remember { mutableStateOf(visibilityOptions.first()) }
    var allVisible by remember { mutableStateOf(visibilityOptions.first()) }
    var currentVisible by remember { mutableStateOf(visibilityOptions.first()) }
    var completedVisible by remember { mutableStateOf(visibilityOptions.first()) }
    var defaultMenuOpen by remember { mutableStateOf(false) }

    Dialog(
        onDismissRequest = onDismiss,
        properties = DialogProperties(usePlatformDefaultWidth = false),
    ) {
        Surface(
            modifier = Modifier
                .fillMaxSize()
                .f7SwipeFromRightToDismiss(onDismiss = onSwipeBack),
            color = F7Colors.Surface,
        ) {
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(20.dp)
                    .verticalScroll(rememberScrollState()),
                verticalArrangement = Arrangement.spacedBy(16.dp),
            ) {
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween,
                    verticalAlignment = Alignment.CenterVertically,
                ) {
                    Text(
                        "Параметры задач",
                        style = MaterialTheme.typography.titleLarge,
                        fontWeight = FontWeight.Bold,
                    )
                    IconButton(onClick = onDismiss) {
                        Text("✕", fontSize = 18.sp, color = F7Colors.TextSecondary)
                    }
                }

                Text("Список по умолчанию", fontSize = 14.sp, fontWeight = FontWeight.Medium)
                Box {
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(48.dp)
                            .clip(RoundedCornerShape(8.dp))
                            .border(1.dp, F7Colors.Border, RoundedCornerShape(8.dp))
                            .clickable { defaultMenuOpen = true }
                            .padding(horizontal = 14.dp),
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.SpaceBetween,
                    ) {
                        Text(
                            lists.firstOrNull { it.href == defaultListHref }?.displayName ?: "Название",
                            color = if (defaultListHref == null) F7Colors.TextSecondary else F7Colors.TextPrimary,
                        )
                        AsyncImage(
                            model = tasksAsset(serverUrl, "chevron-down-16.svg"),
                            contentDescription = null,
                            modifier = Modifier.size(16.dp),
                        )
                    }
                    DropdownMenu(expanded = defaultMenuOpen, onDismissRequest = { defaultMenuOpen = false }) {
                        lists.forEach { list ->
                            DropdownMenuItem(
                                text = { Text(list.displayName) },
                                onClick = {
                                    onDefaultListChange(list.href)
                                    defaultMenuOpen = false
                                },
                            )
                        }
                    }
                }

                HorizontalDivider(color = F7Colors.Border)

                SmartListSettingRow(serverUrl, "important-gray.svg", "Важное", importantVisible) {
                    importantVisible = it
                }
                SmartListSettingRow(serverUrl, "calendar-today-gray.svg", "Сегодня", todayVisible) {
                    todayVisible = it
                }
                SmartListSettingRow(serverUrl, "calendar-nextweek-gray.svg", "На неделе", weekVisible) {
                    weekVisible = it
                }
                SmartListSettingRow(serverUrl, "calendar-icon-gray.svg", "Все", allVisible) {
                    allVisible = it
                }
                SmartListSettingRow(serverUrl, "current-gray.svg", "Текущие", currentVisible) {
                    currentVisible = it
                }
                SmartListSettingRow(serverUrl, "check-done-gray.svg", "Завершенные", completedVisible) {
                    completedVisible = it
                }
            }
        }
    }
}

@Composable
private fun SmartListSettingRow(
    serverUrl: String,
    iconPath: String,
    title: String,
    selected: String,
    onSelect: (String) -> Unit,
) {
    var menuOpen by remember { mutableStateOf(false) }
    val options = listOf("Показывать", "Скрывать")
    Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
        Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) {
            AsyncImage(model = tasksAsset(serverUrl, iconPath), contentDescription = null, modifier = Modifier.size(18.dp))
            Text(title, fontSize = 14.sp, fontWeight = FontWeight.Medium)
        }
        Box {
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(48.dp)
                    .clip(RoundedCornerShape(8.dp))
                    .border(1.dp, F7Colors.Border, RoundedCornerShape(8.dp))
                    .clickable { menuOpen = true }
                    .padding(horizontal = 14.dp),
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.SpaceBetween,
            ) {
                Text(selected)
                AsyncImage(
                    model = tasksAsset(serverUrl, "chevron-down-16.svg"),
                    contentDescription = null,
                    modifier = Modifier.size(16.dp),
                )
            }
            DropdownMenu(expanded = menuOpen, onDismissRequest = { menuOpen = false }) {
                options.forEach { option ->
                    DropdownMenuItem(
                        text = { Text(option) },
                        onClick = {
                            onSelect(option)
                            menuOpen = false
                        },
                    )
                }
            }
        }
    }
}
