package com.pixelized.desktop.lwa.ui.composable.character.inventory

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.pixelized.desktop.lwa.repository.item.ItemRepository
import com.pixelized.desktop.lwa.repository.settings.SettingsRepository
import com.pixelized.desktop.lwa.ui.composable.textfield.createLwaTextField
import com.pixelized.desktop.lwa.ui.composable.textfield.createLwaTextFieldFlow
import com.pixelized.desktop.lwa.utils.extention.unAccent
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.runBlocking
import lwacharactersheet.composeapp.generated.resources.Res
import lwacharactersheet.composeapp.generated.resources.character__inventory__filter_item_inventory__label
import org.jetbrains.compose.resources.getString

class InventoryDialogViewModel(
    itemRepository: ItemRepository,
    settingRepository: SettingsRepository,
    factory: InventoryDialogFactory,
) : ViewModel() {

    private val selectedCharacterSheetId = MutableStateFlow<String?>(null)
    private val filterFlow = createLwaTextFieldFlow(
        label = runBlocking { getString(Res.string.character__inventory__filter_item_inventory__label) },
    )
    private val filterField = filterFlow.createLwaTextField()

    val inventoryDialog = combine(
        itemRepository.itemFlow().map { it.values },
        settingRepository.settingsFlow(),
        filterFlow.valueFlow.map { it.unAccent() },
        selectedCharacterSheetId,
    ) { items, settings, filter, characterSheetId ->
        factory.convertToDialogUio(
            items = factory.filterItems(
                items = items,
                filter = filter,
                setting = settings,
            ),
            filter = filterField,
            characterSheetId = characterSheetId,
        )
    }.stateIn(
        scope = viewModelScope,
        started = SharingStarted.Lazily,
        initialValue = null
    )

    fun showInventoryDialog(characterSheetId: String?) {
        filterFlow.valueFlow.update { "" }
        selectedCharacterSheetId.update { characterSheetId }
    }

    fun hideInventoryDialog() {
        selectedCharacterSheetId.update { null }
    }
}