package de.tsschulz.tt_tagebuch.app.viewmodel

import cafe.adriel.voyager.core.model.ScreenModel
import cafe.adriel.voyager.core.model.screenModelScope
import de.tsschulz.tt_tagebuch.shared.models.Member
import de.tsschulz.tt_tagebuch.shared.repository.MemberRepository
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

class MemberEditScreenModel(private val memberRepository: MemberRepository) : ScreenModel {
    private val _state = MutableStateFlow<MemberEditState>(MemberEditState.Idle)
    val state = _state.asStateFlow()

    fun saveMember(clubId: Int, member: Member) {
        screenModelScope.launch {
            _state.value = MemberEditState.Saving
            try {
                val success = memberRepository.saveMember(clubId, member)
                if (success) {
                    _state.value = MemberEditState.Success
                } else {
                    _state.value = MemberEditState.Error("Fehler beim Speichern")
                }
            } catch (e: Exception) {
                _state.value = MemberEditState.Error(e.message ?: "Netzwerkfehler")
            }
        }
    }
}

sealed class MemberEditState {
    object Idle : MemberEditState()
    object Saving : MemberEditState()
    object Success : MemberEditState()
    data class Error(val message: String) : MemberEditState()
}
