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.ConversationSummary
import de.oaa.xxx.app.data.model.FriendshipDto
import de.oaa.xxx.app.data.model.MessageDto
import de.oaa.xxx.app.data.model.User
import de.oaa.xxx.app.data.model.UserProfile
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch

class SocialViewModel : ViewModel() {

    private val _friends = MutableStateFlow<List<FriendshipDto>>(emptyList())
    val friends: StateFlow<List<FriendshipDto>> = _friends

    private val _pending = MutableStateFlow<List<FriendshipDto>>(emptyList())
    val pending: StateFlow<List<FriendshipDto>> = _pending

    private val _searchResults = MutableStateFlow<List<User>>(emptyList())
    val searchResults: StateFlow<List<User>> = _searchResults

    private val _conversations = MutableStateFlow<List<ConversationSummary>>(emptyList())
    val conversations: StateFlow<List<ConversationSummary>> = _conversations

    private val _messages = MutableStateFlow<List<MessageDto>>(emptyList())
    val messages: StateFlow<List<MessageDto>> = _messages

    private val _viewedProfile = MutableStateFlow<UserProfile?>(null)
    val viewedProfile: StateFlow<UserProfile?> = _viewedProfile

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

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

    fun loadFriends() {
        viewModelScope.launch {
            _isLoading.value = true
            try {
                val f = ApiClient.socialApi.getFriends()
                val p = ApiClient.socialApi.getPendingRequests()
                if (f.isSuccessful) _friends.value = f.body() ?: emptyList()
                if (p.isSuccessful) _pending.value = p.body() ?: emptyList()
            } catch (e: Exception) {
                _error.value = e.message
            } finally {
                _isLoading.value = false
            }
        }
    }

    fun searchUsers(query: String) {
        viewModelScope.launch {
            try {
                val resp = ApiClient.socialApi.searchUsers(query)
                if (resp.isSuccessful) _searchResults.value = resp.body() ?: emptyList()
            } catch (e: Exception) {
                _error.value = e.message
            }
        }
    }

    fun sendFriendRequest(userId: String) {
        viewModelScope.launch {
            try {
                ApiClient.socialApi.sendFriendRequest(mapOf("receiverId" to userId))
            } catch (e: Exception) {
                _error.value = e.message
            }
        }
    }

    fun acceptRequest(friendshipId: String) {
        viewModelScope.launch {
            try {
                ApiClient.socialApi.acceptFriendRequest(mapOf("friendshipId" to friendshipId))
                loadFriends()
            } catch (e: Exception) {
                _error.value = e.message
            }
        }
    }

    fun rejectRequest(friendshipId: String) {
        viewModelScope.launch {
            try {
                ApiClient.socialApi.rejectFriend(mapOf("friendshipId" to friendshipId))
                loadFriends()
            } catch (e: Exception) {
                _error.value = e.message
            }
        }
    }

    fun loadConversations() {
        viewModelScope.launch {
            _isLoading.value = true
            try {
                val resp = ApiClient.socialApi.getConversations()
                if (resp.isSuccessful) _conversations.value = resp.body() ?: emptyList()
            } catch (e: Exception) {
                _error.value = e.message
            } finally {
                _isLoading.value = false
            }
        }
    }

    fun loadMessages(partnerId: String) {
        viewModelScope.launch {
            _isLoading.value = true
            try {
                val resp = ApiClient.socialApi.getConversation(partnerId)
                if (resp.isSuccessful) _messages.value = resp.body() ?: emptyList()
            } catch (e: Exception) {
                _error.value = e.message
            } finally {
                _isLoading.value = false
            }
        }
    }

    fun sendMessage(receiverId: String, text: String) {
        viewModelScope.launch {
            try {
                ApiClient.socialApi.sendMessage(mapOf("receiverId" to receiverId, "text" to text))
                loadMessages(receiverId)
            } catch (e: Exception) {
                _error.value = e.message
            }
        }
    }

    fun loadUserProfile(userId: String) {
        viewModelScope.launch {
            _isLoading.value = true
            try {
                val resp = ApiClient.socialApi.getUserProfile(userId)
                if (resp.isSuccessful) _viewedProfile.value = resp.body()
            } catch (e: Exception) {
                _error.value = e.message
            } finally {
                _isLoading.value = false
            }
        }
    }

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