package com.fastest.pass.signup.presentation.viewmodels

import android.util.Log
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.fastest.pass.app.Result
import com.fastest.pass.app.UIState
import com.fastest.pass.app.WebResponse
import com.fastest.pass.login.utils.LoginRoute
import com.fastest.pass.signup.data.model.SignupRequest
import com.fastest.pass.signup.data.model.SignupResponse
import com.fastest.pass.signup.domain.usecase.SignupUseCase
import com.fastest.pass.signup.utils.SignUpRoute
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class SignUpViewModel @Inject constructor(
    private val signupUseCase: SignupUseCase
) : ViewModel() {

    private val _signupResponse = mutableStateOf(UIState<WebResponse<SignupResponse>>())
    val signupResponse: State<UIState<WebResponse<SignupResponse>>> = _signupResponse

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

    fun signup(email: String, password: String) {
        Log.d("test_signup_api", "signup:viewmodel => $email, $password")
        viewModelScope.launch {
            val request = SignupRequest(email, password)
            signupUseCase(request) { result ->
                Log.d("test_signup_api", "result = $result")
                when (result) {
                    is Result.Loading -> {
                        _signupResponse.value = UIState(true)
                    }
                    is Result.Success -> {
                        _signupResponse.value = UIState(false, result.data)
                    }
                    is Result.Failure -> {
                        _signupResponse.value = UIState(false)
                    }
                }
            }
        }
    }

    fun navigateTo(signUpRoute: SignUpRoute) {
        _router.value = signUpRoute
    }
}