package com.anypreta.bountyboard.ui.developer

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
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.material.icons.Icons
import androidx.compose.material.icons.outlined.Assignment
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
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
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.compose.viewModel
import com.anypreta.bountyboard.data.AppContainer
import com.anypreta.bountyboard.data.model.Task
import com.anypreta.bountyboard.di.LocalAppContainer
import com.anypreta.bountyboard.di.containerVMFactory
import com.anypreta.bountyboard.ui.components.EmptyState
import com.anypreta.bountyboard.ui.components.ScreenState
import com.anypreta.bountyboard.ui.components.TaskCard
import com.anypreta.bountyboard.ui.theme.BB
import com.anypreta.bountyboard.ui.theme.SplineMono
import kotlinx.coroutines.launch

class MyTasksViewModel(private val container: AppContainer) : ViewModel() {

    var loading by mutableStateOf(true)
        private set
    var error by mutableStateOf<String?>(null)
        private set
    var tasks by mutableStateOf<List<Task>>(emptyList())
        private set

    init {
        load()
    }

    fun load() {
        loading = true; error = null
        viewModelScope.launch {
            try {
                val r = container.repo.call { myTasks() }
                tasks = r.tasks
            } catch (e: Exception) {
                error = e.message
            } finally {
                loading = false
            }
        }
    }
}

private data class KanbanSection(val title: String, val match: (String) -> Boolean)

private val kanbanSections = listOf(
    KanbanSection("Assigned") { it == "assigned" },
    KanbanSection("In progress") { it == "in_progress" || it == "changes_requested" },
    KanbanSection("In review") { it == "in_review" },
    KanbanSection("Done") { it == "approved" },
)

@Composable
fun MyTasksScreen(onOpenTask: (String) -> Unit) {
    val container = LocalAppContainer.current
    val vm: MyTasksViewModel = viewModel(factory = containerVMFactory(container) { MyTasksViewModel(it) })
    val p = BB.colors

    ScreenState(loading = vm.loading, error = vm.error, onRetry = { vm.load() }) {
        if (vm.tasks.isEmpty()) {
            EmptyState(
                title = "Nothing on your plate",
                subtitle = "Tasks you've been assigned or are working on will appear here, grouped by status.",
                icon = Icons.Outlined.Assignment,
            )
        } else {
            LazyColumn(
                contentPadding = PaddingValues(16.dp),
                verticalArrangement = Arrangement.spacedBy(14.dp),
            ) {
                kanbanSections.forEach { section ->
                    val sectionTasks = vm.tasks.filter { section.match(it.status) }
                    item(key = "header-${section.title}") {
                        Row(
                            Modifier.fillMaxWidth().padding(top = 6.dp, bottom = 2.dp),
                            verticalAlignment = Alignment.CenterVertically,
                            horizontalArrangement = Arrangement.spacedBy(8.dp),
                        ) {
                            Text(
                                section.title.uppercase(),
                                style = MaterialTheme.typography.labelMedium,
                                fontFamily = SplineMono,
                                color = p.muted,
                            )
                            Text(
                                sectionTasks.size.toString(),
                                style = MaterialTheme.typography.labelMedium,
                                fontFamily = SplineMono,
                                color = p.accent,
                            )
                        }
                    }
                    if (sectionTasks.isEmpty()) {
                        item(key = "empty-${section.title}") {
                            Text(
                                "—",
                                style = MaterialTheme.typography.bodyMedium,
                                color = p.muted,
                                modifier = Modifier.padding(start = 4.dp, bottom = 4.dp),
                            )
                        }
                    } else {
                        items(sectionTasks, key = { it.id }) { task ->
                            TaskCard(
                                task = task,
                                onClick = { onOpenTask(task.id) },
                                showStatus = true,
                            )
                        }
                    }
                }
            }
        }
    }
}
