package top.yeij.cyrene.viewmodel

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.launch
import top.yeij.cyrene.data.local.PreferencesDataStore
import top.yeij.cyrene.data.remote.ApiService
import top.yeij.cyrene.domain.repository.AuthRepository

data class ProfileState(
    val userId: String = "",
    val username: String = "",
    val nickname: String = "",
    val isAdmin: Boolean = false,
    val createdAt: String = "",
    val isLoading: Boolean = false,
    val isLoggedIn: Boolean = false,
)

class ProfileViewModel(
    private val apiService: ApiService,
    private val authRepository: AuthRepository,
    private val prefs: PreferencesDataStore,
) : ViewModel() {

    private val _profile = MutableStateFlow(ProfileState())
    val profile: StateFlow<ProfileState> = _profile.asStateFlow()

    private var loadedFromCache = false

    init {
        viewModelScope.launch {
            _profile.value = _profile.value.copy(isLoggedIn = authRepository.isLoggedIn())
            if (_profile.value.isLoggedIn) {
                loadCachedProfile()
                fetchFreshProfile()
            }
        }
    }

    /**
     * Show cached profile immediately for instant UI.
     */
    private suspend fun loadCachedProfile() {
        val userId = prefs.profileUserId.firstOrNull() ?: return
        val nickname = prefs.profileNickname.firstOrNull() ?: ""
        val isAdmin = prefs.profileIsAdmin.firstOrNull()?.toBoolean() ?: false
        val createdAt = prefs.profileCreatedAt.firstOrNull() ?: ""
        val username = prefs.username.firstOrNull() ?: ""

        _profile.value = ProfileState(
            userId = userId,
            username = username,
            nickname = nickname,
            isAdmin = isAdmin,
            createdAt = createdAt,
            isLoggedIn = true,
        )
        loadedFromCache = true
    }

    /**
     * Fetch fresh profile from server. On success, update cache and UI.
     * On failure, keep showing cached data — no error, no UI disruption.
     */
    fun fetchFreshProfile() {
        viewModelScope.launch {
            if (!loadedFromCache) {
                _profile.value = _profile.value.copy(isLoading = true)
            }
            try {
                val response = apiService.getProfile()
                if (response.isSuccessful) {
                    val body = response.body()
                    if (body != null) {
                        val dateStr = body.createdAt?.take(10) ?: ""
                        val nickname = body.nickname ?: body.username

                        _profile.value = ProfileState(
                            userId = body.userId,
                            username = body.username,
                            nickname = nickname,
                            isAdmin = body.isAdmin == true,
                            createdAt = dateStr,
                            isLoading = false,
                            isLoggedIn = true,
                        )
                        loadedFromCache = true

                        // Update local cache
                        prefs.saveProfileCache(body.userId, nickname, body.isAdmin == true, dateStr)
                    }
                } else if (!loadedFromCache) {
                    _profile.value = _profile.value.copy(isLoading = false)
                }
                // On error with cache already shown: silently ignore
            } catch (e: Exception) {
                Log.w("ProfileVM", "Failed to fetch fresh profile: ${e.message}")
                if (!loadedFromCache) {
                    _profile.value = _profile.value.copy(isLoading = false)
                }
                // If cached data is showing, keep it silently
            }
        }
    }

    fun logout() {
        viewModelScope.launch {
            authRepository.logout()
            prefs.clearProfileCache()
            _profile.value = ProfileState()
            loadedFromCache = false
        }
    }
}
