package de.trainingstagebuch.app.viewmodel

import android.app.Application
import de.trainingstagebuch.app.R
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import de.trainingstagebuch.app.repository.RegisterResult
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 RegisterViewModel(application: Application) : AndroidViewModel(application) {

    private val authService = AppServices.authService

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

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

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

    fun onConfirmPasswordChanged(value: String) {
        _state.update { it.copy(confirmPassword = value) }
    }

    fun register() {
        val email = _state.value.email.trim()
        val password = _state.value.password
        val confirmPassword = _state.value.confirmPassword

        val validationError = AuthInputValidator.validateRegister(email, password, confirmPassword)
        if (validationError != null) {
            _state.update {
                it.copy(
                    status = RegisterStatus.Error,
                    errorMessage = UiText(validationError)
                )
            }
            return
        }

        viewModelScope.launch {
            _state.update { it.copy(status = RegisterStatus.Loading, errorMessage = null, successMessage = null) }
            when (val result = authService.register(email, password)) {
                is RegisterResult.Success -> {
                    val successMessage = result.message?.trim().orEmpty()
                    _state.update {
                        it.copy(
                            status = RegisterStatus.Success,
                            successMessage = if (successMessage.isBlank()) {
                                UiText(R.string.auth_register_success_default)
                            } else {
                                UiText(
                                    resId = R.string.message_dynamic,
                                    args = listOf(successMessage)
                                )
                            },
                            errorMessage = null
                        )
                    }
                }

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

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

data class RegisterUiState(
    val email: String = "",
    val password: String = "",
    val confirmPassword: String = "",
    val status: RegisterStatus = RegisterStatus.Idle,
    val errorMessage: UiText? = null,
    val successMessage: UiText? = null
)

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