package com.fastest.pass.login.presentation.viewmodels

import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.fastest.pass.app.UIState
import com.fastest.pass.app.WebResponse
import com.fastest.pass.login.data.model.LoginRequest
import com.fastest.pass.login.data.model.LoginResponse
import com.fastest.pass.login.domain.usecase.LoginUseCase
import com.fastest.pass.login.utils.LoginRoute
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject
import com.fastest.pass.app.Result

@HiltViewModel
class LoginViewModel @Inject constructor(
    private val loginUseCase: LoginUseCase
) : ViewModel() {

    private var _loginResponse =
        mutableStateOf(UIState<WebResponse<LoginResponse>>())
    val loginResponse: State<UIState<WebResponse<LoginResponse>>> =
        _loginResponse

    private val _router = MutableStateFlow<LoginRoute>(LoginRoute.OpenNoneScreen)
    val router: MutableStateFlow<LoginRoute> = _router

    fun login(email: String, password: String) {
        viewModelScope.launch {
            val request = LoginRequest(email, password)
            loginUseCase(request) { result ->
                when (result) {
                    is Result.Loading -> {
                        _loginResponse.value = UIState(true)
                    }

                    is Result.Success -> {
                        _loginResponse.value = UIState(false,result.data)
                    }

                    is Result.Failure -> {
                        _loginResponse.value = UIState(false)
                    }
                }
            }
        }
    }

    fun navigateTo(loginRoute: LoginRoute) {
        _router.value = loginRoute
    }
}