package com.devlab.app.ui.servers

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.devlab.app.data.model.Server
import com.devlab.app.data.repository.ServerRepository
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

data class ServerListUiState(
    val isLoading: Boolean = true,
    val servers: List<Server> = emptyList(),
    val error: String? = null,
    val searchQuery: String = "",
    val currentPage: Int = 1,
    val isLoadingMore: Boolean = false,
    val hasMore: Boolean = true
)

class ServerListViewModel : ViewModel() {

    private val repository = ServerRepository()

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

    init {
        loadServers()
    }

    fun loadServers() {
        viewModelScope.launch {
            _uiState.value = _uiState.value.copy(
                isLoading = true,
                error = null,
                currentPage = 1,
                servers = emptyList()
            )
            fetchServers(page = 1)
        }
    }

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

        viewModelScope.launch {
            _uiState.value = state.copy(isLoadingMore = true)
            fetchServers(page = state.currentPage + 1, append = true)
        }
    }

    fun updateSearch(query: String) {
        _uiState.value = _uiState.value.copy(searchQuery = query)
        loadServers()
    }

    private suspend fun fetchServers(page: Int, append: Boolean = false) {
        try {
            val search = _uiState.value.searchQuery.takeIf { it.isNotBlank() }
            val response = repository.getServers(page = page, search = search)
            if (response.success) {
                val newList = if (append) {
                    _uiState.value.servers + (response.data ?: emptyList())
                } else {
                    response.data ?: emptyList()
                }
                val pagination = response.pagination
                val hasMore = pagination != null && page < pagination.total_pages
                _uiState.value = _uiState.value.copy(
                    isLoading = false,
                    isLoadingMore = false,
                    servers = newList,
                    currentPage = page,
                    hasMore = hasMore,
                    error = null
                )
            } else {
                _uiState.value = _uiState.value.copy(
                    isLoading = false,
                    isLoadingMore = false,
                    error = response.error ?: "Failed to load servers"
                )
            }
        } catch (e: Exception) {
            _uiState.value = _uiState.value.copy(
                isLoading = false,
                isLoadingMore = false,
                error = e.message ?: "Network error"
            )
        }
    }
}
