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.Participant
import de.tsschulz.tt_tagebuch.shared.repository.DiaryRepository
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

class ParticipantScreenModel(private val diaryRepository: DiaryRepository) : ScreenModel {
    private val _state = MutableStateFlow<ParticipantState>(ParticipantState.Loading)
    val state = _state.asStateFlow()

    fun loadParticipants(dateId: Int) {
        screenModelScope.launch {
            _state.value = ParticipantState.Loading
            try {
                val participants = diaryRepository.getParticipants(dateId)
                _state.value = ParticipantState.Success(participants)
            } catch (e: Exception) {
                _state.value = ParticipantState.Error(e.message ?: "Failed to load participants")
            }
        }
    }

    fun updateStatus(dateId: Int, memberId: Int, status: String) {
        screenModelScope.launch {
            try {
                val success = diaryRepository.updateParticipantStatus(dateId, memberId, status)
                if (success) {
                    // Refresh list after update
                    loadParticipants(dateId)
                }
            } catch (e: Exception) {
                // Handle error
            }
        }
    }
}

sealed class ParticipantState {
    object Loading : ParticipantState()
    data class Success(val participants: List<Participant>) : ParticipantState()
    data class Error(val message: String) : ParticipantState()
}
