package com.jishisongfu.duobibi.ui.worth

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.jishisongfu.duobibi.data.api.WorthBuyResponse
import com.jishisongfu.duobibi.data.repo.PriceRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject

sealed interface WorthUiState {
    data object Idle : WorthUiState
    data object Loading : WorthUiState
    data class Success(val result: WorthBuyResponse) : WorthUiState
    data class Error(val message: String) : WorthUiState
}

@HiltViewModel
class WorthBuyViewModel @Inject constructor(
    private val repo: PriceRepository,
) : ViewModel() {

    private val _state = MutableStateFlow<WorthUiState>(WorthUiState.Idle)
    val state: StateFlow<WorthUiState> = _state.asStateFlow()

    private val _title = MutableStateFlow("")
    val title: StateFlow<String> = _title.asStateFlow()

    private val _price = MutableStateFlow("")
    val price: StateFlow<String> = _price.asStateFlow()

    fun setTitle(s: String) { _title.value = s }
    fun setPrice(s: String) { _price.value = s.filter { it.isDigit() || it == '.' } }

    fun submit() {
        val t = _title.value.trim()
        val p = _price.value.toDoubleOrNull()
        if (t.isEmpty()) { _state.value = WorthUiState.Error("请输入商品名"); return }
        if (p == null || p <= 0) { _state.value = WorthUiState.Error("请输入有效的到手价"); return }
        _state.value = WorthUiState.Loading
        viewModelScope.launch {
            runCatching { repo.worthBuy(t, p) }
                .onSuccess { _state.value = WorthUiState.Success(it) }
                .onFailure {
                    // DEBUG: 把异常类型 + message 暴露到 UI 和 logcat,方便定位调用失败
                    android.util.Log.e("WorthBuyVM", "worthBuy failed", it)
                    _state.value = WorthUiState.Error(
                        "评估失败: ${it::class.simpleName}: ${it.message ?: "(no message)"}",
                    )
                }
        }
    }

    fun reset() { _state.value = WorthUiState.Idle }

    /**
     * 值不值评估完后,行动 CTA "加入降价雷达" 用 —— 把当前 title 设为想买的雷达,
     * 心理价默认 = 评估时的到手价(意思:再降破我现在能买到的价就提醒)。
     */
    fun addToAlert(title: String, targetPrice: Double, onDone: () -> Unit) {
        if (title.isBlank() || targetPrice <= 0) return
        viewModelScope.launch {
            repo.addWantAlert(title.trim(), null, targetPrice)
            onDone()
        }
    }
}
