package de.trainingstagebuch.app.viewmodel

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import de.trainingstagebuch.app.R
import de.trainingstagebuch.app.services.AppServices
import de.trainingstagebuch.app.services.LanguageOption
import de.trainingstagebuch.app.utils.UiText
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update

data class PersonalSettingsUiState(
    val loading: Boolean = true,
    val selectedLanguage: String = "de",
    val languages: List<LanguageOption> = emptyList(),
    val errorMessage: UiText? = null,
    val successMessage: UiText? = null
)

class PersonalSettingsViewModel(application: Application) : AndroidViewModel(application) {

    private val personalSettingsService = AppServices.personalSettingsService

    private val _state = MutableStateFlow(PersonalSettingsUiState())
    val state: StateFlow<PersonalSettingsUiState> = _state.asStateFlow()

    init {
        load()
    }

    fun load() {
        _state.update {
            it.copy(
                loading = false,
                selectedLanguage = personalSettingsService.currentLanguage(),
                languages = personalSettingsService.availableLanguages,
                errorMessage = null
            )
        }
    }

    fun onLanguageSelected(code: String) {
        runCatching {
            personalSettingsService.setLanguage(code)
        }.onSuccess {
            _state.update {
                it.copy(
                    selectedLanguage = code,
                    successMessage = UiText(R.string.personal_settings_language_changed),
                    errorMessage = null
                )
            }
        }.onFailure {
            _state.update {
                it.copy(
                    errorMessage = UiText(R.string.personal_settings_language_change_failed)
                )
            }
        }
    }

    fun clearMessages() {
        _state.update { it.copy(errorMessage = null, successMessage = null) }
    }
}
