package com.example.dtf.viewmodels

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.PagingData
import com.example.dtf.PreferencesManager
import com.example.dtf.models.Comment
import com.example.dtf.models.Like
import com.example.dtf.models.Post
import com.example.dtf.repositories.ICommentRepository
import com.example.dtf.repositories.ILikeRepository
import com.example.dtf.repositories.IPostRepository
import com.example.dtf.repositories.IUserRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.launch
import java.util.Date
import javax.inject.Inject

@HiltViewModel
class PostViewModel @Inject constructor(
    private val postRepository: IPostRepository,
    private val commentRepository: ICommentRepository,
    private val likeRepository: ILikeRepository,
    private val userRepository: IUserRepository
) : ViewModel() {
    private val _post = MutableLiveData<Post>()
    val post: LiveData<Post>
        get() = _post

    fun retrievePost(postId: Int) {
        viewModelScope.launch {
            postRepository.getById(postId).collect {
                _post.postValue(it)
            }
        }
    }

    fun getLikes(postId: Int) = likeRepository.countByPost(postId)

    fun likePost(sharedPref: PreferencesManager, postId: Int) {
        val userId = sharedPref.getData("userId", "-1").toInt()

        if (userId == -1) return

        viewModelScope.launch {
            likeRepository.insert(Like(userId, postId))
        }
    }

    fun unlikePost(sharedPref: PreferencesManager, postId: Int) {
        val userId = sharedPref.getData("userId", "-1").toInt()

        if (userId == -1) return

        viewModelScope.launch {
            likeRepository.delete(Like(userId, postId))
        }
    }

    fun isLiked(sharedPref: PreferencesManager, postId: Int)
        = likeRepository.isLikedByUser(
            sharedPref.getData("userId", "-1").toInt(),
            postId
        )

    fun addComment(sharedPref: PreferencesManager, postId: Int, content: String) {
        val userId = sharedPref.getData("userId", "-1").toInt()

        if (userId == -1 || content.trim().isEmpty()) return

        viewModelScope.launch {
            commentRepository.insert(
                Comment(
                    null,
                    userId,
                    postId,
                    content,
                    "${Date().year + 1900}-${Date().month + 1}-${Date().date}",
                    sharedPref.getData("username", "Unknown")
                )
            )
        }
    }

    fun getCommentsAuthor(comment: Comment) = userRepository.getById(comment.user_id)

    fun getCommentsListUiState(postId: Int): Flow<PagingData<Comment>> = commentRepository.getByPost(postId)
}