package ru.forbion.f7cloud.feature.files

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.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
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.material.icons.Icons
import androidx.compose.material.icons.filled.ChevronRight
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
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.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import ru.forbion.f7cloud.core.designsystem.F7Colors
import ru.forbion.f7cloud.core.designsystem.F7Radius
import ru.forbion.f7cloud.core.designsystem.F7Spacing

// Размеры — из боевой темы forbion (_mobile-files.css), копия один в один.

enum class FilesViewMode { List, Grid }

/**
 * Чекбокс из боевой темы: 16×16, серый контур / зелёная заливка с галкой
 * (checkbox-blank-outline-icon.svg / checkbox-marked-icon.svg). Тап-зона задаётся снаружи.
 */
@Composable
fun F7ThemeCheckbox(checked: Boolean, onToggle: () -> Unit, modifier: Modifier = Modifier) {
    AsyncImage(
        model = FileIcons.chromeAsset(
            if (checked) "checkbox-marked-icon.svg" else "checkbox-blank-outline-icon.svg",
        ),
        contentDescription = if (checked) "Снять выбор" else "Выбрать",
        modifier = modifier
            .size(16.dp)
            .clickable(
                interactionSource = remember { MutableInteractionSource() },
                indication = null,
                onClick = onToggle,
            ),
    )
}

/** Стиль «пилюли» темы: фон #FBFBFB, рамка #E6E6E6, мягкая тень 0 1px 2px. */
private fun Modifier.f7PillSurface(shape: RoundedCornerShape): Modifier = this
    .shadow(1.dp, shape, ambientColor = F7Colors.Border, spotColor = F7Colors.Border)
    .clip(shape)
    .background(F7Colors.Background)
    .border(1.dp, F7Colors.Border, shape)

/** Круглая кнопка-переключатель список⇄сетка справа от поиска (40×40, иконка 16). */
@Composable
fun FilesViewToggleButton(viewMode: FilesViewMode, onToggle: () -> Unit) {
    Box(
        modifier = Modifier
            .size(40.dp)
            .f7PillSurface(RoundedCornerShape(F7Radius.pill))
            .clickable(onClick = onToggle),
        contentAlignment = Alignment.Center,
    ) {
        AsyncImage(
            model = FileIcons.chromeAsset(
                if (viewMode == FilesViewMode.List) "grid-files-gray.svg" else "list-view-icon.svg",
            ),
            contentDescription = "Сменить вид",
            modifier = Modifier.size(16.dp),
        )
    }
}

/** Хлебные крошки: дом 16 + сегменты (все — серые 14/20) через шеврон 16, h-прокрутка. */
@Composable
fun FilesBreadcrumb(
    segments: List<String>,
    onHomeClick: () -> Unit,
    onSegmentClick: (index: Int) -> Unit,
    modifier: Modifier = Modifier,
) {
    Row(
        modifier = modifier
            .fillMaxWidth()
            .horizontalScroll(rememberScrollState())
            .padding(horizontal = F7Spacing.sm, vertical = F7Spacing.xs),
        horizontalArrangement = Arrangement.spacedBy(F7Spacing.xs),
        verticalAlignment = Alignment.CenterVertically,
    ) {
        AsyncImage(
            model = FileIcons.chromeAsset("home-bottom.svg"),
            contentDescription = "В начало",
            modifier = Modifier
                .size(16.dp)
                .clickable(onClick = onHomeClick),
        )
        segments.forEachIndexed { i, seg ->
            Icon(
                imageVector = Icons.Filled.ChevronRight,
                contentDescription = null,
                tint = F7Colors.TextSecondary,
                modifier = Modifier.size(16.dp),
            )
            Text(
                text = seg,
                style = MaterialTheme.typography.bodyMedium,
                color = F7Colors.TextSecondary,
                maxLines = 1,
                modifier = Modifier.clickable { onSegmentClick(i) },
            )
        }
    }
}

/** Ряд фильтр-чипов: Тип файла / Участники / Изменен (пилюли 25dp, minWidth 86). */
@Composable
fun FilesFilterChips(
    onTypeClick: () -> Unit,
    onParticipantsClick: () -> Unit,
    onModifiedClick: () -> Unit,
    modifier: Modifier = Modifier,
) {
    Row(
        modifier = modifier
            .fillMaxWidth()
            .horizontalScroll(rememberScrollState())
            .padding(horizontal = F7Spacing.xs, vertical = F7Spacing.xs),
        horizontalArrangement = Arrangement.spacedBy(F7Spacing.sm),
        verticalAlignment = Alignment.CenterVertically,
    ) {
        FilterChip("Тип файла", onTypeClick)
        FilterChip("Участники", onParticipantsClick)
        FilterChip("Изменен", onModifiedClick)
    }
}

@Composable
private fun FilterChip(label: String, onClick: () -> Unit) {
    Box(
        modifier = Modifier
            .height(25.dp)
            .widthIn(min = 86.dp)
            .f7PillSurface(RoundedCornerShape(F7Radius.pill))
            .clickable(onClick = onClick)
            .padding(horizontal = F7Spacing.sm),
        contentAlignment = Alignment.Center,
    ) {
        Text(label, style = MaterialTheme.typography.bodyMedium, color = F7Colors.TextPrimary)
    }
}

/**
 * Карточка сетки (2 колонки): чекбокс 16 слева-сверху, зелёная звезда 16 справа-сверху
 * (только у избранных), иконка 80 по центру, имя 14/20 + ⋮ 16 снизу. Радиус 12, отступ 12.
 */
@Composable
fun FilesGridCard(
    serverUrl: String,
    item: FileItem,
    selected: Boolean,
    favorite: Boolean,
    onSelectedChange: () -> Unit,
    onOpenClick: () -> Unit,
    onMenuClick: () -> Unit,
    modifier: Modifier = Modifier,
) {
    val shape = RoundedCornerShape(12.dp)
    Column(
        modifier = modifier
            .clip(shape)
            .background(if (selected) F7Colors.PrimaryLight else F7Colors.Background)
            .border(1.dp, F7Colors.Border, shape)
            .clickable(onClick = onOpenClick)
            .padding(12.dp),
    ) {
        Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
            F7ThemeCheckbox(checked = selected, onToggle = onSelectedChange)
            Box(modifier = Modifier.weight(1f))
            if (favorite) {
                AsyncImage(
                    model = FileIcons.chromeAsset("star-green-full.svg"),
                    contentDescription = "В избранном",
                    modifier = Modifier.size(16.dp),
                )
            }
        }
        Spacer(Modifier.height(F7Spacing.sm))
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .height(80.dp),
            contentAlignment = Alignment.Center,
        ) {
            AsyncImage(
                model = FileIcons.iconUrl(serverUrl, item.name, item.isDirectory),
                contentDescription = null,
                modifier = Modifier.size(80.dp),
            )
        }
        Spacer(Modifier.height(F7Spacing.sm))
        Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
            Text(
                text = item.name,
                modifier = Modifier.weight(1f),
                style = MaterialTheme.typography.bodyMedium,
                fontWeight = FontWeight.Medium,
                color = F7Colors.TextPrimary,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis,
            )
            AsyncImage(
                model = FileIcons.chromeAsset("dots-vertic-gray.svg"),
                contentDescription = "Меню",
                modifier = Modifier
                    .size(16.dp)
                    .clickable(onClick = onMenuClick),
            )
        }
    }
}

/** Пустое состояние: круг-иконка + заголовок + подзаголовок + опц. кнопка (макет F-11..16). */
@Composable
fun FilesEmptyState(
    iconUrl: String,
    title: String,
    subtitle: String,
    modifier: Modifier = Modifier,
    action: (@Composable () -> Unit)? = null,
) {
    Column(
        modifier = modifier
            .fillMaxWidth()
            .padding(top = 96.dp, start = F7Spacing.xxl, end = F7Spacing.xxl),
        horizontalAlignment = Alignment.CenterHorizontally,
    ) {
        Box(
            modifier = Modifier
                .size(72.dp)
                .clip(CircleShape)
                .background(F7Colors.SurfaceMuted),
            contentAlignment = Alignment.Center,
        ) {
            AsyncImage(model = iconUrl, contentDescription = null, modifier = Modifier.size(32.dp))
        }
        Spacer(Modifier.size(F7Spacing.lg))
        Text(
            title,
            style = MaterialTheme.typography.titleMedium,
            fontWeight = FontWeight.SemiBold,
            color = F7Colors.TextPrimary,
        )
        Spacer(Modifier.size(F7Spacing.xs))
        Text(
            subtitle,
            style = MaterialTheme.typography.bodySmall,
            color = F7Colors.TextSecondary,
            modifier = Modifier.fillMaxWidth(),
            textAlign = androidx.compose.ui.text.style.TextAlign.Center,
        )
        if (action != null) {
            Spacer(Modifier.size(F7Spacing.xl))
            action()
        }
    }
}
