package com.pixelized.biblib.ui.screen.home.profile

import android.util.Log
import androidx.compose.runtime.State
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.pixelized.biblib.model.user.User
import com.pixelized.biblib.repository.credential.ICredentialRepository
import com.pixelized.biblib.repository.googleSignIn.IGoogleSingInRepository
import com.pixelized.biblib.repository.user.IUserRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class ProfileViewModel @Inject constructor(
    private val credentialRepository: ICredentialRepository,
    private val userRepository: IUserRepository,
    private val googleSignIn: IGoogleSingInRepository,
) : ViewModel() {

    private val _user = mutableStateOf<UserUio?>(null)
    val user: State<UserUio?> = _user

    private val _error = MutableSharedFlow<Exception>()
    val error: Flow<Exception> = _error

    val mails: List<String> by derivedStateOf { user.value?.amazonEmails ?: emptyList() }

    init {
        viewModelScope.launch {
            updateUser()
        }
    }

    suspend fun updateUser() {
        try {
            val data = userRepository.user(
                forceUpdate = userRepository.lastUpdateDuration() > DAY_IN_MILLIS
            )
            _user.value = data.toUio()
        } catch (exception: Exception) {
            Log.e("AccountViewModel", exception.message, exception)
            _error.emit(exception)
        }
    }

    fun logout() {
        credentialRepository.bearer = null
        googleSignIn.client.signOut()
    }

    private fun User.toUio() = UserUio(
        username = username,
        firstname = firstname,
        lastname = lastname,
        amazonEmails = amazonEmails.toList(),
    )

    companion object {
        private const val DAY_IN_MILLIS = 86400000
    }
}