package com.example.elva.ui.auth

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.elva.data.repository.AuthRepository
import com.example.elva.data.repository.UserRepository
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

@HiltViewModel
class LoginViewModel @Inject constructor(
    private val authRepository: AuthRepository,
    private val userRepository: UserRepository
) : ViewModel() {

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

    fun login(emailOrUsername: String, password: String) {
        android.util.Log.d("LoginViewModel", "login() called with: emailOrUsername=$emailOrUsername")

        // Валидация
        when {
            emailOrUsername.isBlank() -> {
                _uiState.value = LoginUiState.Error("Введите email или имя пользователя")
                return
            }
            password.isBlank() -> {
                _uiState.value = LoginUiState.Error("Введите пароль")
                return
            }
        }

        _uiState.value = LoginUiState.Loading
        android.util.Log.d("LoginViewModel", "Starting login process")

        viewModelScope.launch {
            // Определяем, это email или username
            val isEmail = emailOrUsername.contains("@")
            android.util.Log.d("LoginViewModel", "isEmail: $isEmail")

            val result = if (isEmail) {
                authRepository.login(
                    email = emailOrUsername,
                    password = password
                )
            } else {
                authRepository.login(
                    username = emailOrUsername,
                    password = password
                )
            }

            android.util.Log.d("LoginViewModel", "Login result: success=${result.isSuccess}")

            if (result.isSuccess) {
                android.util.Log.d("LoginViewModel", "Login successful!")
                // Сразу переходим на dashboard, профиль загрузится там
                _uiState.value = LoginUiState.Success
            } else {
                val error = when {
                    result.exceptionOrNull()?.message?.contains("401") == true ||
                    result.exceptionOrNull()?.message?.contains("Unauthorized") == true ->
                        "Неверный email/пароль"
                    result.exceptionOrNull()?.message?.contains("Unable to resolve host") == true ->
                        "Не удается подключиться к серверу. Проверьте настройки сети."
                    else -> result.exceptionOrNull()?.message ?: "Ошибка входа"
                }
                android.util.Log.e("LoginViewModel", "Login failed: $error", result.exceptionOrNull())
                _uiState.value = LoginUiState.Error(error)
            }
        }
    }

    fun checkIfLoggedIn(): Boolean {
        val isLoggedIn = authRepository.isLoggedIn()
        android.util.Log.d("LoginViewModel", "checkIfLoggedIn: $isLoggedIn")
        return isLoggedIn
    }

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

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

