package de.trainingstagebuch.app.viewmodel

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import de.trainingstagebuch.app.R
import de.trainingstagebuch.app.repository.ActivateResult
import de.trainingstagebuch.app.services.AppServices
import de.trainingstagebuch.app.utils.ErrorMessageFormatter
import de.trainingstagebuch.app.utils.UiText
import de.trainingstagebuch.app.utils.ViewModelStateUtils
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch

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

    private val authService = AppServices.authService
    private val _state = MutableStateFlow(ActivateUiState())
    val state: StateFlow<ActivateUiState> = _state.asStateFlow()

    fun activate(activationCode: String) {
        val normalizedCode = activationCode.trim()
        if (normalizedCode.isBlank()) {
            _state.update {
                it.copy(
                    status = ActivateStatus.Error,
                    message = UiText(R.string.error_required_activation_code)
                )
            }
            return
        }

        viewModelScope.launch {
            _state.update { it.copy(status = ActivateStatus.Loading, message = null) }
            when (val result = authService.activate(normalizedCode)) {
                is ActivateResult.Success -> {
                    val successMessage = result.message?.trim().orEmpty()
                    _state.update {
                        it.copy(
                            status = ActivateStatus.Success,
                            message = if (successMessage.isBlank()) {
                                UiText(R.string.auth_activate_success_default)
                            } else {
                                UiText(R.string.message_dynamic, args = listOf(successMessage))
                            }
                        )
                    }
                }

                is ActivateResult.Error -> {
                    val uiText = ErrorMessageFormatter.dynamicWithOptionalCode(result.message, result.code)
                    _state.update {
                        it.copy(
                            status = ActivateStatus.Error,
                            message = ViewModelStateUtils.normalizeUiText(uiText)
                        )
                    }
                }
            }
        }
    }
}

data class ActivateUiState(
    val status: ActivateStatus = ActivateStatus.Idle,
    val message: UiText? = null
)

enum class ActivateStatus {
    Idle,
    Loading,
    Success,
    Error
}
