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.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.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.List
import androidx.compose.material.icons.filled.GridView
import androidx.compose.material.icons.filled.Home
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.Star
import androidx.compose.material.icons.filled.StarBorder
import androidx.compose.material3.Checkbox
import androidx.compose.material3.CheckboxDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
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.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

enum class FilesViewMode { List, Grid }

/** Квадратная кнопка-переключатель вида список⇄сетка справа от поиска (макет F-17/F-22). */
@Composable
fun FilesViewToggleButton(viewMode: FilesViewMode, onToggle: () -> Unit) {
    Box(
        modifier = Modifier
            .size(40.dp)
            .clip(RoundedCornerShape(F7Radius.md))
            .background(F7Colors.SecondaryButtonBg)
            .border(1.dp, F7Colors.Border, RoundedCornerShape(F7Radius.md))
            .clickable(onClick = onToggle),
        contentAlignment = Alignment.Center,
    ) {
        Icon(
            imageVector = if (viewMode == FilesViewMode.List) Icons.Filled.GridView else Icons.AutoMirrored.Filled.List,
            contentDescription = "Сменить вид",
            tint = F7Colors.TextSecondary,
            modifier = Modifier.size(20.dp),
        )
    }
}

/** Хлебные крошки: домой + сегменты пути через ›, прокрутка по горизонтали (макет F-21/F-22). */
@Composable
fun FilesBreadcrumb(
    segments: List<String>,
    onHomeClick: () -> Unit,
    onSegmentClick: (index: Int) -> Unit,
    modifier: Modifier = Modifier,
) {
    Row(
        modifier = modifier
            .fillMaxWidth()
            .horizontalScroll(rememberScrollState())
            .padding(vertical = F7Spacing.sm),
        verticalAlignment = Alignment.CenterVertically,
    ) {
        Icon(
            imageVector = Icons.Filled.Home,
            contentDescription = "В начало",
            tint = F7Colors.TextSecondary,
            modifier = Modifier
                .size(22.dp)
                .clickable(onClick = onHomeClick),
        )
        segments.forEachIndexed { i, seg ->
            Text(" › ", style = MaterialTheme.typography.bodyMedium, color = F7Colors.TextSecondary)
            Text(
                text = seg,
                style = MaterialTheme.typography.bodyMedium,
                color = if (i == segments.lastIndex) F7Colors.TextPrimary else F7Colors.TextSecondary,
                maxLines = 1,
                modifier = Modifier.clickable { onSegmentClick(i) },
            )
        }
    }
}

/** Ряд фильтр-чипов: Тип файла / Участники / Изменен (макет F-18/F-22). */
@Composable
fun FilesFilterChips(
    onTypeClick: () -> Unit,
    onParticipantsClick: () -> Unit,
    onModifiedClick: () -> Unit,
    modifier: Modifier = Modifier,
) {
    Row(
        modifier = modifier
            .fillMaxWidth()
            .horizontalScroll(rememberScrollState())
            .padding(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
            .clip(RoundedCornerShape(F7Radius.pill))
            .border(1.dp, F7Colors.Border, RoundedCornerShape(F7Radius.pill))
            .clickable(onClick = onClick)
            .padding(horizontal = F7Spacing.md, vertical = F7Spacing.xs),
    ) {
        Text(label, style = MaterialTheme.typography.bodyMedium, color = F7Colors.TextSecondary)
    }
}

/** Карточка сетки: чекбокс + звезда сверху, крупная иконка по центру, имя + ⋮ снизу (макет F-17). */
@Composable
fun FilesGridCard(
    serverUrl: String,
    item: FileItem,
    selected: Boolean,
    favorite: Boolean,
    onSelectedChange: () -> Unit,
    onOpenClick: () -> Unit,
    onMenuClick: () -> Unit,
    modifier: Modifier = Modifier,
) {
    Column(
        modifier = modifier
            .clip(RoundedCornerShape(F7Radius.lg))
            .background(if (selected) F7Colors.PrimaryLight else F7Colors.Surface)
            .border(1.dp, F7Colors.Border, RoundedCornerShape(F7Radius.lg))
            .clickable(onClick = onOpenClick)
            .padding(F7Spacing.md),
    ) {
        Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
            Checkbox(
                checked = selected,
                onCheckedChange = { onSelectedChange() },
                colors = CheckboxDefaults.colors(checkedColor = F7Colors.Primary),
            )
            Spacer(Modifier.width(F7Spacing.sm))
            Box(modifier = Modifier.weight(1f))
            Icon(
                imageVector = if (favorite) Icons.Filled.Star else Icons.Filled.StarBorder,
                contentDescription = null,
                tint = if (favorite) F7Colors.Primary else F7Colors.TextMuted,
                modifier = Modifier.size(18.dp),
            )
        }
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .padding(vertical = F7Spacing.lg),
            contentAlignment = Alignment.Center,
        ) {
            AsyncImage(
                model = FileIcons.iconUrl(serverUrl, item.name, item.isDirectory),
                contentDescription = null,
                modifier = Modifier.size(48.dp),
            )
        }
        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,
            )
            Icon(
                imageVector = Icons.Filled.MoreVert,
                contentDescription = "Меню",
                tint = F7Colors.TextSecondary,
                modifier = Modifier
                    .size(18.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(RoundedCornerShape(F7Radius.pill))
                .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()
        }
    }
}
