package com.example.ops_android.ui.order

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

val ORDER_STATUSES = listOf(
    "" to "全部",
    "pending" to "待处理",
    "ordered" to "已订购",
    "arrived" to "已到货",
    "received" to "已收货",
    "lost" to "丢失",
    "returned" to "退货"
)

data class OrderListUiState(
    val orders: List<PurchaseOrder> = 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 OrderListViewModel(
    private val orderRepository: OrderRepository
) : ViewModel() {

    private val _uiState = MutableStateFlow(OrderListUiState())
    val uiState: StateFlow<OrderListUiState> = _uiState.asStateFlow()

    private val pageSize = 20
    private var currentPage = 1

    init {
        loadOrders()
    }

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

    fun refresh() {
        viewModelScope.launch {
            _uiState.value = _uiState.value.copy(isRefreshing = true, orders = emptyList())
            currentPage = 1
            val state = _uiState.value
            val result = orderRepository.getOrders(
                status = state.selectedStatus.ifEmpty { null },
                page = 1,
                entries = pageSize
            )
            result.fold(
                onSuccess = { (orders, total) ->
                    _uiState.value = _uiState.value.copy(
                        orders = orders,
                        isRefreshing = false,
                        isLoading = false,
                        hasMore = orders.size >= pageSize,
                        errorMessage = null
                    )
                },
                onFailure = { e ->
                    _uiState.value = _uiState.value.copy(
                        isRefreshing = false,
                        isLoading = false,
                        errorMessage = e.message
                    )
                }
            )
        }
    }

    fun loadMore() {
        val state = _uiState.value
        if (state.isLoadingMore || !state.hasMore) return

        viewModelScope.launch {
            _uiState.value = _uiState.value.copy(isLoadingMore = true)
            currentPage++
            val result = orderRepository.getOrders(
                status = state.selectedStatus.ifEmpty { null },
                page = currentPage,
                entries = pageSize
            )
            result.fold(
                onSuccess = { (orders, total) ->
                    _uiState.value = _uiState.value.copy(
                        orders = _uiState.value.orders + orders,
                        isLoadingMore = false,
                        hasMore = orders.size >= pageSize
                    )
                },
                onFailure = { e ->
                    _uiState.value = _uiState.value.copy(
                        isLoadingMore = false,
                        errorMessage = e.message
                    )
                }
            )
        }
    }

    private fun loadOrders() {
        viewModelScope.launch {
            _uiState.value = _uiState.value.copy(isLoading = true)
            val result = orderRepository.getOrders(entries = pageSize)
            result.fold(
                onSuccess = { (orders, total) ->
                    _uiState.value = _uiState.value.copy(
                        orders = orders,
                        isLoading = false,
                        hasMore = orders.size >= pageSize
                    )
                },
                onFailure = { e ->
                    _uiState.value = _uiState.value.copy(
                        isLoading = false,
                        errorMessage = e.message
                    )
                }
            )
        }
    }

    class Factory(
        private val orderRepository: OrderRepository
    ) : ViewModelProvider.Factory {
        @Suppress("UNCHECKED_CAST")
        override fun <T : ViewModel> create(modelClass: Class<T>): T {
            return OrderListViewModel(orderRepository) as T
        }
    }
}
