package com.syaroful.agrilinkvocpro.presentation.screen.login

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.syaroful.agrilinkvocpro.core.utils.ResultState
import com.syaroful.agrilinkvocpro.core.utils.extention.mapToUserFriendlyError
import com.syaroful.agrilinkvocpro.data.UserPreferences
import com.syaroful.agrilinkvocpro.data.model.LoginResponse
import com.syaroful.agrilinkvocpro.data.repository.AuthRepository
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch

class LoginViewModel(
    private val repository: AuthRepository,
    private val userPreferences: UserPreferences
) : ViewModel() {
    private val _loginState = MutableStateFlow<ResultState<LoginResponse>>(ResultState.Idle)
    val loginState: StateFlow<ResultState<LoginResponse>> = _loginState

    fun login(username: String, password: String) {
        _loginState.value = ResultState.Loading
        viewModelScope.launch {
            try {
                val response = repository.login(username, password)
                if (response.isSuccessful) {
                    val token = response.body()?.data?.token
                    val jwtToken = response.body()?.data?.jwtToken
                    if (token != null && jwtToken != null) {
                        userPreferences.saveToken(token)
                        userPreferences.saveJwtToken(jwtToken)
                        _loginState.value = ResultState.Success(response.body())

                    } else {
                        val errorMessage = response.body()?.message ?: "Login Failed: Token is null"
                        _loginState.value = ResultState.Error(errorMessage)
                    }
                } else {
                    val errorBody = response.errorBody()?.string()
                    val errorMessage = if (errorBody != null) {
                        // Assuming errorBody is a JSON string with a "message" key
                        org.json.JSONObject(errorBody)
                            .optString("message", "Login Failed: ${response.code()}")
                    } else {
                        "Login Failed: ${response.code()}"
                    }
                    _loginState.value = ResultState.Error(errorMessage)
                }
            } catch (e: Exception) {
                val errorMessage = mapToUserFriendlyError(e)
                _loginState.value = ResultState.Error(errorMessage)
            }
        }
    }

    fun resetLoginState() {
        _loginState.value = ResultState.Idle
    }
}
