package de.haushalt.app.ui.schema

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.TaskSchemaRequest
import de.haushalt.app.data.TaskSchemaStatus
import de.haushalt.app.data.TaskStatus
import kotlinx.coroutines.launch
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.buildJsonArray

class SchemaCreateViewModel : ViewModel() {
    var name by mutableStateOf("")
    var status by mutableStateOf(TaskSchemaStatus.active)
    var taskStatus by mutableStateOf(TaskStatus.active)
    var repeatType by mutableStateOf("none")
    var date by mutableStateOf("")
    var start by mutableStateOf("")
    var end by mutableStateOf("")
    var weekly by mutableStateOf(List(7) { false })
    var monthly by mutableStateOf(List(31) { false })
    var days by mutableStateOf(listOf<String>())
    var isSubmitting by mutableStateOf(false)
        private set
    var error by mutableStateOf<String?>(null)
        private set

    fun save(onSuccess: () -> Unit) {
        viewModelScope.launch {
            isSubmitting = true
            error = null
            try {
                ApiClient.schemaApi.create(buildRequest())
                onSuccess()
            } catch (e: Exception) {
                error = e.message
            } finally {
                isSubmitting = false
            }
        }
    }

    private fun buildRequest(): TaskSchemaRequest {
        val repeat = when (repeatType) {
            "daily" -> JsonObject(mapOf("daily" to JsonPrimitive(true)))
            "weekly" -> JsonObject(mapOf("weekly" to buildJsonArray { weekly.forEach { add(JsonPrimitive(it)) } }))
            "2week" -> JsonObject(mapOf("2week" to buildJsonArray { weekly.forEach { add(JsonPrimitive(it)) } }))
            "4week" -> JsonObject(mapOf("4week" to buildJsonArray { weekly.forEach { add(JsonPrimitive(it)) } }))
            "monthly" -> JsonObject(mapOf("monthly" to buildJsonArray { monthly.forEach { add(JsonPrimitive(it)) } }))
            "days" -> JsonObject(mapOf("days" to buildJsonArray { days.filter { it.isNotBlank() }.forEach { add(JsonPrimitive(it)) } }))
            else -> null
        }

        return TaskSchemaRequest(
            name = name,
            status = status,
            taskStatus = taskStatus,
            date = if (repeatType == "none" && date.isNotBlank()) date else null,
            repeat = repeat,
            start = if (repeatType != "none" && start.isNotBlank()) start else null,
            end = if (repeatType != "none" && end.isNotBlank()) end else null,
        )
    }
}
