package com.example.elva.ui.auth

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.elva.data.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.launch
import javax.inject.Inject

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

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

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

    fun register(
        username: String,
        email: String,
        password: String,
        confirmPassword: String,
        fullName: String? = null,
        phone: String? = null
    ) {
        // Валидация
        when {
            username.isBlank() -> {
                _uiState.value = RegisterUiState.Error("Введите имя пользователя")
                return
            }
            email.isBlank() -> {
                _uiState.value = RegisterUiState.Error("Введите email")
                return
            }
            !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches() -> {
                _uiState.value = RegisterUiState.Error("Неверный формат email")
                return
            }
            password.length < 8 -> {
                _uiState.value = RegisterUiState.Error("Пароль должен содержать минимум 8 символов")
                return
            }
            password != confirmPassword -> {
                _uiState.value = RegisterUiState.Error("Пароли не совпадают")
                return
            }
        }

        viewModelScope.launch {
            _uiState.value = RegisterUiState.Loading
            try {
                val result = authRepository.register(
                    username = username,
                    email = email,
                    password = password,
                    fullName = fullName,
                    phone = phone
                )

                result.fold(
                    onSuccess = { response ->
                        // Данные уже сохранены в AuthRepository
                        _uiState.value = RegisterUiState.Success
                    },
                    onFailure = { error ->
                        _uiState.value = RegisterUiState.Error(
                            error.message ?: "Ошибка регистрации"
                        )
                    }
                )
            } catch (e: Exception) {
                _uiState.value = RegisterUiState.Error(
                    e.message ?: "Ошибка регистрации"
                )
            }
        }
    }

    fun resetState() {
        _uiState.value = RegisterUiState.Idle
    }
}

