package com.example.triphelper.view.Registration

import android.util.Log
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.navigation.NavController
import com.example.triphelper.domain.Constants
import com.example.triphelper.model.Country
import com.example.triphelper.model.Users
import com.example.triphelper.view.navigation.NavigationRoutes
import com.google.android.gms.tasks.Tasks.await
import dagger.hilt.android.lifecycle.HiltViewModel
import io.github.jan.supabase.gotrue.Auth
import io.github.jan.supabase.gotrue.auth
import io.github.jan.supabase.gotrue.providers.builtin.Email
import io.github.jan.supabase.postgrest.from
import io.github.jan.supabase.postgrest.query.Columns
import io.github.jan.supabase.postgrest.query.Order
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import javax.inject.Inject

@HiltViewModel
class RegistrationViewModel@Inject constructor(): ViewModel(){
    private var _navigationTo = MutableStateFlow<String?>(null)
    val navigationTo = _navigationTo.asStateFlow()

    private var _country: MutableStateFlow<List<Country>> = MutableStateFlow(listOf())
    val country: StateFlow<List<Country>> = _country.asStateFlow()

    var wrongSignUp = mutableStateOf(false)
    val wrongText = mutableStateOf("")

    private val _idCountry = MutableStateFlow<Int?>(null)
    val idCountry: StateFlow<Int?> = _idCountry.asStateFlow()

    fun getCountry(){
        viewModelScope.launch {
            try {
                withContext(Dispatchers.IO) {
                    val response = Constants.supabase
                        .from("country")
                        .select(){
                            order(column = "title", order = Order.ASCENDING)
                        }
                        .decodeList<Country>()
                    _country.value = response
                }
            } catch (e: Exception) {
                Log.e("getCountry", "Error retrieving country data", e)
            }
        }
    }

    suspend fun getIdCountry(titleCountry: String) {
        try {
            val response = Constants.supabase
                .from("country")
                .select {
                    filter {
                        eq("title", titleCountry)
                    }
                }
                .decodeSingleOrNull<Country>()
            _idCountry.value = response?.id
            Log.i("id","${_idCountry.value}")

        } catch (e: Exception) {
            Log.e("getCountry", "Error retrieving country data", e)
        }
    }

    fun createNewUser(emailUser:String, nameUser:String,passwordUser:String, repeatPasswordUser:String, countryTitle:String){
        viewModelScope.launch {
            try {
                getIdCountry(countryTitle)
                if(emailUser == "" || nameUser == "" || _idCountry.value == null || passwordUser == "" || repeatPasswordUser == ""){
                    wrongSignUp.value = true
                    wrongText.value = "Заполните все данные"
                }
                else if(idCountry.value == null){
                    wrongSignUp.value = true
                    wrongText.value = "Не выбрана страна"
                }
                else if(passwordUser != repeatPasswordUser){
                    wrongSignUp.value = true
                    wrongText.value = "Пароли не совпадают"
                }
                else{
                    val user = Constants.supabase.auth.signUpWith(Email) {
                        email = emailUser
                        password = passwordUser
                    }
                    AddNewUserInTable(emailUser,nameUser,passwordUser, _idCountry.value!!)
                    Log.i("Reg", "Success")
                    wrongSignUp.value = false
                    _navigationTo.value = NavigationRoutes.MAIN
                }
            }catch (e: Exception){
                Log.i("Registration", "Error")
            }
        }
    }
    suspend fun AddNewUserInTable(emailUser: String, nameUser: String, passwordUser:String, idCountryUser:Int){
        try {
            Constants.supabase.auth.signInWith(Email) {
                email = emailUser
                password = passwordUser
            }
            val idUser = Constants.supabase.auth.currentUserOrNull()?.id ?: return
            val newUser = Users(id = idUser, avatar = null, country = idCountryUser, name = nameUser)
            Constants.supabase.from("users").insert(newUser)
        } catch (e: Exception) {
            Log.e("AddNewUserInTable", "Error adding user: ${e.message}")
        }
    }
}
