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

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

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

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

    fun submit(token: String) {
        val normalizedToken = token.trim()
        val password = _state.value.password
        val confirmPassword = _state.value.confirmPassword

        val validationError = AuthInputValidator.validateResetPassword(
            token = normalizedToken,
            password = password,
            confirmPassword = confirmPassword
        )
        if (validationError != null) {
            _state.update {
                it.copy(
                    status = ResetPasswordStatus.Error,
                    message = UiText(validationError)
                )
            }
            return
        }

        viewModelScope.launch {
            _state.update { it.copy(status = ResetPasswordStatus.Loading, message = null) }
            when (val result = authService.resetPassword(normalizedToken, password)) {
                is ResetPasswordResult.Success -> {
                    val successMessage = result.message?.trim().orEmpty()
                    _state.update {
                        it.copy(
                            status = ResetPasswordStatus.Success,
                            message = if (successMessage.isBlank()) {
                                UiText(R.string.auth_reset_success_default)
                            } else {
                                UiText(R.string.message_dynamic, args = listOf(successMessage))
                            }
                        )
                    }
                }

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

data class ResetPasswordUiState(
    val password: String = "",
    val confirmPassword: String = "",
    val status: ResetPasswordStatus = ResetPasswordStatus.Idle,
    val message: UiText? = null
)

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