package com.example.tomatoandpotatoapp.ViewModelsPack

import android.content.Context
import android.content.SharedPreferences
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.tomatoandpotatoapp.data.models.GenderTable
import com.example.tomatoandpotatoapp.data.models.Plants
import com.example.tomatoandpotatoapp.data.models.RolesTable
import com.example.tomatoandpotatoapp.data.models.TypesOfPlants
import com.example.tomatoandpotatoapp.data.models.UserState
import com.example.tomatoandpotatoapp.data.models.UsersTable
import com.example.tomatoandpotatoapp.data.network.TomatAndPotatClient.client
import com.example.tomatoandpotatoapp.utils.SharedPreferenceHelper
import io.github.jan.supabase.auth.admin.AdminUserBuilder
import io.github.jan.supabase.auth.auth
import io.github.jan.supabase.auth.providers.builtin.Email
import kotlinx.coroutines.launch

class SupabaseAuthViewModel : ViewModel() {
    private val _userState = mutableStateOf<UserState>(UserState.Loading)
    val userState: State<UserState> = _userState

    private val _users = mutableStateOf(listOf<UsersTable>())
    val users: State<List<UsersTable>> = _users

    private val _plants = mutableStateOf(listOf<Plants>())
    val plants: State<List<Plants>> = _plants

    private val _typesOfPlants = mutableStateOf(listOf<TypesOfPlants>())
    val typesOfPlants: State<List<TypesOfPlants>> = _typesOfPlants

    private val _roles = mutableStateOf(listOf<RolesTable>())
    val roles: State<List<RolesTable>> = _roles

    private val _genders = mutableStateOf(listOf<GenderTable>())
    val genders: State<List<GenderTable>> = _genders

    fun singUp(
        context: Context,
        userEmail: String,
        userPassword: String
    ) {
        viewModelScope.launch {
            try {
                client.auth.signInWith(Email) {
                    email = userEmail
                    password = userPassword
                }
                saveToken(context)
                _userState.value = UserState.Success("Регистрация успешно пройдена!")
            } catch (e: Exception) {
                _userState.value = UserState.Error("Error${e.message}")
            }
        }

    }

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

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

    fun singIn(
        context: Context,
        userEmail: String,
        userPassword: String
    ) {
        viewModelScope.launch {
            try {
                client.auth.signInWith(Email) {
                    email = userEmail
                    password = userPassword
                }
                saveToken(context)
                _userState.value = UserState.Success("Успешный вход!")
            }catch (e:Exception){
                _userState.value = UserState.Error("Error ${e.message}")
            }
        }
    }

    fun singOut(context: Context){
        val sharedPref =SharedPreferenceHelper(context)
        viewModelScope.launch {
            try {
                client.auth.signOut()
                sharedPref.clearPreferences()
                _userState.value = UserState.Success("Успешный выход!")

            }catch (e:Exception){
                _userState.value =UserState.Error("Error ${e.message}")
            }
        }
    }


}