package de.krisenvorrat.app.ui.item

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import de.krisenvorrat.app.data.db.entity.ItemEntity
import de.krisenvorrat.app.domain.repository.CategoryRepository
import de.krisenvorrat.app.domain.repository.ItemRepository
import de.krisenvorrat.app.domain.repository.LocationRepository
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import javax.inject.Inject

internal data class ItemListUiState(
    val groupedItems: Map<String, List<ItemUiModel>> = emptyMap(),
    val isDeleteDialogVisible: Boolean = false,
    val itemToDelete: ItemUiModel? = null
) {
    val isEmpty: Boolean get() = groupedItems.isEmpty()
}

@HiltViewModel
internal class ItemListViewModel @Inject constructor(
    private val itemRepository: ItemRepository,
    private val categoryRepository: CategoryRepository,
    private val locationRepository: LocationRepository
) : ViewModel() {

    private val _uiState = MutableStateFlow(ItemListUiState())
    val uiState: StateFlow<ItemListUiState> = _uiState.asStateFlow()

    init {
        viewModelScope.launch {
            combine(
                itemRepository.getAll(),
                categoryRepository.getAll(),
                locationRepository.getAll()
            ) { items, categories, locations ->
                val categoryMap = categories.associate { it.id to it.name }
                val locationMap = locations.associate { it.id to it.name }

                items.map { item ->
                    ItemUiModel(
                        id = item.id,
                        name = item.name,
                        categoryName = categoryMap[item.categoryId] ?: "Unbekannt",
                        quantity = item.quantity,
                        unit = item.unit,
                        locationName = locationMap[item.locationId] ?: "Unbekannt",
                        expiryDate = item.expiryDate,
                        categoryId = item.categoryId
                    )
                }.groupBy { it.categoryName }
                    .toSortedMap()
            }.collect { grouped ->
                _uiState.update { it.copy(groupedItems = grouped) }
            }
        }
    }

    fun showDeleteDialog(item: ItemUiModel) {
        _uiState.update { it.copy(isDeleteDialogVisible = true, itemToDelete = item) }
    }

    fun dismissDeleteDialog() {
        _uiState.update { it.copy(isDeleteDialogVisible = false, itemToDelete = null) }
    }

    fun deleteItem() {
        val item = _uiState.value.itemToDelete ?: return
        viewModelScope.launch {
            try {
                itemRepository.delete(
                    ItemEntity(
                        id = item.id,
                        name = item.name,
                        categoryId = item.categoryId,
                        quantity = item.quantity,
                        unit = item.unit,
                        unitPrice = 0.0,
                        kcalPerKg = null,
                        expiryDate = item.expiryDate,
                        locationId = 0,
                        notes = "",
                        lastUpdated = 0L
                    )
                )
            } catch (_: Exception) {
                // Room-Fehler werden still behandelt
            }
        }
        _uiState.update { it.copy(isDeleteDialogVisible = false, itemToDelete = null) }
    }
}
