package ru.forbion.f7cloud.core.designsystem

import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutVertically
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.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
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.navigationBarsPadding
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
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.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
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.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.AsyncImage

// Живой forbion (_header.css .app-menu--mobile): нижний отступ 90 под плавающую панель,
// иконки 62, сетка 3 колонки с gap 8, БЕЗ скругления верха и БЕЗ ручки-хендла,
// высота — по контенту (почти весь экран), фон #FBFBFB.
private val BottomBarReserve: Dp = 90.dp
private val MenuIconSize = 62.dp
private val MenuGridGap = 8.dp

data class F7AppMenuItem(
    val label: String,
    val iconUrl: String,
    val selected: Boolean,
    val externalUrl: String? = null,
    // Локальная иконка вместо серверной (для нативных пунктов — Уведомления/Настройки),
    // рисуется в круглом бейдже с зелёной обводкой под стиль glass-иконок.
    val localIcon: ImageVector? = null,
)

@Composable
fun F7AppMenuSheet(
    visible: Boolean,
    serverUrl: String,
    items: List<F7AppMenuItem>,
    onDismiss: () -> Unit,
    onItemClick: (Int) -> Unit,
    modifier: Modifier = Modifier,
) {
    var searchQuery by remember(visible) { mutableStateOf("") }
    val filteredItems = remember(items, searchQuery) {
        val query = searchQuery.trim()
        if (query.isBlank()) {
            items
        } else {
            items.filter { it.label.contains(query, ignoreCase = true) }
        }
    }
    val base = serverUrl.trimEnd('/')

    Box(modifier = modifier.fillMaxSize()) {
        // Затемнение над листом — тап закрывает меню (лист занимает только низ экрана)
        AnimatedVisibility(
            visible = visible,
            enter = fadeIn(tween(200)),
            exit = fadeOut(tween(200)),
            modifier = Modifier.fillMaxSize(),
        ) {
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .background(Color.Black.copy(alpha = 0.18f))
                    .clickable(
                        interactionSource = remember { MutableInteractionSource() },
                        indication = null,
                        onClick = onDismiss,
                    ),
            )
        }
        // Сам лист — выезжает снизу вверх (translateY 100%→0), как в живом forbion:
        // без скругления верха и без ручки, высота по контенту до почти всего экрана.
        AnimatedVisibility(
            visible = visible,
            enter = fadeIn(tween(250)) + slideInVertically(
                animationSpec = tween(350),
                initialOffsetY = { it },
            ),
            exit = fadeOut(tween(200)) + slideOutVertically(
                animationSpec = tween(300),
                targetOffsetY = { it },
            ),
            modifier = Modifier.align(Alignment.BottomCenter),
        ) {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .heightIn(max = 640.dp)
                    .background(F7Colors.Background)
                    .navigationBarsPadding()
                    .padding(start = 16.dp, end = 16.dp, top = 16.dp, bottom = BottomBarReserve)
                    .verticalScroll(rememberScrollState()),
            ) {
                F7AppMenuSearchField(
                    serverUrl = base,
                    value = searchQuery,
                    onValueChange = { searchQuery = it },
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(bottom = 24.dp),
                )
                // Сетка 3 колонки, gap 8 (живой forbion). Не-ленивая — лист сам в verticalScroll.
                Column(
                    modifier = Modifier.fillMaxWidth(),
                    verticalArrangement = Arrangement.spacedBy(MenuGridGap),
                ) {
                    filteredItems.chunked(3).forEach { rowItems ->
                        Row(
                            modifier = Modifier.fillMaxWidth(),
                            horizontalArrangement = Arrangement.spacedBy(MenuGridGap),
                        ) {
                            rowItems.forEach { item ->
                                val originalIndex = items.indexOf(item)
                                Box(
                                    modifier = Modifier.weight(1f),
                                    contentAlignment = Alignment.TopCenter,
                                ) {
                                    F7AppMenuGridItem(
                                        item = item,
                                        onClick = { if (originalIndex >= 0) onItemClick(originalIndex) },
                                    )
                                }
                            }
                            // добить ряд пустыми ячейками для выравнивания по левому краю
                            repeat(3 - rowItems.size) { Box(modifier = Modifier.weight(1f)) {} }
                        }
                    }
                }
            }
        }
    }
}

@Composable
private fun F7AppMenuSearchField(
    serverUrl: String,
    value: String,
    onValueChange: (String) -> Unit,
    modifier: Modifier = Modifier,
) {
    Box(
        modifier = modifier
            .height(40.dp)
            .clip(RoundedCornerShape(20.dp))
            .background(Color.White)
            .border(1.dp, Color(0xFFE6E6E6), RoundedCornerShape(20.dp)),
        contentAlignment = Alignment.CenterStart,
    ) {
        AsyncImage(
            model = "$serverUrl/themes/forbion/images/header/search-glass.svg",
            contentDescription = null,
            modifier = Modifier
                .padding(start = 10.dp)
                .size(18.dp),
            contentScale = ContentScale.Fit,
        )
        BasicTextField(
            value = value,
            onValueChange = onValueChange,
            singleLine = true,
            textStyle = TextStyle(
                fontSize = 14.sp,
                color = F7Colors.TextPrimary,
            ),
            cursorBrush = SolidColor(F7Colors.Primary),
            modifier = Modifier
                .fillMaxWidth()
                .padding(start = 40.dp, end = 14.dp),
            decorationBox = { innerTextField ->
                Box(contentAlignment = Alignment.CenterStart) {
                    if (value.isBlank()) {
                        Text(
                            text = "Поиск...",
                            style = MaterialTheme.typography.bodyMedium,
                            color = Color(0xFF808080),
                        )
                    }
                    innerTextField()
                }
            },
        )
    }
}

@Composable
private fun F7AppMenuGridItem(
    item: F7AppMenuItem,
    onClick: () -> Unit,
) {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .clip(RoundedCornerShape(12.dp))
            .clickable(onClick = onClick)
            .padding(vertical = 4.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.spacedBy(8.dp),
    ) {
        val localIcon = item.localIcon
        if (localIcon != null) {
            // Нативный пункт: иконка в круглом бейдже с зелёной обводкой (стиль glass)
            Box(
                modifier = Modifier
                    .size(MenuIconSize)
                    .clip(CircleShape)
                    .background(Color.White)
                    .border(1.5.dp, F7Colors.Green30, CircleShape),
                contentAlignment = Alignment.Center,
            ) {
                Icon(
                    localIcon,
                    contentDescription = item.label,
                    tint = F7Colors.Primary,
                    modifier = Modifier.size(MenuIconSize * 0.46f),
                )
            }
        } else {
            AsyncImage(
                model = item.iconUrl,
                contentDescription = item.label,
                modifier = Modifier.size(MenuIconSize),
                contentScale = ContentScale.Fit,
            )
        }
        Text(
            text = item.label,
            style = MaterialTheme.typography.labelLarge.copy(
                fontWeight = FontWeight.Bold,
                fontSize = 12.sp,
                lineHeight = 14.sp,
                color = Color(0xFF151515),
            ),
            textAlign = TextAlign.Center,
            maxLines = 2,
            overflow = TextOverflow.Ellipsis,
        )
    }
}
