package com.pixelized.desktop.lwa.ui.screen.campaign.toolbar

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.pixelized.desktop.lwa.repository.campaign.CampaignRepository
import com.pixelized.desktop.lwa.repository.map.MapRepository
import com.pixelized.desktop.lwa.repository.network.NetworkRepository
import com.pixelized.desktop.lwa.repository.settings.SettingsRepository
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.update

class CampaignToolbarViewModel(
    campaignRepository: CampaignRepository,
    mapRepository: MapRepository,
    networkRepository: NetworkRepository,
    settingsRepository: SettingsRepository,
) : ViewModel() {

    private val _menusState = MutableStateFlow(
        CampaignMenuStateUio(
            isResourcesMenuOpen = false,
            isNetworkMenuOpen = false,
            isMapMenuOpen = false
        )
    )
    val menusState: StateFlow<CampaignMenuStateUio> = _menusState

    val status = networkRepository.status

    val title = campaignRepository.campaignFlow()
        .map { it.scene.name }
        .stateIn(
            scope = viewModelScope,
            started = SharingStarted.Lazily,
            initialValue = "",
        )

    val isAdmin = settingsRepository.settingsFlow()
        .map { it.isAdmin ?: false }
        .stateIn(
            scope = viewModelScope,
            started = SharingStarted.Lazily,
            initialValue = false,
        )

    val isMapEnable = mapRepository.currentMap()
        .map { it != null }
        .stateIn(
            scope = viewModelScope,
            started = SharingStarted.Lazily,
            initialValue = false,
        )

    val isGameMaster = settingsRepository.settingsFlow()
        .map { it.isGameMaster ?: false }
        .stateIn(
            scope = viewModelScope,
            started = SharingStarted.Lazily,
            initialValue = false,
        )

    fun onNetwork() {
        _menusState.update { it.copy(isNetworkMenuOpen = true) }
    }

    fun onResources() {
        _menusState.update { it.copy(isResourcesMenuOpen = true) }
    }

    fun onMap() {
        _menusState.update { it.copy(isMapMenuOpen = true) }
    }

    fun onDismissNetworkMenu() {
        _menusState.update { it.copy(isNetworkMenuOpen = false) }
    }

    fun onDismissResourcesMenu() {
        _menusState.update { it.copy(isResourcesMenuOpen = false) }
    }

    fun onDismissMapMenu() {
        _menusState.update { it.copy(isMapMenuOpen = false) }
    }
}