package ru.forbion.f7cloud.feature.mail

import androidx.compose.foundation.background
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.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
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.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
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.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.Dialog
import androidx.compose.ui.window.DialogProperties
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

private val FIELD_OPTIONS = listOf("from" to "От", "subject" to "Тема", "to" to "Кому")
private val ACTION_OPTIONS = listOf(
    "fileinto" to "Переместить в папку",
    "markread" to "Пометить прочитанным",
)

/** Пилюля-переключатель варианта (чипы живой темы: актив — #ECF9DE). */
@Composable
private fun OptionChip(text: String, selected: Boolean, onClick: () -> Unit) {
    Box(
        modifier = Modifier
            .heightIn(min = 25.dp)
            .clip(RoundedCornerShape(100.dp))
            .background(if (selected) F7Colors.PrimaryLight else F7Colors.SurfaceMuted)
            .clickable(onClick = onClick)
            .padding(horizontal = 10.dp, vertical = 4.dp),
        contentAlignment = Alignment.Center,
    ) {
        Text(text, style = MaterialTheme.typography.bodyMedium, color = F7Colors.TextPrimary)
    }
}

private fun ruleSummary(rule: MailFilterRule): String {
    val tests = rule.tests.joinToString("; ") { (field, op, values) ->
        val fieldLabel = FIELD_OPTIONS.firstOrNull { it.first == field }?.second ?: field
        "$fieldLabel $op «${values.joinToString(", ")}»"
    }
    val actions = rule.actions.joinToString("; ") { action ->
        when (action.optString("type")) {
            "fileinto" -> "в папку «${action.optString("mailbox")}»"
            "addflag", "addsystemflag" ->
                if (action.optString("flag").contains("Seen")) "пометить прочитанным"
                else "флаг «${action.optString("flag")}»"
            "keep" -> "оставить"
            "stop" -> "стоп"
            else -> action.optString("type")
        }
    }
    return "$tests → $actions"
}

/**
 * Фильтры почты — общие с веб-версией (официальный API NC Mail).
 * Список всех правил (вкл/выкл, удаление), редактирование простых, конструктор нового.
 */
@Composable
fun MailSieveFiltersSheet(
    visible: Boolean,
    rules: List<MailFilterRule>,
    folders: List<String>,
    loading: Boolean,
    saving: Boolean,
    error: String?,
    onDismiss: () -> Unit,
    onAdd: (MailFilterRule) -> Unit,
    onUpdate: (Int, MailFilterRule) -> Unit,
    onDelete: (Int) -> Unit,
    onToggle: (Int, Boolean) -> Unit,
) {
    if (!visible) return
    var name by rememberSaveable { mutableStateOf("") }
    var field by rememberSaveable { mutableStateOf("subject") }
    var contains by rememberSaveable { mutableStateOf("") }
    var action by rememberSaveable { mutableStateOf("fileinto") }
    var targetFolder by rememberSaveable(folders) { mutableStateOf(folders.firstOrNull().orEmpty()) }
    // -1 = создание нового; иначе — индекс редактируемого правила
    var editingIndex by rememberSaveable { mutableIntStateOf(-1) }

    fun loadIntoForm(rule: MailFilterRule) {
        name = rule.name
        rule.tests.firstOrNull()?.let { (f, _, values) ->
            field = f
            contains = values.joinToString(", ")
        }
        val act = rule.actions.firstOrNull()
        action = if (act?.optString("type") == "fileinto") "fileinto" else "markread"
        if (act?.optString("type") == "fileinto") {
            targetFolder = act.optString("mailbox")
        }
    }

    fun clearForm() {
        name = ""
        contains = ""
        editingIndex = -1
    }

    Dialog(
        onDismissRequest = onDismiss,
        properties = DialogProperties(usePlatformDefaultWidth = false),
    ) {
        Surface(
            modifier = Modifier
                .fillMaxWidth(0.94f)
                .heightIn(max = 660.dp),
            shape = RoundedCornerShape(16.dp),
            color = Color.White,
        ) {
            Column(
                modifier = Modifier
                    .verticalScroll(rememberScrollState())
                    .padding(16.dp),
                verticalArrangement = Arrangement.spacedBy(10.dp),
            ) {
                Text(
                    "Фильтры",
                    style = MaterialTheme.typography.titleMedium.copy(fontSize = 18.sp),
                    fontWeight = FontWeight.SemiBold,
                    color = F7Colors.TextPrimary,
                )
                when {
                    loading -> Box(
                        modifier = Modifier.fillMaxWidth().padding(vertical = 16.dp),
                        contentAlignment = Alignment.Center,
                    ) {
                        CircularProgressIndicator(color = F7Colors.Primary)
                    }
                    else -> {
                        if (rules.isEmpty()) {
                            Text(
                                "Фильтров пока нет.",
                                style = MaterialTheme.typography.bodyMedium,
                                color = F7Colors.TextSecondary,
                            )
                        }
                        rules.forEachIndexed { index, rule ->
                            Row(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .heightIn(min = 36.dp)
                                    .clip(RoundedCornerShape(10.dp))
                                    .background(
                                        if (editingIndex == index) F7Colors.PrimaryLight else F7Colors.SurfaceMuted,
                                    )
                                    .clickable(enabled = !saving && rule.isSimple) {
                                        editingIndex = index
                                        loadIntoForm(rule)
                                    }
                                    .padding(horizontal = 10.dp, vertical = 6.dp),
                                verticalAlignment = Alignment.CenterVertically,
                                horizontalArrangement = Arrangement.spacedBy(8.dp),
                            ) {
                                Column(modifier = Modifier.weight(1f)) {
                                    Text(
                                        rule.name.ifBlank { "Без названия" },
                                        style = MaterialTheme.typography.bodyMedium,
                                        fontWeight = FontWeight.Medium,
                                        color = F7Colors.TextPrimary,
                                        maxLines = 1,
                                        overflow = TextOverflow.Ellipsis,
                                    )
                                    Text(
                                        ruleSummary(rule) +
                                            if (!rule.isSimple) " (сложное — правится в вебе)" else "",
                                        style = MaterialTheme.typography.bodyMedium,
                                        color = F7Colors.TextSecondary,
                                        maxLines = 2,
                                        overflow = TextOverflow.Ellipsis,
                                    )
                                }
                                Switch(
                                    checked = rule.enable,
                                    onCheckedChange = { onToggle(index, it) },
                                    enabled = !saving,
                                    colors = SwitchDefaults.colors(checkedTrackColor = F7Colors.Primary),
                                )
                                Icon(
                                    imageVector = Icons.Filled.Close,
                                    contentDescription = "Удалить фильтр",
                                    tint = F7Colors.TextSecondary,
                                    modifier = Modifier
                                        .size(16.dp)
                                        .clickable(enabled = !saving) {
                                            if (editingIndex == index) clearForm()
                                            onDelete(index)
                                        },
                                )
                            }
                        }
                        Text(
                            if (editingIndex >= 0) "Изменить фильтр" else "Новый фильтр",
                            style = MaterialTheme.typography.bodyLarge,
                            fontWeight = FontWeight.Medium,
                            color = F7Colors.TextPrimary,
                        )
                        F7OutlinedField(value = name, onValueChange = { name = it }, label = "Название")
                        Text("Если", style = MaterialTheme.typography.bodyMedium, color = F7Colors.TextSecondary)
                        Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
                            FIELD_OPTIONS.forEach { (value, label) ->
                                OptionChip(label, selected = field == value) { field = value }
                            }
                        }
                        F7OutlinedField(value = contains, onValueChange = { contains = it }, label = "Содержит")
                        Text("То", style = MaterialTheme.typography.bodyMedium, color = F7Colors.TextSecondary)
                        Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
                            ACTION_OPTIONS.forEach { (value, label) ->
                                OptionChip(label, selected = action == value) { action = value }
                            }
                        }
                        if (action == "fileinto" && folders.isNotEmpty()) {
                            Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
                                folders.forEach { folder ->
                                    Row(
                                        modifier = Modifier
                                            .fillMaxWidth()
                                            .heightIn(min = 32.dp)
                                            .clip(RoundedCornerShape(10.dp))
                                            .background(
                                                if (folder == targetFolder) F7Colors.PrimaryLight else F7Colors.SurfaceMuted,
                                            )
                                            .clickable { targetFolder = folder }
                                            .padding(horizontal = 10.dp, vertical = 6.dp),
                                        verticalAlignment = Alignment.CenterVertically,
                                    ) {
                                        Text(
                                            folder,
                                            style = MaterialTheme.typography.bodyMedium,
                                            color = F7Colors.TextPrimary,
                                        )
                                    }
                                }
                            }
                        }
                        if (!error.isNullOrBlank()) {
                            Text(error, color = F7Colors.Error, style = MaterialTheme.typography.bodyMedium)
                        }
                        Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                            F7SecondaryButton(
                                if (editingIndex >= 0) "Отменить правку" else "Закрыть",
                                onClick = { if (editingIndex >= 0) clearForm() else onDismiss() },
                                modifier = Modifier.weight(1f),
                            )
                            F7PrimaryButton(
                                text = when {
                                    saving -> "Сохранение…"
                                    editingIndex >= 0 -> "Сохранить"
                                    else -> "Создать"
                                },
                                onClick = {
                                    val rule = MailFilterRule.simple(
                                        name = name.trim().ifBlank { "Фильтр" },
                                        field = field,
                                        contains = contains.trim(),
                                        action = action,
                                        targetFolder = if (action == "fileinto") targetFolder else "",
                                    )
                                    if (editingIndex >= 0) onUpdate(editingIndex, rule) else onAdd(rule)
                                    clearForm()
                                },
                                enabled = !saving && contains.isNotBlank() &&
                                    (action != "fileinto" || targetFolder.isNotBlank()),
                                modifier = Modifier.weight(1f),
                            )
                        }
                    }
                }
            }
        }
    }
}
