package com.example.ops_android.ui.workorder

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

val WO_STATUSES = listOf(
    "" to "全部",
    "pending" to "待处理",
    "checked" to "已检查",
    "parts_ordered" to "待配件",
    "repaired" to "已修复",
    "returned" to "已返还",
    "unrepairable" to "不可修"
)

data class WorkOrderListUiState(
    val workOrders: List<WorkOrder> = emptyList(),
    val selectedStatus: String = "",
    val isLoading: Boolean = false,
    val isRefreshing: Boolean = false,
    val isLoadingMore: Boolean = false,
    val hasMore: Boolean = true,
    val errorMessage: String? = null
)

class WorkOrderListViewModel(
    private val repository: WorkOrderRepository
) : ViewModel() {
    private val _uiState = MutableStateFlow(WorkOrderListUiState())
    val uiState: StateFlow<WorkOrderListUiState> = _uiState.asStateFlow()
    private val pageSize = 20
    private var page = 1

    init { load() }

    fun selectStatus(s: String) { _uiState.value = _uiState.value.copy(selectedStatus = s); refresh() }

    fun refresh() {
        viewModelScope.launch {
            _uiState.value = _uiState.value.copy(isRefreshing = true, workOrders = emptyList())
            page = 1
            val r = repository.list(status = _uiState.value.selectedStatus.ifEmpty { null })
            r.fold(
                onSuccess = { (list, _) -> _uiState.value = _uiState.value.copy(workOrders = list, isRefreshing = false, isLoading = false, hasMore = list.size >= pageSize) },
                onFailure = { e -> _uiState.value = _uiState.value.copy(isRefreshing = false, isLoading = false, errorMessage = e.message) }
            )
        }
    }

    fun loadMore() {
        if (_uiState.value.isLoadingMore || !_uiState.value.hasMore) return
        viewModelScope.launch {
            _uiState.value = _uiState.value.copy(isLoadingMore = true)
            page++
            val r = repository.list(status = _uiState.value.selectedStatus.ifEmpty { null }, page = page, entries = pageSize)
            r.fold(
                onSuccess = { (list, _) -> _uiState.value = _uiState.value.copy(workOrders = _uiState.value.workOrders + list, isLoadingMore = false, hasMore = list.size >= pageSize) },
                onFailure = { _uiState.value = _uiState.value.copy(isLoadingMore = false) }
            )
        }
    }

    private fun load() {
        viewModelScope.launch {
            _uiState.value = _uiState.value.copy(isLoading = true)
            repository.list().fold(
                onSuccess = { (list, _) -> _uiState.value = _uiState.value.copy(workOrders = list, isLoading = false, hasMore = list.size >= pageSize) },
                onFailure = { e -> _uiState.value = _uiState.value.copy(isLoading = false, errorMessage = e.message) }
            )
        }
    }

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