package ru.forbion.f7cloud.feature.deck

import androidx.compose.foundation.background
import androidx.compose.foundation.border
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.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
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.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.pulltorefresh.PullToRefreshBox
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
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.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import ru.forbion.f7cloud.core.auth.AuthSession
import ru.forbion.f7cloud.core.designsystem.F7Colors
import ru.forbion.f7cloud.core.designsystem.F7ModuleScreen
import ru.forbion.f7cloud.core.designsystem.F7OverlayDismissHandler
import ru.forbion.f7cloud.core.designsystem.F7SecondaryButton

@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class)
@Composable
fun DeckScreen(
    session: AuthSession,
    modifier: Modifier = Modifier,
    openCardId: Int? = null,
    onOpenCardConsumed: () -> Unit = {},
    onUnauthorized: () -> Unit = {},
) {
    val vm: DeckViewModel = viewModel()
    val state by vm.state.collectAsState()
    var addStackOpen by remember { mutableStateOf(false) }
    var addCardStackId by remember { mutableStateOf<Int?>(null) }

    LaunchedEffect(session.serverUrl, session.username) { vm.load(session) }
    LaunchedEffect(openCardId) {
        val cardId = openCardId ?: return@LaunchedEffect
        vm.openCardById(session, cardId)
        onOpenCardConsumed()
    }
    LaunchedEffect(state.unauthorized) { if (state.unauthorized) onUnauthorized() }

    F7OverlayDismissHandler(enabled = state.boardDetail != null, onDismiss = vm::closeBoard)

    F7ModuleScreen(
        modifier = modifier,
        loading = state.loading && state.boards.isEmpty() && state.boardDetail == null,
        error = state.error,
        onRefresh = { vm.load(session) },
        headerActions = {
            val detail = state.boardDetail
            if (detail != null) {
                if (detail.canEdit) {
                    F7SecondaryButton(text = "+ Колонка", onClick = { addStackOpen = true })
                    Spacer(Modifier.size(8.dp))
                }
                F7SecondaryButton(text = "Назад", onClick = { vm.closeBoard() })
            }
        },
    ) {
        val detail = state.boardDetail
        PullToRefreshBox(
            isRefreshing = state.loading && (state.boards.isNotEmpty() || detail != null),
            onRefresh = {
                if (detail != null) vm.openBoard(session, detail.boardId) else vm.load(session)
            },
            modifier = Modifier.weight(1f).fillMaxWidth(),
        ) {
            if (detail != null) {
                LazyColumn(
                    modifier = Modifier.fillMaxSize(),
                    contentPadding = androidx.compose.foundation.layout.PaddingValues(bottom = 24.dp),
                    verticalArrangement = Arrangement.spacedBy(12.dp),
                ) {
                    items(detail.stacks, key = { it.id }) { stack ->
                        DeckStackSection(
                            stack = stack,
                            canEdit = detail.canEdit,
                            onCardClick = { vm.openCard(it) },
                            onToggleDone = { vm.toggleDone(session, it) },
                            onAddCard = { addCardStackId = stack.id },
                        )
                    }
                }
            } else {
                LazyColumn(
                    modifier = Modifier.fillMaxSize(),
                    contentPadding = androidx.compose.foundation.layout.PaddingValues(vertical = 8.dp),
                    verticalArrangement = Arrangement.spacedBy(8.dp),
                ) {
                    items(state.boards, key = { it.id }) { board ->
                        DeckBoardRow(board = board, onClick = { vm.openBoard(session, board.id) })
                    }
                }
            }
        }
    }

    // Карточка-деталь
    state.openedCard?.let { card ->
        DeckCardSheet(
            card = card,
            boardLabels = state.boardDetail?.labels.orEmpty(),
            stacks = state.boardDetail?.stacks.orEmpty(),
            canEdit = state.boardDetail?.canEdit ?: false,
            busy = state.busy,
            onDismiss = vm::closeCard,
            onToggleDone = { vm.toggleDone(session, card) },
            onSave = { title, desc, due -> vm.updateCard(session, card, title, desc, due) },
            onToggleLabel = { vm.toggleLabel(session, card, it) },
            onMove = { vm.moveCard(session, card, it) },
            onArchive = { vm.archiveCard(session, card) },
            onDelete = { vm.deleteCard(session, card) },
        )
    }

    if (addStackOpen) {
        DeckTextPromptDialog(
            title = "Новая колонка",
            label = "Название колонки",
            confirmText = "Создать",
            onConfirm = { vm.createStack(session, it); addStackOpen = false },
            onDismiss = { addStackOpen = false },
        )
    }
    addCardStackId?.let { stackId ->
        DeckTextPromptDialog(
            title = "Новая карточка",
            label = "Название карточки",
            confirmText = "Создать",
            onConfirm = { vm.createCard(session, stackId, it); addCardStackId = null },
            onDismiss = { addCardStackId = null },
        )
    }
}

@Composable
private fun DeckBoardRow(board: DeckBoard, onClick: () -> Unit) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .clip(RoundedCornerShape(8.dp))
            .background(Color(0xFFFDFDFD))
            .border(1.dp, Color(0xFFF0F1F4), RoundedCornerShape(8.dp))
            .clickable(onClick = onClick)
            .padding(horizontal = 12.dp, vertical = 14.dp),
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.spacedBy(10.dp),
    ) {
        Box(
            modifier = Modifier
                .size(12.dp)
                .clip(CircleShape)
                .background(parseDeckColor(board.color) ?: F7Colors.Primary),
        )
        Text(
            board.title,
            modifier = Modifier.weight(1f),
            style = MaterialTheme.typography.bodyLarge,
            fontWeight = FontWeight.Medium,
            color = F7Colors.TextPrimary,
            maxLines = 1,
            overflow = TextOverflow.Ellipsis,
        )
    }
}

@OptIn(ExperimentalLayoutApi::class)
@Composable
private fun DeckStackSection(
    stack: DeckStack,
    canEdit: Boolean,
    onCardClick: (DeckCard) -> Unit,
    onToggleDone: (DeckCard) -> Unit,
    onAddCard: () -> Unit,
) {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .clip(RoundedCornerShape(8.dp))
            .background(F7Colors.Grey2)
            .padding(8.dp),
        verticalArrangement = Arrangement.spacedBy(6.dp),
    ) {
        Row(verticalAlignment = Alignment.CenterVertically) {
            Text(
                stack.title,
                modifier = Modifier.weight(1f),
                style = MaterialTheme.typography.titleSmall,
                fontWeight = FontWeight.SemiBold,
                color = F7Colors.TextPrimary,
            )
            Text(
                stack.cards.size.toString(),
                style = MaterialTheme.typography.bodyMedium,
                color = F7Colors.TextSecondary,
            )
            if (canEdit) {
                Spacer(Modifier.size(8.dp))
                Box(
                    modifier = Modifier
                        .size(28.dp)
                        .clip(CircleShape)
                        .background(F7Colors.PrimaryLight)
                        .clickable(onClick = onAddCard),
                    contentAlignment = Alignment.Center,
                ) {
                    Icon(Icons.Filled.Add, contentDescription = "Добавить карточку", tint = F7Colors.Primary, modifier = Modifier.size(18.dp))
                }
            }
        }
        stack.cards.forEach { card ->
            DeckCardRow(card = card, onClick = { onCardClick(card) }, onToggleDone = { onToggleDone(card) })
        }
        if (stack.cards.isEmpty()) {
            Text("Нет карточек", style = MaterialTheme.typography.bodyMedium, color = F7Colors.TextSecondary)
        }
    }
}

@OptIn(ExperimentalLayoutApi::class)
@Composable
private fun DeckCardRow(card: DeckCard, onClick: () -> Unit, onToggleDone: () -> Unit) {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .clip(RoundedCornerShape(8.dp))
            .background(Color(0xFFFDFDFD))
            .border(1.dp, F7Colors.Border, RoundedCornerShape(8.dp))
            .clickable(onClick = onClick)
            .padding(10.dp),
        verticalArrangement = Arrangement.spacedBy(4.dp),
    ) {
        if (card.labels.isNotEmpty()) {
            FlowRow(horizontalArrangement = Arrangement.spacedBy(4.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
                card.labels.forEach { DeckLabelChip(it) }
            }
        }
        Row(verticalAlignment = Alignment.CenterVertically) {
            Box(
                modifier = Modifier
                    .size(20.dp)
                    .clip(RoundedCornerShape(4.dp))
                    .border(1.5.dp, if (card.done) F7Colors.Primary else F7Colors.Grey1, RoundedCornerShape(4.dp))
                    .background(if (card.done) F7Colors.Primary else Color.Transparent)
                    .clickable(onClick = onToggleDone),
                contentAlignment = Alignment.Center,
            ) {
                if (card.done) Text("✓", color = Color.White, style = MaterialTheme.typography.labelSmall)
            }
            Spacer(Modifier.size(8.dp))
            Text(
                card.title,
                modifier = Modifier.weight(1f),
                style = MaterialTheme.typography.bodyMedium,
                color = F7Colors.TextPrimary,
                maxLines = 3,
                overflow = TextOverflow.Ellipsis,
            )
        }
        val due = card.duedate?.let { formatDeckDue(it) }
        if (due != null || card.assignees.isNotEmpty()) {
            Row(
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.spacedBy(8.dp),
                modifier = Modifier.padding(start = 28.dp),
            ) {
                if (due != null) {
                    Text("🗓 $due", style = MaterialTheme.typography.labelMedium, color = F7Colors.TextSecondary)
                }
                if (card.assignees.isNotEmpty()) {
                    Text("👤 ${card.assignees.joinToString(", ")}", style = MaterialTheme.typography.labelMedium, color = F7Colors.TextSecondary, maxLines = 1, overflow = TextOverflow.Ellipsis)
                }
            }
        }
    }
}

@Composable
internal fun DeckLabelChip(label: DeckLabel) {
    val bg = parseDeckColor(label.color) ?: F7Colors.Primary
    Box(
        modifier = Modifier
            .clip(RoundedCornerShape(4.dp))
            .background(bg.copy(alpha = 0.22f))
            .border(1.dp, bg, RoundedCornerShape(4.dp))
            .padding(horizontal = 6.dp, vertical = 1.dp),
    ) {
        Text(
            label.title,
            style = MaterialTheme.typography.labelMedium,
            color = F7Colors.TextPrimary,
            maxLines = 1,
            overflow = TextOverflow.Ellipsis,
        )
    }
}

/** Цвет Deck («RRGGBB» без #, иногда с #). */
internal fun parseDeckColor(hex: String?): Color? {
    val h = hex?.trim()?.removePrefix("#")?.takeIf { it.length == 6 } ?: return null
    return runCatching { Color(("FF$h").toLong(16)) }.getOrNull()
}
