package com.radiola.ui.favorites

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.radiola.domain.model.Station
import com.radiola.domain.model.Track
import com.radiola.domain.repository.FavoritesRepository
import com.radiola.domain.repository.NowPlayingRepository
import com.radiola.domain.usecase.ToggleFavoriteUseCase
import com.radiola.domain.usecase.auth.PushFavoriteUseCase
import com.radiola.domain.usecase.auth.SyncFavoritesUseCase
import com.radiola.service.PlayerController
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class FavoritesViewModel @Inject constructor(
    private val favoritesRepository: FavoritesRepository,
    private val toggleFavoriteUseCase: ToggleFavoriteUseCase,
    private val pushFavoriteUseCase: PushFavoriteUseCase,
    private val syncFavoritesUseCase: SyncFavoritesUseCase,
    private val nowPlayingRepository: NowPlayingRepository,
    private val playerController: PlayerController
) : ViewModel() {

    // Активная (играющая) станция — для подсветки карточки, как на экране всех станций.
    val playingStationId: StateFlow<Int?> = playerController.currentStationId
    val isPlaying: StateFlow<Boolean> = playerController.isPlaying

    val favorites: StateFlow<List<Station>> = favoritesRepository.getFavorites()
        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList())

    val favoriteIds: StateFlow<Set<Int>> = favoritesRepository.getFavorites()
        .map { list -> list.map { it.id }.toSet() }
        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptySet())

    // Текущие треки по id станции (каталожный == station.id) — без коллизий по имени.
    val nowPlaying: StateFlow<Map<Int, Track>> = nowPlayingRepository.getAllNowPlaying()
        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyMap())

    init {
        viewModelScope.launch {
            syncFavoritesUseCase()
        }
        // Периодическое обновление now-playing каждые 20 секунд.
        viewModelScope.launch {
            while (true) {
                nowPlayingRepository.refreshNowPlaying()
                delay(20_000)
            }
        }
    }

    fun toggleFavorite(station: Station) {
        viewModelScope.launch {
            val currentlyFavorite = favoriteIds.value.contains(station.id)
            toggleFavoriteUseCase(station)
            pushFavoriteUseCase(station.id, !currentlyFavorite)
        }
    }
}
