package com.seven.ikar.kotlin.feature.settings

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.seven.ikar.kotlin.app.AppContainer
import com.seven.ikar.kotlin.core.push.NotificationPreferenceCatalog
import com.seven.ikar.kotlin.core.push.NotificationSettingsSnapshot
import com.seven.ikar.kotlin.core.push.NotificationSoundChoice
import com.seven.ikar.kotlin.core.push.NotificationSoundOption
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

data class NotificationSettingsUiState(
    val snapshot: NotificationSettingsSnapshot,
    val isSaving: Boolean = false,
    val errorMessage: String? = null,
    val infoMessage: String? = null
)

class NotificationSettingsViewModel(private val container: AppContainer) : ViewModel() {
    private val _uiState = MutableStateFlow(
        NotificationSettingsUiState(snapshot = container.pushSettings.loadSnapshot())
    )
    val uiState: StateFlow<NotificationSettingsUiState> = _uiState.asStateFlow()

    val messageSoundOptions: List<NotificationSoundChoice> = NotificationPreferenceCatalog.messageSoundChoices
    private var saveRevision = 0

    fun updateSnapshot(transform: (NotificationSettingsSnapshot) -> NotificationSettingsSnapshot) {
        val snapshot = transform(_uiState.value.snapshot)
        _uiState.value = _uiState.value.copy(snapshot = snapshot, errorMessage = null, infoMessage = null)
        persist(snapshot)
    }

    fun setMessageSound(value: NotificationSoundOption) = updateSnapshot { it.copy(messageSound = value) }

    private fun persist(snapshot: NotificationSettingsSnapshot) {
        val revision = ++saveRevision
        viewModelScope.launch {
            _uiState.value = _uiState.value.copy(isSaving = true, errorMessage = null, infoMessage = null)
            runCatching {
                container.pushSettings.saveSnapshot(snapshot)
                container.pushRegistrationManager.registerCurrentDeviceAsync()
            }.onSuccess {
                if (revision == saveRevision) {
                    _uiState.value = _uiState.value.copy(isSaving = false, infoMessage = null)
                }
            }.onFailure { error ->
                if (revision == saveRevision) {
                    _uiState.value = _uiState.value.copy(isSaving = false, errorMessage = error.message)
                }
            }
        }
    }

    fun reset() {
        container.pushSettings.resetNotificationPreferences()
        val snapshot = container.pushSettings.createDefaultSnapshot()
        _uiState.value = NotificationSettingsUiState(snapshot = snapshot)
        persist(snapshot)
    }
}
