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.TaskRequest
import de.haushalt.app.data.TaskStatus
import kotlinx.coroutines.launch

class TaskEditViewModel : ViewModel() {
    var name by mutableStateOf("")
    var date by mutableStateOf("")
    var status by mutableStateOf(TaskStatus.active)
    var availableStatuses by mutableStateOf<List<TaskStatus>>(emptyList())
        private set
    var isLoading by mutableStateOf(false)
        private set
    var isSubmitting by mutableStateOf(false)
        private set
    var error by mutableStateOf<String?>(null)
        private set

    init {
        viewModelScope.launch {
            try {
                availableStatuses = ApiClient.taskApi.statuses()
            } catch (e: Exception) {
                availableStatuses = emptyList()
            }
        }
    }

    fun load(id: Int) {
        viewModelScope.launch {
            isLoading = true
            error = null
            try {
                val task = ApiClient.taskApi.get(id)
                applyTask(task)
            } catch (e: Exception) {
                error = e.message
            } finally {
                isLoading = false
            }
        }
    }

    fun update(id: Int, onSuccess: () -> Unit) {
        viewModelScope.launch {
            isSubmitting = true
            error = null
            try {
                ApiClient.taskApi.update(
                    id,
                    TaskRequest(
                        name = name,
                        date = date.ifBlank { null },
                        status = status,
                    )
                )
                onSuccess()
            } catch (e: Exception) {
                error = e.message
            } finally {
                isSubmitting = false
            }
        }
    }

    private fun applyTask(task: Task) {
        name = task.name
        date = task.date?.take(10) ?: ""
        status = task.status
    }
}
