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.models.Users
import com.example.mystictale.resources.SharedPreferenceHelper
import io.github.jan.supabase.auth.auth
import io.github.jan.supabase.auth.providers.builtin.Email
import io.github.jan.supabase.postgrest.from
import kotlinx.coroutines.launch

class AuthViewModel : ViewModel() {
    private val _userState = mutableStateOf<UserState>(UserState.Loading)
    val userState: State<UserState> = _userState
    var uid by mutableStateOf<String?>(null)
    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)
    private val _user = mutableStateOf(listOf<Users>())
    val user: State<List<Users>> = _user
    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!!)

            }

        }
    }

    fun onSignInEmailPassword(context: Context, emailUser: String, passwordUser: String) {
        viewModelScope.launch {
            try {
                _userState.value = UserState.Loading
                SupabaseConnect.supabase.auth.signInWith(Email) {
                    email = emailUser
                    password = passwordUser
                }

                saveToken(context)
                _userState.value = UserState.Success("Success sing in")
                Log.d("my_tag", "Success sing in")

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

    fun addProfile() {
        viewModelScope.launch {
            try {
                _userState.value = UserState.Loading
                SupabaseConnect.supabase.from("Users").insert(
                    Users(
                        name = name!!,
                        id_gender = gender!!,
                        UID = SupabaseConnect.supabase.auth.currentUserOrNull()!!.id,
                        date_of_birth = dateOfBirth!!
                    )
                )

                _userState.value = UserState.Success("Success create profile")
                Log.d("my_tag", "Success create profile")

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

    fun selectProfile() {
        viewModelScope.launch {
            try {
                _userState.value = UserState.Loading
                _user.value =  SupabaseConnect.supabase.from("Users").select {
                    filter {
                        Users::UID eq SupabaseConnect.supabase.auth.currentUserOrNull()!!.id
                    }
                }.decodeList<Users>()

                _userState.value = UserState.Success("Success create profile")
                Log.d("my_tag", "Success create profile")

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

    fun resetPassword(passwordUser: String) {
        viewModelScope.launch {
            try {
                Log.d("my_tag", uid!!)
                _userState.value = UserState.Loading
                SupabaseConnect.supabaseAdmin.auth.admin.updateUserById(uid = uid!!) {
                    password = passwordUser
                }
                _userState.value = UserState.Success("Success changed password")
                Log.d("my_tag", "Success changed password")

            } 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")

    }

}