package com.seven.ikar.kotlin.feature.chatinfo

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.seven.ikar.kotlin.app.AppContainer
import com.seven.ikar.kotlin.core.model.MessageDto
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

enum class ChatMaterialFilter(val routeValue: String, val wireValue: String, val title: String) {
    Media("media", "media", "Медиа"),
    Files("files", "files", "Файлы"),
    Links("links", "links", "Ссылки"),
    Voice("voice", "voice", "Голосовые"),
    Pinned("pinned", "pinned", "Закреплённые");

    companion object {
        fun fromRoute(value: String?): ChatMaterialFilter =
            entries.firstOrNull { it.routeValue == value } ?: Media
    }
}

data class ChatMaterialsUiState(
    val filter: ChatMaterialFilter,
    val messages: List<MessageDto> = emptyList(),
    val page: Int = 1,
    val hasMore: Boolean = false,
    val isLoading: Boolean = false,
    val isLoadingMore: Boolean = false,
    val errorMessage: String? = null
)

class ChatMaterialsViewModel(
    private val container: AppContainer,
    private val chatId: String,
    private val filter: ChatMaterialFilter
) : ViewModel() {
    private val _uiState = MutableStateFlow(ChatMaterialsUiState(filter = filter, isLoading = true))
    val uiState: StateFlow<ChatMaterialsUiState> = _uiState.asStateFlow()

    init {
        refresh()
    }

    fun refresh() {
        loadPage(page = 1, append = false)
    }

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

        loadPage(page = state.page + 1, append = true)
    }

    private fun loadPage(page: Int, append: Boolean) {
        viewModelScope.launch {
            val current = _uiState.value
            _uiState.value = current.copy(
                isLoading = !append,
                isLoadingMore = append,
                errorMessage = null
            )
            runCatching {
                container.executeAuthorized { session ->
                    container.apiClient.searchChatMessagesPage(
                        accessToken = session.accessToken,
                        chatId = chatId,
                        query = " ",
                        filter = filter.wireValue,
                        page = page,
                        limit = 40
                    )
                }
            }.onSuccess { result ->
                val existing = if (append) _uiState.value.messages else emptyList()
                _uiState.value = _uiState.value.copy(
                    messages = (existing + result.messages).distinctBy { it.id },
                    page = result.page,
                    hasMore = result.hasMore,
                    isLoading = false,
                    isLoadingMore = false
                )
            }.onFailure { error ->
                _uiState.value = _uiState.value.copy(
                    isLoading = false,
                    isLoadingMore = false,
                    errorMessage = error.message
                )
            }
        }
    }
}
