package id.iiyh.inatrading.feature.profile.presentation

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import id.iiyh.inatrading.core.data.local.SessionManager
import id.iiyh.inatrading.feature.auth.domain.repository.AuthRepository
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import javax.inject.Inject

data class UserProfile(
    val name: String,
    val email: String,
    val avatarUrl: String,
    val isPremium: Boolean,
)

data class OrderCounts(
    val toShip: Int = 0,
)

data class ProfileUiState(
    val isLoggedIn: Boolean = false,
    val user: UserProfile? = null,
    val orderCounts: OrderCounts = OrderCounts(),
)

@HiltViewModel
class ProfileViewModel @Inject constructor(
    private val sessionManager: SessionManager,
    private val authRepository: AuthRepository,
) : ViewModel() {

    val uiState: StateFlow<ProfileUiState> = combine(
        sessionManager.token,
        sessionManager.email,
        sessionManager.name,
        sessionManager.avatarUrl,
        sessionManager.userType,
    ) { token, email, name, avatarUrl, userType ->
        if (token.isNullOrEmpty()) {
            ProfileUiState(isLoggedIn = false)
        } else {
            ProfileUiState(
                isLoggedIn = true,
                user = UserProfile(
                    name      = name.orEmpty().ifEmpty { email.orEmpty() },
                    email     = email.orEmpty(),
                    avatarUrl = avatarUrl.orEmpty(),
                    isPremium = userType.equals("SELLER", ignoreCase = true),
                ),
                orderCounts = OrderCounts(),
            )
        }
    }.stateIn(
        scope         = viewModelScope,
        started       = SharingStarted.WhileSubscribed(5_000),
        initialValue  = ProfileUiState(),
    )

    init {
        sessionManager.token
            .distinctUntilChanged()
            .onEach { token ->
                if (!token.isNullOrBlank()) {
                    refreshProfile()
                }
            }
            .launchIn(viewModelScope)
    }

    private fun refreshProfile() {
        viewModelScope.launch {
            authRepository.getBuyerProfile()
        }
    }

    fun logout() {
        viewModelScope.launch {
            authRepository.logout()
        }
    }
}
