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.ForgotPasswordResult
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 ForgotPasswordViewModel(application: Application) : AndroidViewModel(application) {

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

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

    fun submit() {
        val email = _state.value.email.trim()
        val validationError = AuthInputValidator.validateForgotPassword(email)
        if (validationError != null) {
            _state.update {
                it.copy(
                    status = ForgotPasswordStatus.Error,
                    message = UiText(validationError)
                )
            }
            return
        }

        viewModelScope.launch {
            _state.update { it.copy(status = ForgotPasswordStatus.Loading, message = null) }
            when (val result = authService.forgotPassword(email)) {
                is ForgotPasswordResult.Success -> {
                    val successMessage = result.message?.trim().orEmpty()
                    _state.update {
                        it.copy(
                            status = ForgotPasswordStatus.Success,
                            message = if (successMessage.isBlank()) {
                                UiText(R.string.auth_forgot_success_default)
                            } else {
                                UiText(R.string.message_dynamic, args = listOf(successMessage))
                            }
                        )
                    }
                }

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

data class ForgotPasswordUiState(
    val email: String = "",
    val status: ForgotPasswordStatus = ForgotPasswordStatus.Idle,
    val message: UiText? = null
)

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