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

import androidx.lifecycle.viewModelScope
import com.zaojiao.app.core.auth.data.AuthRepository
import com.zaojiao.app.core.auth.utils.AuthState
import com.zaojiao.app.feat.design.viewmodel.BaseViewModel
import com.zaojiao.app.data.repo.BabyRepository
import com.zaojiao.app.feat.home.index.state.HomeIndexBabyUiState
import com.zaojiao.app.feat.home.index.state.HomeIndexPageUiState
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.stateIn
import javax.inject.Inject

@HiltViewModel
class HomeIndexViewModel @Inject constructor(
    private val authRepository: AuthRepository,
    private val babyRepository: BabyRepository,
) : BaseViewModel<HomeIndexPageUiState>() {
    val babyUiState: StateFlow<HomeIndexBabyUiState> =
        combine(authRepository.state, babyRepository.current) { auth, baby ->
            when (auth) {
                AuthState.IN -> {
                    if (baby != null) {
                        HomeIndexBabyUiState(
                            name = baby.name,
                            avatar = baby.img,
                            age = baby.age.substringBefore("-"),
                        )
                    } else {
                        HomeIndexBabyUiState.Add
                    }
                }

                AuthState.OUT -> {
                    HomeIndexBabyUiState.Login
                }
            }
        }.stateIn(
            scope = viewModelScope,
            started = SharingStarted.WhileSubscribed(5_000),
            initialValue = HomeIndexBabyUiState.None,
        )

    override suspend fun initData(): HomeIndexPageUiState {
        val list = listOf(
            "https://t7.baidu.com/it/u=1595072465,3644073269&fm=193&f=GIF",
            "https://t7.baidu.com/it/u=4198287529,2774471735&fm=193&f=GIF",
            "https://t7.baidu.com/it/u=1956604245,3662848045&fm=193&f=GIF",
            "https://t7.baidu.com/it/u=2529476510,3041785782&fm=193&f=GIF",
        )

        return HomeIndexPageUiState(
            bannerList = list
        )
    }
}