package de.oaa.xxx.app.ui.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import de.oaa.xxx.app.data.api.ApiClient
import de.oaa.xxx.app.data.model.FeedItemDto
import de.oaa.xxx.app.data.model.FeedPostRequest
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch

class FeedViewModel : ViewModel() {

    private val _myFeed = MutableStateFlow<List<FeedItemDto>>(emptyList())
    val myFeed: StateFlow<List<FeedItemDto>> = _myFeed

    private val _publicFeed = MutableStateFlow<List<FeedItemDto>>(emptyList())
    val publicFeed: StateFlow<List<FeedItemDto>> = _publicFeed

    private val _isLoading = MutableStateFlow(false)
    val isLoading: StateFlow<Boolean> = _isLoading

    private val _error = MutableStateFlow<String?>(null)
    val error: StateFlow<String?> = _error

    fun loadMyFeed() {
        viewModelScope.launch {
            _isLoading.value = true
            try {
                val resp = ApiClient.feedApi.getMyFeed()
                if (resp.isSuccessful) _myFeed.value = resp.body() ?: emptyList()
                else _error.value = "Fehler beim Laden des Feeds"
            } catch (e: Exception) {
                _error.value = e.message
            } finally {
                _isLoading.value = false
            }
        }
    }

    fun loadPublicFeed() {
        viewModelScope.launch {
            _isLoading.value = true
            try {
                val resp = ApiClient.feedApi.getPublicFeed()
                if (resp.isSuccessful) _publicFeed.value = resp.body() ?: emptyList()
                else _error.value = "Fehler beim Laden"
            } catch (e: Exception) {
                _error.value = e.message
            } finally {
                _isLoading.value = false
            }
        }
    }

    fun createPost(text: String, isPublic: Boolean) {
        viewModelScope.launch {
            try {
                val resp = ApiClient.feedApi.createPost(FeedPostRequest(text, isPublic = isPublic))
                if (resp.isSuccessful) loadMyFeed()
                else _error.value = "Post konnte nicht erstellt werden"
            } catch (e: Exception) {
                _error.value = e.message
            }
        }
    }

    fun toggleLike(postId: String) {
        viewModelScope.launch {
            try {
                ApiClient.feedApi.toggleLike(postId)
                loadMyFeed()
            } catch (e: Exception) {
                _error.value = e.message
            }
        }
    }

    fun deletePost(postId: String) {
        viewModelScope.launch {
            try {
                ApiClient.feedApi.deletePost(postId)
                loadMyFeed()
            } catch (e: Exception) {
                _error.value = e.message
            }
        }
    }

    fun clearError() { _error.value = null }
}
