package com.example.ops_android.ui.warehouse

import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import com.example.ops_android.data.model.Container
import com.example.ops_android.data.model.Item
import com.example.ops_android.data.repository.WarehouseRepository
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

data class WarehouseUiState(
    val containers: List<Container> = emptyList(),
    val items: List<Item> = emptyList(),
    val breadcrumb: List<Pair<Int, String>> = listOf(0 to "根目录"),
    val showItemsOnly: Boolean = false,
    val isLoading: Boolean = false,
    val isRefreshing: Boolean = false,
    val errorMessage: String? = null
)

class WarehouseViewModel(
    private val repo: WarehouseRepository
) : ViewModel() {
    private val _s = MutableStateFlow(WarehouseUiState()); val s: StateFlow<WarehouseUiState> = _s.asStateFlow()

    init { loadContainers(null) }

    fun loadContainers(parentId: Int?) {
        viewModelScope.launch {
            _s.value = _s.value.copy(isLoading = true, isRefreshing = true)
            repo.listContainer(parentId).fold(
                onSuccess = { _s.value = _s.value.copy(containers = it) },
                onFailure = { _s.value = _s.value.copy(errorMessage = it.message) }
            )
            repo.listItem(parentId).fold(
                onSuccess = { _s.value = _s.value.copy(items = it) },
                onFailure = { }
            )
            _s.value = _s.value.copy(isLoading = false, isRefreshing = false)
        }
    }

    fun navigateTo(containerId: Int, containerName: String) {
        val breadcrumb = _s.value.breadcrumb.toMutableList()
        breadcrumb.add(containerId to containerName)
        _s.value = _s.value.copy(breadcrumb = breadcrumb)
        loadContainers(containerId)
    }

    fun navigateToBreadcrumb(index: Int) {
        val entry = _s.value.breadcrumb[index]
        _s.value = _s.value.copy(breadcrumb = _s.value.breadcrumb.take(index + 1))
        loadContainers(entry.first.takeIf { it != 0 })
    }

    fun toggleItemsOnly() { _s.value = _s.value.copy(showItemsOnly = !_s.value.showItemsOnly) }

    fun refresh() {
        loadContainers(_s.value.breadcrumb.last().first.takeIf { it != 0 })
    }

    fun addContainer(name: String) {
        val parentId = _s.value.breadcrumb.last().first
        val parentIdOrNull: Int? = parentId.takeIf { it != 0 }
        viewModelScope.launch {
            val data = mutableMapOf<String, Any>("title" to name)
            if (parentIdOrNull != null) data["parent_id"] = parentIdOrNull
            repo.addContainer(data).fold(
                onSuccess = { refresh() },
                onFailure = { _s.value = _s.value.copy(errorMessage = it.message) }
            )
        }
    }

    class Factory(private val repo: WarehouseRepository) : ViewModelProvider.Factory {
        @Suppress("UNCHECKED_CAST") override fun <T : ViewModel> create(c: Class<T>): T = WarehouseViewModel(repo) as T
    }
}
