package de.trainingstagebuch.app.viewmodel

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import de.trainingstagebuch.app.repository.LoginResult
import de.trainingstagebuch.app.services.AppServices
import de.trainingstagebuch.app.utils.AuthInputValidator
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 LoginViewModel(application: Application) : AndroidViewModel(application) {

    private val authService = AppServices.authService

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

    fun onEmailChanged(value: String) {
        _state.update { it.copy(email = value) }
    }

    fun onPasswordChanged(value: String) {
        _state.update { it.copy(password = value) }
    }

    fun login() {
        val email = _state.value.email.trim()
        val password = _state.value.password
        val validationError = AuthInputValidator.validateLogin(email, password)
        if (validationError != null) {
            _state.update {
                it.copy(
                    status = LoginStatus.Error,
                    errorMessage = UiText(validationError)
                )
            }
            return
        }

        viewModelScope.launch {
            _state.update { it.copy(status = LoginStatus.Loading, errorMessage = null) }

            when (val result = authService.login(email, password)) {
                is LoginResult.Success -> {
                    _state.update { it.copy(status = LoginStatus.Success, errorMessage = null) }
                }

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

    fun resetToIdle() {
        _state.update { it.copy(status = LoginStatus.Idle, errorMessage = null) }
    }
}

data class LoginUiState(
    val email: String = "",
    val password: String = "",
    val status: LoginStatus = LoginStatus.Idle,
    val errorMessage: UiText? = null
)

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