package com.example.mystictale.ViewModels

import android.content.Context
import android.util.Log
import androidx.compose.runtime.State
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.mystictale.Constants.SupabaseConnect
import com.example.mystictale.models.UserState
import com.example.mystictale.resources.SharedPreferenceHelper
import io.github.jan.supabase.auth.auth
import io.github.jan.supabase.auth.providers.builtin.Email
import kotlinx.coroutines.launch

class AuthViewModel: ViewModel() {
    private val _userState = mutableStateOf<UserState>(UserState.Loading)
    val userState: State<UserState> = _userState
    var emailUser by mutableStateOf<String?>(null)
    var passwordUser by mutableStateOf<String?>(null)
    var dateOfBirth by mutableStateOf<String?>(null)
    var gender by mutableStateOf<Int?>(null)
    var name by mutableStateOf<String?>(null)
    fun onSignUpEmailPassword(context: Context) {
        viewModelScope.launch {
            try {
                _userState.value = UserState.Loading
                SupabaseConnect.supabase.auth.signUpWith(Email) {
                    email = emailUser!!
                    password = passwordUser!!
                }
                saveToken(context)
                _userState.value = UserState.Success("Success sing up")
                Log.d("my_tag","Success sing up")


            } catch (e: Exception) {
                _userState.value = UserState.Error("Error: ${e.message}")
                Log.d("my_tag",e.message!!)

            }

        }
    }

    private fun saveToken(context: Context) {
        viewModelScope.launch {
            val accessToken = SupabaseConnect.supabase.auth.currentAccessTokenOrNull()
            val sharedPref = SharedPreferenceHelper(context)
            sharedPref.saveStringData("accessToken", accessToken)
        }
    }

    private fun getToken(context: Context): String? {
        val sharedPref = SharedPreferenceHelper(context)
        return sharedPref.getStringData("accessToken")

    }




}