package com.jishisongfu.duobibi.ui.records

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.jishisongfu.duobibi.data.db.Cluster
import com.jishisongfu.duobibi.data.db.PriceRecord
import com.jishisongfu.duobibi.data.repo.PriceRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import javax.inject.Inject

@OptIn(ExperimentalCoroutinesApi::class)
@HiltViewModel
class ClusterDetailViewModel @Inject constructor(
    private val repo: PriceRepository,
) : ViewModel() {

    private val _cluster = MutableStateFlow<Cluster?>(null)
    val cluster: StateFlow<Cluster?> = _cluster.asStateFlow()

    private val _clusterId = MutableStateFlow<Long?>(null)

    val records: StateFlow<List<PriceRecord>> = _clusterId
        .flatMapLatest { id -> if (id == null) flowOf(emptyList()) else repo.observeRecordsByCluster(id) }
        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())

    fun load(id: Long) {
        _clusterId.value = id
        viewModelScope.launch { _cluster.value = repo.clusterById(id) }
    }

    fun rename(newTitle: String) {
        val id = _clusterId.value ?: return
        viewModelScope.launch {
            repo.renameCluster(id, newTitle.trim())
            _cluster.value = repo.clusterById(id)
        }
    }

    fun deleteRecord(recordId: Long, onClusterEmpty: () -> Unit) {
        viewModelScope.launch {
            repo.deleteRecord(recordId)
            if (records.value.size - 1 <= 0) onClusterEmpty()
        }
    }

    fun deleteCluster(onDone: () -> Unit) {
        val id = _clusterId.value ?: return
        viewModelScope.launch { repo.deleteCluster(id); onDone() }
    }
}
