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.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
    }

    private fun mapToUserFriendlyError(e: Exception): String {
        return when (e) {
            is java.net.UnknownHostException -> "Tidak dapat terhubung ke server. Periksa koneksi internet Anda."
            is java.net.SocketTimeoutException -> "Waktu koneksi habis. Mohon coba lagi."
            is java.io.IOException -> "Terjadi kesalahan jaringan. Silakan cek koneksi Anda."
            is retrofit2.HttpException -> {
                // Kamu bisa cek kode HTTP di sini juga kalau mau
                when (e.code()) {
                    401 -> "Akses ditolak. Silakan periksa kredensial login Anda."
                    403 -> "Anda tidak memiliki izin untuk mengakses ini."
                    404 -> "Data tidak ditemukan."
                    500 -> "Terjadi kesalahan pada server. Silakan coba lagi nanti."
                    else -> "Terjadi kesalahan. Kode: ${e.code()}"
                }
            }

            else -> "Terjadi kesalahan. Silakan coba lagi."
        }
    }
}
