package com.fastest.pass.home.presentation.viewmodels

import android.util.Log
import androidx.lifecycle.ViewModel
import com.fastest.pass.home.domain.model.CountryInfo
import com.fastest.pass.home.utils.NewItemFormRoute
import kotlinx.coroutines.flow.MutableStateFlow

class NewItemFormViewModel : ViewModel() {
    private val _router = MutableStateFlow<NewItemFormRoute>(NewItemFormRoute.OpenNoneScreen)
    val router: MutableStateFlow<NewItemFormRoute> = _router

    private val _searchText = MutableStateFlow<String>("")
    val searchText: MutableStateFlow<String> = _searchText

    private val _countriesList = MutableStateFlow<List<CountryInfo>>(emptyList())
    val countriesList: MutableStateFlow<List<CountryInfo>> = _countriesList

    fun navigateTo(newItemFormRoute: NewItemFormRoute) {
        _router.value = newItemFormRoute
    }

    fun updateSearchText(searchText: String) {
        _searchText.value = searchText
    }

    fun getCountries(text: String, countryList: List<CountryInfo>) : List<CountryInfo> {
        var searchFilterCountries = listOf<CountryInfo>()
        var filterCountries = ArrayList<CountryInfo>()

        Log.d("searchText", "NI VM => countryList = ${countryList.size}")

        countryList.forEachIndexed { index, countryInfo ->
            if (countryInfo.name.lowercase().contains(text.lowercase()) ||
                countryInfo.flag.lowercase().contains(text.lowercase()) ||
                countryInfo.timezone.lowercase().contains(text.lowercase())) {
                Log.d("searchText", "NI VM => contains = $text")
                filterCountries.add(countryInfo)
            }
        }

        searchFilterCountries = if (text.isEmpty()) {
            countryList
        } else {
            if (filterCountries.size > 0) {
                filterCountries
            } else {
                emptyList()
            }
        }

        Log.d("searchText", "NIFS => searchFilterCountries = ${searchFilterCountries.size}")

        _countriesList.value = searchFilterCountries
        return searchFilterCountries
    }
}