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 kotlinx.coroutines.launch

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

    init {
        refresh()
    }

    fun refresh() {
        viewModelScope.launch {
            isLoading = true
            error = null
            try {
                tasks = ApiClient.taskApi.list()
            } 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 delete(id: Int) {
        viewModelScope.launch {
            try {
                ApiClient.taskApi.delete(id)
                tasks = tasks.filter { it.id != id }
            } catch (e: Exception) {
                error = e.message
            }
        }
    }
}
