package app.closer.ui.auth

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import app.closer.domain.repository.AuthRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import javax.inject.Inject

data class ForgotPasswordUiState(
    val email: String = "",
    val isLoading: Boolean = false,
    val error: String? = null,
    val sent: Boolean = false
)

@HiltViewModel
class ForgotPasswordViewModel @Inject constructor(
    private val authRepository: AuthRepository
) : ViewModel() {

    private val _uiState = MutableStateFlow(ForgotPasswordUiState())
    val uiState: StateFlow<ForgotPasswordUiState> = _uiState.asStateFlow()

    fun updateEmail(v: String) = _uiState.update { it.copy(email = v, error = null) }
    fun dismissError() = _uiState.update { it.copy(error = null) }

    fun sendReset() {
        val email = _uiState.value.email.trim()
        if (email.isBlank()) {
            _uiState.update { it.copy(error = "Please enter your email address.") }
            return
        }
        _uiState.update { it.copy(isLoading = true, error = null) }
        viewModelScope.launch {
            authRepository.sendPasswordResetEmail(email)
                .onSuccess { _uiState.update { it.copy(isLoading = false, sent = true) } }
                .onFailure { e ->
                    val msg = friendlyError(e)
                    _uiState.update { it.copy(isLoading = false, error = msg) }
                }
        }
    }

    private fun friendlyError(e: Throwable): String = when {
        e.message?.contains("no user record") == true -> "No account found with that email."
        e.message?.contains("badly formatted") == true -> "Please enter a valid email address."
        else -> e.message ?: "Something went wrong. Please try again."
    }
}
