package com.example.exvesta.Screans.Responses

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.navigation.NavHostController
import com.example.exvesta.domain.utils.Constants
import com.example.exvesta.model.ResultStateSignIn
import com.example.exvesta.model.Users
import com.example.exvesta.model.Wardob
import io.github.jan.supabase.gotrue.auth
import io.github.jan.supabase.gotrue.providers.builtin.Email
import io.github.jan.supabase.gotrue.providers.builtin.OTP
import io.github.jan.supabase.postgrest.from
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch


class  Auth(): ViewModel() {
    val _signInState = MutableStateFlow<ResultStateSignIn>(ResultStateSignIn.Loading)
    val signInState: StateFlow<ResultStateSignIn> = _signInState.asStateFlow()
    fun onSignInEmailCode(emailUser: String) {
        viewModelScope.launch {
            try {
                Constants.supabase.auth.signInWith(OTP) {
                    email = emailUser
                    createUser = false
                }

            } catch (e: Exception) {
                println(e.message.toString())

            }

        }
    }

    fun onSignInEmailPassword(emailUser: String, passwordUser: String, navHost: NavHostController) {
        viewModelScope.launch {
            try {
                val user = Constants.supabase.auth.signInWith(Email) {
                    email = emailUser
                    password = passwordUser
                }
                println(user.toString())
                println(Constants.supabase.auth.currentUserOrNull()!!.id)
                println("Success")
                val userId = Constants.supabase.auth.currentUserOrNull()?.id

                if(userId =="ef7ee127-53ac-4360-8bae-8934eebb2390"){
                    navHost.navigate("HomeAdmin")
                }
                else{
                    navHost.navigate("Home")
                }
                _signInState.value = ResultStateSignIn.Success(user)
                true
            } catch (e: Exception) {
                println("Error")
                println(e.message.toString())
                _signInState.value = ResultStateSignIn.Error(e.message ?: "Unknown error")
                false
            }
        }
    }

    fun onSignUpEmail(emailUser: String, passwordUser: String, login:String, navHost: NavHostController) {
        viewModelScope.launch {
            try {
                var user = Constants.supabase.auth.signUpWith(Email) {
                    email = emailUser
                    password = passwordUser

                }
                println("Success")
                val count = Constants.supabase.from("Users").select().data.count()
                val id =Constants.supabase.auth.currentUserOrNull()!!.id
                Log.d("newBowId", id.toString())
                Log.d("newBowId", count.toString())
                val NewUser = Users(
                    id = count+1,
                    user = id,
                    Name = login
                )
               val res =  Constants.supabase.from("Users").insert(NewUser){
                   select()
               }.decodeSingle<Users>().id
                Log.d("newBowId", res.toString())
                if(res!=null){
                    val war = Wardob(
                        id = res,
                        id_user = res
                    )
                    Constants.supabase.from("Wardob").insert(war)

                }

                navHost.navigate("Home")
                println("Success")
            } catch (e: Exception) {
                println("Error")
                println(e.message.toString())
            }

        }
    }


}




