package com.radiola.ui.auth

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.radiola.domain.usecase.auth.RequestMagicLinkUseCase
import com.radiola.domain.usecase.auth.VerifyMagicLinkUseCase
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class AuthViewModel @Inject constructor(
    private val requestMagicLinkUseCase: RequestMagicLinkUseCase,
    private val verifyMagicLinkUseCase: VerifyMagicLinkUseCase
) : ViewModel() {

    sealed class AuthState {
        data object Idle : AuthState()
        data object Loading : AuthState()
        data object CodeSent : AuthState()
        data object Success : AuthState()
        data class Error(val message: String) : AuthState()
    }

    private val _state = MutableStateFlow<AuthState>(AuthState.Idle)
    val state: StateFlow<AuthState> = _state

    private val _email = MutableStateFlow("")
    val email: StateFlow<String> = _email

    fun onEmailChange(value: String) {
        _email.value = value
    }

    fun requestCode() {
        val email = _email.value.trim()
        if (email.isBlank() || !email.contains("@")) {
            _state.value = AuthState.Error("Введите корректный email")
            return
        }
        viewModelScope.launch {
            _state.value = AuthState.Loading
            requestMagicLinkUseCase(email)
                .onSuccess { _state.value = AuthState.CodeSent }
                .onFailure { _state.value = AuthState.Error(it.message ?: "Ошибка отправки") }
        }
    }

    fun verifyCode(code: String) {
        val email = _email.value.trim()
        if (code.length != 6) {
            _state.value = AuthState.Error("Код должен содержать 6 символов")
            return
        }
        viewModelScope.launch {
            _state.value = AuthState.Loading
            verifyMagicLinkUseCase(email, code)
                .onSuccess { _state.value = AuthState.Success }
                .onFailure { _state.value = AuthState.Error(it.message ?: "Неверный код") }
        }
    }

    fun dismissError() {
        if (_state.value is AuthState.Error) {
            _state.value = AuthState.Idle
        }
    }
}
