package com.zaojiao.app.feat.home.index

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.zaojiao.app.data.repo.BabyRepository
import com.zaojiao.app.data.repo.LoginRepository
import com.zaojiao.app.data.repo.UserRepository
import com.zaojiao.app.feat.home.index.state.HomeIndexBabyUiState
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.async
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class HomeIndexViewModel @Inject constructor(
    private val loginRepository: LoginRepository,
    private val userRepository: UserRepository,
    private val babyRepository: BabyRepository,
) : ViewModel() {
    val babyUiState: StateFlow<HomeIndexBabyUiState> =
        loginRepository.state.combine(babyRepository.current) { login, baby ->
//            when (login) {
//                LoginState.IN -> {
//                    babyRepository.getBaby()
//
//                    if (baby != null) {
//                        HomeIndexBabyUiState(
//                            name = baby.name,
//                            avatar = baby.img,
//                            age = baby.age.substringBefore("-"),
//                        )
//                    } else {
//                        HomeIndexBabyUiState.Add
//                    }
//                }
//
//                LoginState.OUT -> {
//                    HomeIndexBabyUiState.None
//                }
//            }
            viewModelScope.launch {
                async {
                    userRepository.getUser()
                }
                async {
                    babyRepository.getBaby()
                }
            }

            if (baby != null) {
                HomeIndexBabyUiState(
                    name = baby.name,
                    avatar = baby.img,
                    age = baby.age.substringBefore("-"),
                )
            } else {
                HomeIndexBabyUiState.Add
            }
        }.stateIn(
            scope = viewModelScope,
            started = SharingStarted.WhileSubscribed(5_000),
            initialValue = HomeIndexBabyUiState.None,
        )
}