package ru.forbion.f7cloud.feature.notes

import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
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.padding
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.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.lifecycle.viewmodel.compose.viewModel
import ru.forbion.f7cloud.core.auth.AuthSession
import ru.forbion.f7cloud.core.designsystem.F7AlertDialog
import ru.forbion.f7cloud.core.designsystem.F7CreateButton
import ru.forbion.f7cloud.core.designsystem.F7ListCard
import ru.forbion.f7cloud.core.designsystem.F7ModuleScreen
import ru.forbion.f7cloud.core.designsystem.F7OutlinedField
import ru.forbion.f7cloud.core.designsystem.F7SolidPrimaryButton
import ru.forbion.f7cloud.core.designsystem.F7Spacing

/**
 * Экран «Заметки» (P1): список с поиском и пустым состоянием, открытие заметки в редакторе,
 * диалог конфликта версий. Состав/поведение — по карте app-map/notes.md.
 */
@Composable
fun NotesScreen(
    session: AuthSession,
    modifier: Modifier = Modifier,
    createRequest: Int = 0,
    onUnauthorized: () -> Unit = {},
) {
    val context = LocalContext.current
    val vm: NotesViewModel = viewModel(factory = NotesViewModel.Factory(context))
    val state by vm.state.collectAsState()

    LaunchedEffect(session.serverUrl, session.username, session.davUserId) { vm.load(session) }
    LaunchedEffect(createRequest) { if (createRequest > 0) vm.createNote(session) }
    LaunchedEffect(state.unauthorized) { if (state.unauthorized) onUnauthorized() }

    val open = state.openNote
    if (open != null) {
        NoteEditorScreen(
            note = open,
            saving = state.saving,
            onContentSave = { vm.saveNote(session, it) },
            onToggleFavorite = { vm.toggleFavorite(session, open) },
            onDelete = { vm.deleteNote(session, open) },
            onBack = { vm.closeNote() },
            modifier = modifier,
        )
        ConflictDialog(
            conflict = state.conflict,
            onKeepMine = { vm.resolveConflictKeepMine(session) },
            onUseServer = { vm.resolveConflictUseServer() },
        )
        return
    }

    F7ModuleScreen(
        title = "Заметки",
        modifier = modifier,
        loading = state.loading,
        error = state.error,
        onRefresh = { vm.load(session) },
        headerActions = { F7CreateButton(onClick = { vm.createNote(session) }) },
    ) {
        F7OutlinedField(
            value = state.searchQuery,
            onValueChange = vm::setSearch,
            label = "Искать заметки",
            modifier = Modifier.fillMaxWidth().padding(bottom = F7Spacing.md),
        )

        if (state.isEmpty) {
            NotesEmptyState(onNewNote = { vm.createNote(session) })
        } else {
            Column(verticalArrangement = Arrangement.spacedBy(F7Spacing.sm)) {
                state.visibleNotes.forEach { note ->
                    NoteRow(
                        note = note,
                        onOpen = { vm.openNote(session, note.id) },
                        onToggleFavorite = { vm.toggleFavorite(session, note) },
                    )
                }
            }
        }
    }
    ConflictDialog(
        conflict = state.conflict,
        onKeepMine = { vm.resolveConflictKeepMine(session) },
        onUseServer = { vm.resolveConflictUseServer() },
    )
}

@Composable
private fun NoteRow(note: Note, onOpen: () -> Unit, onToggleFavorite: () -> Unit) {
    F7ListCard(onClick = onOpen) {
        Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
            Text(
                text = if (note.favorite) "★" else "☆",
                modifier = Modifier.clickable(onClick = onToggleFavorite).padding(end = F7Spacing.sm),
            )
            Column(modifier = Modifier.weight(1f)) {
                Text(
                    text = note.title.ifBlank { "Без названия" },
                    fontWeight = FontWeight.SemiBold,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis,
                )
                if (note.category.isNotBlank()) {
                    Text(text = note.category, maxLines = 1, overflow = TextOverflow.Ellipsis)
                }
            }
        }
    }
}

@Composable
private fun NotesEmptyState(onNewNote: () -> Unit) {
    Column(
        horizontalAlignment = Alignment.CenterHorizontally,
        modifier = Modifier.fillMaxWidth().padding(F7Spacing.lg),
    ) {
        Text(text = "Заметки", fontWeight = FontWeight.Bold)
        Spacer(Modifier.height(F7Spacing.sm))
        Text(text = "Начните писать заметку, нажав «Новая заметка».")
        Spacer(Modifier.height(F7Spacing.md))
        F7SolidPrimaryButton(text = "Новая заметка", onClick = onNewNote)
    }
}

@Composable
private fun ConflictDialog(conflict: NoteConflictException?, onKeepMine: () -> Unit, onUseServer: () -> Unit) {
    if (conflict == null) return
    F7AlertDialog(
        title = "Конфликт версий",
        onDismiss = onUseServer,
        confirmText = "Оставить мою версию",
        onConfirm = onKeepMine,
        dismissText = "Версия сервера",
    ) {
        Text("Заметка была изменена в другой сессии. Выберите, какую версию сохранить.")
    }
}
