package com.syaroful.agrilinkvocpro.presentation.screen.profile

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.auth0.jwt.JWT
import com.syaroful.agrilinkvocpro.data.UserPreferences
import com.syaroful.agrilinkvocpro.data.model.UserProfile
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

private const val TAG = "ProfileViewModel"

class ProfileViewModel(
    private val userPreferences: UserPreferences
) : ViewModel() {
    private val _profileState = MutableStateFlow<UserProfile?>(null)
    val profileState: StateFlow<UserProfile?> = _profileState

    fun loadUserProfile() {
        viewModelScope.launch {
            val token = userPreferences.jwtTokenFlow.first()

            if (!token.isNullOrEmpty()) {
                Log.d(TAG, "loadUserProfile: $token")
                try {
                    val jwt = JWT.decode(token)
                    val userMap = jwt.getClaim("user").asMap()
                    val username = userMap["username"] as? String
                    val email = userMap["email"] as? String
                    val fullname = userMap["fullname"] as? String

                    Log.d(TAG, "loadUserProfile: $username")

                    val profile =
                        UserProfile(name = fullname, username = username, email = email)
                    _profileState.value = profile
                } catch (e: Exception) {
                    Log.e(TAG, "loadUserProfile: ${e.message}")
                    _profileState.value = null
                }
            } else {
                Log.d(TAG, "loadUserProfile: null")
                _profileState.value = null
            }

        }
    }

    fun logout(onLogoutCompleted: () -> Unit) {
        viewModelScope.launch {
            withContext(Dispatchers.IO) {
                userPreferences.clearToken()
                userPreferences.clearJwtToken()
            }
            onLogoutCompleted()
        }
    }
}