package com.anypreta.bountyboard.ui.developer

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.anypreta.bountyboard.data.AppContainer
import com.anypreta.bountyboard.data.model.CustomerRef
import com.anypreta.bountyboard.data.model.Task
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import kotlinx.coroutines.launch

class BoardViewModel(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
    var customers by mutableStateOf<List<CustomerRef>>(emptyList())
        private set

    // Filters
    var query by mutableStateOf("")
    var customerId by mutableStateOf<String?>(null)
        private set
    var minBounty by mutableStateOf("")
    var sortByBounty by mutableStateOf(false)
        private set

    init {
        load()
    }

    fun setCustomer(id: String?) {
        customerId = id; load()
    }

    fun setSort(byBounty: Boolean) {
        sortByBounty = byBounty; load()
    }

    fun load() {
        loading = true; error = null
        viewModelScope.launch {
            try {
                val min = minBounty.toDoubleOrNull()
                val r = container.repo.call {
                    board(
                        customerId = customerId,
                        q = query.ifBlank { null },
                        minBounty = min,
                        sort = if (sortByBounty) "bounty" else null,
                    )
                }
                tasks = r.tasks
                customers = r.customers
            } catch (e: Exception) {
                error = e.message
            } finally {
                loading = false
            }
        }
    }

    fun claim(taskId: String, note: String?, onDone: (String?) -> Unit) {
        viewModelScope.launch {
            try {
                container.repo.action { claim(taskId, com.anypreta.bountyboard.data.net.ClaimBody(note?.ifBlank { null })) }
                load()
                onDone(null)
            } catch (e: Exception) {
                onDone(e.message)
            }
        }
    }

    fun customerName(id: String): String? = customers.firstOrNull { it.id == id }?.name
}
