package ru.forbion.f7cloud.feature.deck

import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.lifecycle.viewmodel.compose.viewModel
import ru.forbion.f7cloud.core.auth.AuthSession
import ru.forbion.f7cloud.core.designsystem.F7ListCard
import ru.forbion.f7cloud.core.designsystem.F7ModuleScreen
import ru.forbion.f7cloud.core.designsystem.F7OverlayDismissHandler
import ru.forbion.f7cloud.core.designsystem.F7SecondaryButton

@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()

    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 = {
            if (state.selectedBoardId != null) {
                F7SecondaryButton(text = "Назад", onClick = { vm.closeBoard() })
            }
        },
    ) {
        val detail = state.boardDetail
        if (detail != null) {
            LazyColumn(modifier = Modifier.fillMaxSize()) {
                items(detail.stacks, key = { it.id }) { stack ->
                    F7ListCard {
                        Text(stack.title, style = MaterialTheme.typography.titleSmall)
                        stack.cards.forEach { card ->
                            val prefix = if (card.done) "✓ " else "• "
                            Text(prefix + card.title, style = MaterialTheme.typography.bodyMedium)
                        }
                    }
                }
            }
        } else {
            LazyColumn(modifier = Modifier.fillMaxSize()) {
                items(state.boards, key = { it.id }) { board ->
                    F7ListCard(onClick = { vm.openBoard(session, board.id) }) {
                        Text(board.title, style = MaterialTheme.typography.titleSmall)
                    }
                }
            }
        }
    }
}
