package ru.forbion.f7cloud.feature.tasks

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Text
import androidx.compose.material3.ExperimentalMaterial3Api
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.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.F7OverlayDismissHandler

@Composable
fun TasksScreen(
    session: AuthSession,
    modifier: Modifier = Modifier,
    createRequest: Int = 0,
    openListSlug: String? = null,
    showListsRequest: Int = 0,
    onOpenListConsumed: () -> Unit = {},
    onUnauthorized: () -> Unit = {},
) {
    val vm: TasksViewModel = viewModel()
    val state by vm.state.collectAsState()
    // Родитель для создаваемой подзадачи (открывает диалог ввода названия).
    var subtaskParent by remember { mutableStateOf<TaskItem?>(null) }

    // Стрелка «назад» нижней панели на Задачах → показать панель списков (закрыть открытый список).
    LaunchedEffect(showListsRequest) {
        if (showListsRequest > 0) vm.closeList()
    }

    LaunchedEffect(session.serverUrl, session.username, session.davUserId) {
        vm.load(session)
    }
    LaunchedEffect(createRequest) {
        if (createRequest > 0) {
            if (state.selectedListHref == null && state.lists.isNotEmpty()) {
                vm.openList(session, state.lists.first().href)
            }
            vm.expandCreateInput()
        }
    }
    LaunchedEffect(openListSlug, state.lists) {
        if (!openListSlug.isNullOrBlank() && state.lists.isNotEmpty()) {
            vm.openListBySlug(session, openListSlug)
            onOpenListConsumed()
        }
    }
    LaunchedEffect(state.unauthorized) {
        if (state.unauthorized) onUnauthorized()
    }

    F7OverlayDismissHandler(
        enabled = state.detailTask != null,
        onDismiss = vm::closeDetail,
    )
    F7OverlayDismissHandler(
        enabled = state.settingsOpen,
        onDismiss = vm::closeSettings,
    )

    Box(
        modifier = modifier
            .fillMaxSize()
            .background(F7Colors.Background)
            .padding(horizontal = 8.dp, vertical = 8.dp),
    ) {
        when {
            state.loading && state.lists.isEmpty() -> {
                Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
                    CircularProgressIndicator(color = F7Colors.Primary)
                }
            }
            state.selectedListHref == null -> {
                TasksListNavView(
                    serverUrl = session.serverUrl,
                    lists = state.lists,
                    selectedHref = null,
                    onListClick = { vm.openList(session, it.href) },
                )
            }
            else -> {
                TasksMainContent(
                    session = session,
                    state = state,
                    onCreateExpand = vm::expandCreateInput,
                    onCreateCollapse = vm::collapseCreateInput,
                    onCreateTextChange = vm::setCreateInputText,
                    onCreateSubmit = { vm.submitCreateInput(session) },
                    onFilterClick = vm::openSettings,
                    onSortClick = vm::toggleSortOrder,
                    onMoreClick = vm::closeList,
                    onToggleComplete = { vm.toggleComplete(session, it) },
                    onOpenTask = vm::openDetail,
                    onReload = { vm.refreshTasks(session) },
                    onToggleCompletedExpanded = vm::toggleCompletedExpanded,
                    onDeleteCompleted = { vm.deleteCompletedTasks(session) },
                    onAddSubtask = { subtaskParent = it },
                    onDeleteTask = { vm.deleteTask(session, it) },
                )
            }
        }

        state.error?.let { error ->
            Text(
                error,
                color = F7Colors.Error,
                modifier = Modifier
                    .align(Alignment.BottomCenter)
                    .padding(bottom = 96.dp),
            )
        }
    }

    TaskDetailSheet(
        visible = state.detailTask != null,
        serverUrl = session.serverUrl,
        task = state.detailTask,
        saving = state.saving,
        onDismiss = vm::closeDetail,
        onSwipeBack = vm::closeDetail,
        onToggleComplete = {
            state.detailTask?.let { vm.toggleComplete(session, it) }
        },
        onSave = { summary, due, priority, description ->
            vm.saveDetail(session, summary, due, priority, description)
        },
        onDelete = { vm.deleteDetail(session) },
    )

    TasksSettingsSheet(
        visible = state.settingsOpen,
        serverUrl = session.serverUrl,
        lists = state.lists,
        defaultListHref = state.defaultListHref,
        onDefaultListChange = vm::setDefaultList,
        onDismiss = vm::closeSettings,
        onSwipeBack = vm::closeSettings,
    )

    // Диалог «Добавить вложенную задачу»
    subtaskParent?.let { parent ->
        TaskSubtaskDialog(
            parentTitle = parent.summary,
            onConfirm = { title ->
                vm.createSubtask(session, parent, title)
                subtaskParent = null
            },
            onDismiss = { subtaskParent = null },
        )
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun TasksMainContent(
    session: AuthSession,
    state: TasksUiState,
    onCreateExpand: () -> Unit,
    onCreateCollapse: () -> Unit,
    onCreateTextChange: (String) -> Unit,
    onCreateSubmit: () -> Unit,
    onFilterClick: () -> Unit,
    onSortClick: () -> Unit,
    onMoreClick: () -> Unit,
    onToggleComplete: (TaskItem) -> Unit,
    onOpenTask: (TaskItem) -> Unit,
    onReload: () -> Unit,
    onToggleCompletedExpanded: () -> Unit,
    onDeleteCompleted: () -> Unit,
    onAddSubtask: (TaskItem) -> Unit,
    onDeleteTask: (TaskItem) -> Unit,
) {
    // Подзадачи (RELATED-TO) — рисуем под родителем с отступом; из верхнего уровня исключаем.
    val childrenByParent = remember(state.visibleActiveGroups) {
        state.visibleActiveGroups.flatMap { it.tasks }
            .filter { it.parentUid.isNotBlank() }
            .groupBy { it.parentUid }
    }
    Column(modifier = Modifier.fillMaxSize()) {
        TasksToolbar(
            serverUrl = session.serverUrl,
            createExpanded = state.createInputExpanded,
            createText = state.createInputText,
            saving = state.saving,
            onCreateTextChange = onCreateTextChange,
            onCreateExpand = onCreateExpand,
            onCreateCollapse = onCreateCollapse,
            onCreateSubmit = onCreateSubmit,
            onFilterClick = onFilterClick,
            onSortClick = onSortClick,
            onMoreClick = onMoreClick,
        )

        if (state.loading && state.tasks.isEmpty()) {
            Box(
                modifier = Modifier.fillMaxSize(),
                contentAlignment = Alignment.Center,
            ) {
                CircularProgressIndicator(color = F7Colors.Primary)
            }
        } else if (state.showEmptyState) {
            TasksEmptyState(
                serverUrl = session.serverUrl,
                loading = state.loading,
                onReload = onReload,
                modifier = Modifier.fillMaxWidth(),
            )
        } else {
            PullToRefreshBox(
                isRefreshing = state.loading,
                onRefresh = onReload,
                modifier = Modifier
                    .weight(1f)
                    .fillMaxWidth(),
            ) {
            LazyColumn(
                modifier = Modifier.fillMaxSize(),
                verticalArrangement = Arrangement.spacedBy(8.dp),
            ) {
                state.visibleActiveGroups.forEach { group ->
                    item(key = "header-${group.title}") {
                        TasksGroupHeader(
                            title = group.title,
                            accentColor = group.accentColor,
                            modifier = Modifier.padding(bottom = 4.dp),
                        )
                    }
                    items(group.tasks.filter { it.parentUid.isBlank() }, key = { it.uid }) { task ->
                        Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
                            TasksRow(
                                task = task,
                                serverUrl = session.serverUrl,
                                onToggleComplete = { onToggleComplete(task) },
                                onOpen = { onOpenTask(task) },
                                onAddSubtask = { onAddSubtask(task) },
                                onDelete = { onDeleteTask(task) },
                            )
                            childrenByParent[task.uid].orEmpty().forEach { sub ->
                                TasksRow(
                                    task = sub,
                                    serverUrl = session.serverUrl,
                                    onToggleComplete = { onToggleComplete(sub) },
                                    onOpen = { onOpenTask(sub) },
                                    onDelete = { onDeleteTask(sub) },
                                    modifier = Modifier.padding(start = 24.dp),
                                )
                            }
                        }
                    }
                }

                if (state.completedTasks.isNotEmpty()) {
                    item(key = "completed-section") {
                        TasksCompletedSection(
                            serverUrl = session.serverUrl,
                            tasks = state.completedTasks,
                            expanded = state.completedExpanded,
                            listName = state.selectedList?.displayName ?: "",
                            deleting = state.deletingCompleted,
                            onToggleExpanded = onToggleCompletedExpanded,
                            onToggleComplete = onToggleComplete,
                            onOpen = onOpenTask,
                            onDeleteCompleted = onDeleteCompleted,
                            modifier = Modifier.padding(top = 8.dp),
                        )
                    }
                }
            }
            }
        }
    }
}
