package de.haushalt.app.ui.task

import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import de.haushalt.app.data.ApiClient
import de.haushalt.app.data.Task
import de.haushalt.app.data.TaskStatus
import kotlinx.coroutines.launch

class TaskListViewModel : ViewModel() {
    var tasks by mutableStateOf<List<Task>>(emptyList())
        private set
    var showDone by mutableStateOf(false)
    var isLoading by mutableStateOf(false)
        private set
    var error by mutableStateOf<String?>(null)
        private set

    val visibleTasks: List<Task>
        get() = if (showDone) tasks else tasks.filter { it.status != TaskStatus.done }

    val groupedTasks: Map<String, List<Task>>
        get() = visibleTasks.groupBy { task -> task.date?.let { formatDate(it) } ?: "" }

    init {
        refresh()
    }

    fun refresh() {
        viewModelScope.launch {
            isLoading = true
            error = null
            try {
                tasks = ApiClient.taskApi.list("current")
            } catch (e: Exception) {
                error = e.message
            } finally {
                isLoading = false
            }
        }
    }

    fun toggle(id: Int) {
        viewModelScope.launch {
            try {
                val updated = ApiClient.taskApi.toggle(id)
                tasks = tasks.map { if (it.id == id) updated else it }
            } catch (e: Exception) {
                error = e.message
            }
        }
    }

    fun toggleShowDone() {
        showDone = !showDone
    }
}
