package com.aiwazian.messenger.viewModels

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.aiwazian.messenger.data.SearchInfo
import com.aiwazian.messenger.services.SearchService
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class SearchViewModel @Inject constructor(private val searchService: SearchService) : ViewModel() {
    
    private val _searchResults = MutableStateFlow<List<SearchInfo>>(emptyList())
    val searchResults = _searchResults.asStateFlow()
    
    private val _query = MutableStateFlow("")
    val query = _query.asStateFlow()

    private val _isSearching = MutableStateFlow(false)
    val isSearching = _isSearching.asStateFlow()

    private var searchJob: Job? = null
    
    fun onQueryChange(newQuery: String) {
        _query.value = newQuery
        searchJob?.cancel()
        
        val normalizedQuery = newQuery.trim().trimStart('@')
        if (normalizedQuery.isBlank()) {
            _searchResults.value = emptyList()
            _isSearching.value = false
            return
        }
        
        searchJob = viewModelScope.launch {
            _isSearching.value = true
            delay(350)
            search(normalizedQuery)
        }
    }
    
    private suspend fun search(query: String) {
        try {
            val searchResult = searchService.searchUserByUsername(query)
            if (this.query.value.trim().trimStart('@') == query) {
                _searchResults.value = searchResult ?: emptyList()
            }
        } catch (e: Exception) {
            Log.e(
                "SearchViewModel",
                "${e.message}"
            )
        } finally {
            if (this.query.value.trim().trimStart('@') == query) {
                _isSearching.value = false
            }
        }
    }
}
