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.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,
    onOpenListConsumed: () -> Unit = {},
    onUnauthorized: () -> Unit = {},
) {
    val vm: TasksViewModel = viewModel()
    val state by vm.state.collectAsState()

    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) },
                )
            }
        }

        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,
    )
}

@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,
) {
    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, key = { it.uid }) { task ->
                        TasksRow(
                            task = task,
                            serverUrl = session.serverUrl,
                            onToggleComplete = { onToggleComplete(task) },
                            onOpen = { onOpenTask(task) },
                        )
                    }
                }

                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),
                        )
                    }
                }
            }
            }
        }
    }
}
