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

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

    fun loadDiaryDates(clubId: Int) {
        screenModelScope.launch {
            try {
                val dates = diaryRepository.getDiaryDates(clubId)
                _state.value = DiaryState.Success(dates)
                diaryRepository.connectSocket(clubId)
                
                // Observe socket events
                diaryRepository.observeEvents().collect { (event, data) ->
                    // Handle real-time updates here
                    // For now, just reload to keep it simple
                    loadDiaryDates(clubId)
                }
            } catch (e: Exception) {
                _state.value = DiaryState.Error(e.message ?: "Failed to load diary")
            }
        }
    }

    override fun onDispose() {
        diaryRepository.disconnectSocket()
        super.onDispose()
    }
}

sealed class DiaryState {
    object Loading : DiaryState()
    data class Success(val dates: List<DiaryDate>) : DiaryState()
    data class Error(val message: String) : DiaryState()
}
