package com.jishisongfu.duobibi.ui.arena

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.jishisongfu.duobibi.data.repo.ArenaOutcome
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 ArenaUiState {
    data object Idle : ArenaUiState
    data object Loading : ArenaUiState
    data class Success(val outcome: ArenaOutcome) : ArenaUiState
    data class Error(val message: String) : ArenaUiState
}

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

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

    private val _input = MutableStateFlow("")
    val input: StateFlow<String> = _input.asStateFlow()

    /** 当前锁定的品类。null = 未选,走 ARENA_PLATFORMS 默认 4 大电商。 */
    private val _selectedCategory = MutableStateFlow<ArenaCategory?>(null)
    val selectedCategory: StateFlow<ArenaCategory?> = _selectedCategory.asStateFlow()

    fun setInput(s: String) { _input.value = s }

    /**
     * 切换品类。传 null 表示退出品类、回到默认电商比价。
     * 切换时清空旧结果,回到 Idle 让品类首屏或结果页正确刷新。
     */
    fun selectCategory(c: ArenaCategory?) {
        if (_selectedCategory.value == c) return
        _selectedCategory.value = c
        _state.value = ArenaUiState.Idle
    }

    fun submit() {
        val q = _input.value.trim()
        if (q.isEmpty()) {
            _state.value = ArenaUiState.Error("请输入要比价的商品名")
            return
        }
        _state.value = ArenaUiState.Loading
        val platforms = _selectedCategory.value?.platforms
        viewModelScope.launch {
            runCatching { repo.arenaQuote(q, platforms) }
                .onSuccess { _state.value = ArenaUiState.Success(it) }
                .onFailure { _state.value = ArenaUiState.Error("比价失败,请稍后重试") }
        }
    }

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

    /** 从擂台一键加入"想买的"降价雷达。target 通常传擂台搜出来的全网最低价。 */
    fun addToAlert(title: String, targetPrice: Double, onDone: () -> Unit) {
        if (title.isBlank() || targetPrice <= 0) return
        viewModelScope.launch {
            repo.addWantAlert(title.trim(), null, targetPrice)
            onDone()
        }
    }

    /**
     * 给"发现"页用:外部带着 title(可选品类)直接预填 + 提交,
     * 调用方再跳到"比价"Tab,出对比表。
     *
     * 传 category 时会顺手锁定品类(影响后端 arena-quote 的 platforms 参数);
     * 不传则沿用用户当前已选品类(可能是 null = 默认 4 大电商)。
     */
    fun submitWithTitle(title: String, category: ArenaCategory? = null) {
        if (title.isBlank()) return
        if (category != null) _selectedCategory.value = category
        _input.value = title.trim()
        submit()
    }
}
