package com.example.iplace.main.viewModel

import android.content.Context
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.State
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.core.os.bundleOf
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import androidx.navigation.NavHostController
import com.example.iplace.R
import com.example.iplace.domain.Constants
import com.example.iplace.model.Gender
import com.example.iplace.model.Users
import io.github.jan.supabase.gotrue.auth
import io.github.jan.supabase.gotrue.providers.builtin.Email
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 MainViewModel(): ViewModel() {

    private val _authData = mutableStateOf(AuthData())
    val authData: State<AuthData> = _authData

    fun onSignInEmailPassword(emailUser: String, passwordUser1: String, navController: NavHostController) {
        _authData.value = AuthData(email = emailUser, password = passwordUser1)
        viewModelScope.launch {
            try {
                val user = Constants.supabase.auth.signInWith(Email) {
                    email = emailUser
                    password = passwordUser1
                }

                println(user.toString())
                println(Constants.supabase.auth.currentUserOrNull()!!.id)
                println("Success")
                navController.navigate("menuV")
            } catch (e: Exception) {
                println("Error")
                println(e.message.toString())
            }
        }
    }
    fun onSignUpEmail(emailUser: String, passwordUser1: String, passwordUser2: String, navController: NavHostController) {
        _authData.value = AuthData(email = emailUser, password = passwordUser1)

        if(emailUser != "" && passwordUser1 != "" && passwordUser2 != "" ) {

            if(passwordUser1 == passwordUser2) {
                if(passwordUser1.length >= 8){

                    viewModelScope.launch {
                        try{
                            val user = Constants.supabase.auth.signUpWith(Email) {
                                email = emailUser
                                password = passwordUser1
                            }

                            println(user.toString())
                            println(Constants.supabase.auth.currentUserOrNull()!!.id)
                            println("Success")

                            navController.navigate("creatingUser")
                        }
                        catch (e: Exception) {
                            println("Error")
                            println(e.message.toString())
                        }

                    }
                }
                else Log.i("Reg", "Длина пароля должна быть от 8 до 64 символов")
            }
            else Log.i("Reg", "Пароли не совпадают")

        }
        else Log.i("Reg", "Не все поля заполнены")

    }


    fun AddNewUserInTable(nameUser: String, address: String, about_me: String, id_genderFK: String, img_user: String, navController: NavHostController){
        viewModelScope.launch {
            try {
                // Получаем email и password из authData
                val email = authData.value.email
                val password = authData.value.password

                // Проверяем, авторизован ли пользователь
                if (Constants.supabase.auth.currentUserOrNull() == null) {
                    // Если нет, то пытаемся авторизоваться с сохраненными данными
                    if (email.isNotEmpty() && password.isNotEmpty()) {
                        Constants.supabase.auth.signInWith(Email) {
                            this.email = email
                            this.password = password
                        }
                    } else {
                        // Обработка ситуации, когда нет сохраненных данных
                        Log.e("AddNewUserInTable", "No user data found for sign-in.")
                        return@launch
                    }
                }

                val idUser = Constants.supabase.auth.currentUserOrNull()?.id ?: return@launch
                val newUser = Users(id_UUID = idUser, name = nameUser, address = address, about_me = about_me, id_genderFK = 1, img_user = "dsad")

                Constants.supabase.from("users").insert(newUser)

                navController.navigate("policyConditionality")
            } catch (e: Exception) {
                Log.e("AddNewUserInTable", "Error adding user: ${e.message}")
            }
        }
    }

}








