// Copyright (C) 2026 Jason M. Schwefel. All Rights Reserved.
package com.coldboreballisticsllc.scopedope.ui.screens.ammo

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import com.coldboreballisticsllc.scopedope.domain.model.AmmoLoad
import com.coldboreballisticsllc.scopedope.domain.repository.AmmoRepository
import com.coldboreballisticsllc.scopedope.domain.repository.DuplicateAmmoException
import javax.inject.Inject

@HiltViewModel
class AmmoViewModel @Inject constructor(
    private val repository: AmmoRepository,
) : ViewModel() {

    private val _query   = MutableStateFlow("")
    private val _caliber = MutableStateFlow<String?>(null)

    val searchQuery:     StateFlow<String>  = _query.asStateFlow()
    val selectedCaliber: StateFlow<String?> = _caliber.asStateFlow()

    private val _addError = MutableStateFlow<String?>(null)
    val addError: StateFlow<String?> = _addError.asStateFlow()

    // All ammo from both databases as a live stream
    private val _allAmmo: StateFlow<List<AmmoLoad>> = repository.observeAll()
        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())

    val calibers: StateFlow<List<String>> = _allAmmo
        .map { list -> list.map { it.caliber }.distinct().sorted() }
        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())

    val filteredAmmo: StateFlow<List<AmmoLoad>> =
        combine(_allAmmo, _query, _caliber) { all, q, cal ->
            when {
                q.isNotBlank() -> {
                    val lower = q.lowercase()
                    all.filter { it.name.lowercase().contains(lower) ||
                                 it.caliber.lowercase().contains(lower) }
                }
                cal != null -> all.filter { it.caliber == cal }
                else        -> all
            }
        }
        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())

    fun setQuery(q: String) {
        _query.value   = q
        if (q.isNotBlank()) _caliber.value = null
    }

    fun selectCaliber(caliber: String?) {
        _caliber.value = caliber
        _query.value   = ""
    }

    fun addUserAmmo(ammo: AmmoLoad) {
        viewModelScope.launch {
            try {
                repository.addUserAmmo(ammo)
            } catch (e: DuplicateAmmoException) {
                _addError.value = e.message
            }
        }
    }

    fun clearAddError() { _addError.value = null }

    fun updateUserAmmo(ammo: AmmoLoad) {
        viewModelScope.launch { repository.updateUserAmmo(ammo) }
    }

    fun deleteUserAmmo(id: Int) {
        viewModelScope.launch { repository.deleteUserAmmo(id) }
    }
}
