package ru.forbion.f7cloud.feature.mail

import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
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.widthIn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
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.graphics.SolidColor
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.text.TextStyle
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.designsystem.F7Colors
import ru.forbion.f7cloud.feature.contacts.ContactItem
import ru.forbion.f7cloud.feature.contacts.ContactListRow

/**
 * Поле получателей с чипами — как в живой теме (_mobile-mail.css):
 * подтверждённые адреса (сегменты строки через запятую) — пилюли 26dp
 * (фон #70B62B 12%, рамка 25%, текст 13/18, крестик 14), хвост — инлайн-ввод.
 * Значение остаётся строкой «a, b, черновик» — VM/parseRecipients не меняются.
 */
@OptIn(ExperimentalLayoutApi::class)
@Composable
fun MailRecipientComposeField(
    label: String,
    value: String,
    onValueChange: (String) -> Unit,
    suggestions: List<ContactItem>,
    showSuggestions: Boolean,
    onSuggestionClick: (ContactItem) -> Unit,
    onDismissSuggestions: () -> Unit,
    trailingIconUrl: String? = null,
    onTrailingClick: (() -> Unit)? = null,
) {
    val parts = value.split(',').map { it.trim() }
    val draft = if (value.trimEnd().endsWith(",")) "" else parts.lastOrNull().orEmpty()
    val committed = (if (draft.isEmpty()) parts else parts.dropLast(1)).filter { it.isNotBlank() }

    fun rebuild(newCommitted: List<String>, newDraft: String): String {
        val head = newCommitted.joinToString(", ")
        return when {
            head.isEmpty() -> newDraft
            newDraft.isEmpty() -> "$head, "
            else -> "$head, $newDraft"
        }
    }

    Box(modifier = Modifier.fillMaxWidth()) {
        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)
                .heightIn(min = 40.dp)
                .padding(4.dp),
            verticalAlignment = Alignment.CenterVertically,
        ) {
            FlowRow(
                modifier = Modifier.weight(1f),
                horizontalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(4.dp),
                verticalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(4.dp),
            ) {
                committed.forEachIndexed { index, recipient ->
                    RecipientChip(
                        text = recipient,
                        onRemove = {
                            val rest = committed.toMutableList().also { it.removeAt(index) }
                            onValueChange(rebuild(rest, draft))
                        },
                    )
                }
                BasicTextField(
                    value = draft,
                    onValueChange = { new -> onValueChange(rebuild(committed, new)) },
                    modifier = Modifier
                        .widthIn(min = 80.dp)
                        .weight(1f)
                        .height(26.dp)
                        .padding(horizontal = 4.dp),
                    singleLine = true,
                    textStyle = TextStyle(
                        fontSize = 14.sp,
                        lineHeight = 20.sp,
                        color = F7Colors.TextPrimary,
                    ),
                    cursorBrush = SolidColor(F7Colors.Primary),
                    decorationBox = { inner ->
                        Box(contentAlignment = Alignment.CenterStart, modifier = Modifier.height(26.dp)) {
                            if (draft.isEmpty() && committed.isEmpty()) {
                                Text(label, color = F7Colors.TextSecondary, fontSize = 14.sp)
                            }
                            inner()
                        }
                    },
                )
            }
            if (trailingIconUrl != null && onTrailingClick != null) {
                AsyncImage(
                    model = trailingIconUrl,
                    contentDescription = null,
                    modifier = Modifier
                        .padding(end = 4.dp)
                        .size(16.dp)
                        .clickable(onClick = onTrailingClick),
                    contentScale = ContentScale.Fit,
                )
            }
        }
        if (showSuggestions && suggestions.isNotEmpty()) {
            Popup(
                alignment = Alignment.TopStart,
                onDismissRequest = onDismissSuggestions,
                properties = PopupProperties(focusable = false),
            ) {
                Column(
                    modifier = Modifier
                        .padding(horizontal = 12.dp, vertical = 2.dp)
                        .fillMaxWidth()
                        .heightIn(max = 240.dp)
                        .clip(RoundedCornerShape(8.dp))
                        .background(Color.White)
                        .border(1.dp, F7Colors.Border, RoundedCornerShape(8.dp)),
                ) {
                    suggestions.forEachIndexed { index, contact ->
                        ContactListRow(
                            contact = contact,
                            onClick = { onSuggestionClick(contact) },
                        )
                        if (index < suggestions.lastIndex) {
                            HorizontalDivider(color = F7Colors.Border.copy(alpha = 0.6f))
                        }
                    }
                }
            }
        }
    }
}

@Composable
private fun RecipientChip(text: String, onRemove: () -> Unit) {
    Row(
        modifier = Modifier
            .height(26.dp)
            .clip(RoundedCornerShape(100.dp))
            .background(F7Colors.Primary.copy(alpha = 0.12f))
            .border(1.dp, F7Colors.Primary.copy(alpha = 0.25f), RoundedCornerShape(100.dp))
            .padding(start = 6.dp, end = 8.dp),
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(4.dp),
    ) {
        Text(
            text,
            fontSize = 13.sp,
            lineHeight = 18.sp,
            color = F7Colors.TextPrimary,
            maxLines = 1,
            overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis,
            modifier = Modifier.widthIn(max = 220.dp),
        )
        Icon(
            imageVector = Icons.Filled.Close,
            contentDescription = "Убрать получателя",
            tint = F7Colors.TextPrimary.copy(alpha = 0.5f),
            modifier = Modifier
                .size(14.dp)
                .clickable(
                    interactionSource = androidx.compose.runtime.remember { MutableInteractionSource() },
                    indication = null,
                    onClick = onRemove,
                ),
        )
    }
}
