package com.devlab.app.ui.notifications

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.devlab.app.ServerManagerApp
import com.devlab.app.data.api.RetrofitClient
import com.devlab.app.data.model.AppNotification
import com.devlab.app.util.PreferencesManager
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

data class NotificationsUiState(
    val isLoading: Boolean = true,
    val notifications: List<AppNotification> = emptyList(),
    val unreadCount: Int = 0,
    val error: String? = null,
    val currentPage: Int = 1,
    val hasMore: Boolean = true,
    val isLoadingMore: Boolean = false
)

class NotificationsViewModel : ViewModel() {

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

    init { load() }

    fun load() {
        viewModelScope.launch {
            _uiState.value = _uiState.value.copy(isLoading = true, error = null, currentPage = 1)
            fetchPage(1)
        }
    }

    fun loadMore() {
        val state = _uiState.value
        if (state.isLoadingMore || !state.hasMore) return
        viewModelScope.launch {
            _uiState.value = state.copy(isLoadingMore = true)
            fetchPage(state.currentPage + 1, append = true)
        }
    }

    fun markAsRead(id: Int) {
        viewModelScope.launch {
            try {
                RetrofitClient.getApiService().markNotificationRead(id)
                val updated = _uiState.value.notifications.map {
                    if (it.id == id) it.copy(is_read = 1) else it
                }
                val newUnread = (_uiState.value.unreadCount - 1).coerceAtLeast(0)
                _uiState.value = _uiState.value.copy(notifications = updated, unreadCount = newUnread)
            } catch (_: Exception) { }
        }
    }

    fun markAllAsRead() {
        viewModelScope.launch {
            try {
                RetrofitClient.getApiService().markAllNotificationsRead()
                val updated = _uiState.value.notifications.map { it.copy(is_read = 1) }
                _uiState.value = _uiState.value.copy(notifications = updated, unreadCount = 0)
            } catch (_: Exception) { }
        }
    }

    private suspend fun fetchPage(page: Int, append: Boolean = false) {
        try {
            val response = RetrofitClient.getApiService().getNotifications(page = page)
            if (response.success) {
                val list = if (append) _uiState.value.notifications + response.data else response.data
                val pagination = response.pagination
                val hasMore = pagination != null && page < pagination.total_pages
                _uiState.value = _uiState.value.copy(
                    isLoading = false,
                    isLoadingMore = false,
                    notifications = list,
                    currentPage = page,
                    hasMore = hasMore,
                    unreadCount = response.unread_count
                )
            } else {
                _uiState.value = _uiState.value.copy(
                    isLoading = false, isLoadingMore = false,
                    error = response.error ?: "Failed to load"
                )
            }
        } catch (e: Exception) {
            _uiState.value = _uiState.value.copy(
                isLoading = false, isLoadingMore = false,
                error = e.message ?: "Network error"
            )
        }
    }
}
