package com.vpn.fastestvpnservice.viewmodels

import android.content.Context
import android.util.Log
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.platform.LocalContext
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewmodel.compose.viewModel
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.vpn.fastestvpnservice.beans.Server
import com.vpn.fastestvpnservice.beans.ServerData
import com.vpn.fastestvpnservice.beans.ServerResponse
import com.vpn.fastestvpnservice.helpers.BasePreferenceHelper
import com.vpn.fastestvpnservice.retrofit.RetrofitNetworkHandling
import com.vpn.fastestvpnservice.retrofit.WebServiceFactory
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import retrofit2.Call

class SearchListViewModel constructor(
    context: Context,
    serverListViewModel: ServerListViewModel,
    splashViewModel: SplashViewModel
    ): ViewModel() {

    private var serverListViewModel: ServerListViewModel
    private var splashViewModel: SplashViewModel
    val mutableLiveDataFavUnFav = MutableLiveData<ServerResponse?>()


    init {
        this.serverListViewModel = serverListViewModel
        this.splashViewModel = splashViewModel
    }

    private var _searchText = MutableLiveData<String>("")
    var searchText: LiveData<String> = _searchText

    private var _isActive = MutableLiveData<Boolean>(false)
    var isActive: LiveData<Boolean> = _isActive


    val basePreferenceHelper = BasePreferenceHelper(context)

    private var _countriesList = MutableLiveData<ArrayList<Server>>(getCountries())
    var countriesList: LiveData<ArrayList<Server>> = _countriesList

     suspend fun searchTextChange(text: String) {
//        Log.d("test_search_logic", "B:=> ${_searchText.value} & $text")
        _searchText.value = text

//        Log.d("test_search_logic", "A:=> ${_searchText.value} & $text")

//         delay(100)

         if (_searchText.value == text) {
            Log.d("test_search_logic", "Same:: => ${_searchText.value} & $text")
            _countriesList.value = getCountries()
        }
    }

    suspend fun isActiveChange(state: Boolean) {
        _isActive.value = state

        if (_isActive.value == false) {
            searchTextChange("")
//            _searchText.value = ""
//            _countriesList.value = getCountries()
        }
    }

    private var debounceJob: Job? = null

    fun debounceSearch(text: String, scope: CoroutineScope = CoroutineScope(IO)) {
        debounceJob?.cancel() // Cancel any previous debounce job
        debounceJob = scope.launch {
            delay(500) // Adjust delay as needed
            if (_searchText.value == text) {
                Log.d("test_search_logic", "Same:: => ${_searchText.value} & $text")
                getCountries()
            }
        }
    }

    fun getCountries(): ArrayList<Server> {
        val serversData = basePreferenceHelper.getServerData()
        val allServers: ArrayList<Server> = ArrayList<Server>()
        val serversArray: ArrayList<Server> = ArrayList<Server>()
        var filtersArray: ArrayList<Server> = ArrayList<Server>()
        var emptyArray: ArrayList<Server> = ArrayList<Server>()


        serversData.forEachIndexed { index, serverData ->
            serverData.servers?.forEachIndexed { indexes, server ->
                allServers.add(indexes, server)
            }
        }

        val searchServersList = serverListViewModel.filterServersAllCategory(allServers)

        searchServersList.forEachIndexed { index, server ->
            if (server.country?.lowercase()?.contains(_searchText.value?.lowercase().toString()) == true
                || server.server_name?.lowercase()?.contains(_searchText.value?.lowercase().toString()) == true
                || server.name?.lowercase()?.contains(_searchText.value?.lowercase().toString()) == true
                || server.iso?.lowercase()?.contains(_searchText.value?.lowercase().toString()) == true) {
                serversArray.add(server)
            }
        }

        filtersArray = if (_searchText.value == ""){
            searchServersList
        } else {
            if (serversArray.size > 0) {
                serversArray
            } else {
                emptyArray
            }
        }



        Log.d("test_search", searchServersList.size.toString())
            return filtersArray
    }

    fun updateFavUnFavServerState(server: Server) {
        server.isFavourited = server.isFavourited != true
        val serverData = basePreferenceHelper.getServerData()
        val allServers: ArrayList<Server> = ArrayList<Server>()

        serverData.forEachIndexed { i, serverDataList ->
            serverDataList.servers?.let {serverList ->
                serverList.forEachIndexed { index, obj ->
                    if (obj.id == server.id) {
                        obj.isFavourited = server.isFavourited
                        serverList.set(index, obj)
                    }
                }
            }
        }

        serverData.forEachIndexed { index1, serverData1 ->
            serverData1.servers?.forEachIndexed { indexes, server ->
                allServers.add(indexes, server)
            }
        }

        val searchServersList = serverListViewModel.filterServersAllCategory(allServers)
        _countriesList.value = searchServersList

        basePreferenceHelper.saveServerData(serverData)
    }

}