package com.example.tomatoandpotatoapp.ViewModelsPack

import android.content.Context
import android.content.SharedPreferences
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.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 io.github.jan.supabase.postgrest.from
import io.github.jan.supabase.storage.storage
import kotlinx.coroutines.launch

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

    private val _user = mutableStateOf(listOf<UsersTable>())
    val user: State<List<UsersTable>> = _user

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

    var alonePlant by mutableStateOf<Plants?>(null)

    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


    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): String? {
        val sharedPref = SharedPreferenceHelper(context)
        return sharedPref.getStringData("accessToken")
    }

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

    }

    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("Успешный вход!")

                Log.d("ЧТо нибудь", "бла бла бла бебебе")
            } catch (e: Exception) {
                _userState.value = UserState.Error("Error ${e.message}")
                Log.d("ЧТо нибудь", "${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}")
            }
        }
    }


    fun addPeople() {
        viewModelScope.launch {
            try {
                _userState.value = UserState.Loading
                client.from("UsersTable").insert(
                    UsersTable(
                        idRole = 2,
                        genderId = null,
                        uid = client.auth.currentUserOrNull()!!.id
                    )
                )
                Log.d("ЧТо нибудь нужное и полезное нигер", "БЕЗУспешное получение дауна")
            } catch (e: Exception) {
                _userState.value = UserState.Error("Error ${e.message}")

                Log.d("ЧТо нибудь", "${e.message}")
            }
        }
    }

    fun addAvatar(byteArray: ByteArray) {
        viewModelScope.launch {
            try {

                _userState.value = UserState.Loading
                val basket = client.storage["avatars"]
                if(byteArray.isNotEmpty()){
                    try {
                        basket.upload(
                            "${client.auth.currentUserOrNull()!!.email}.jpg",
                            byteArray,
                            options = { }
                        )
                        client.from("UsersTable").update(
                            {
                                UsersTable::image setTo basket.publicUrl("${client.auth.currentUserOrNull()!!.email}.jpg")

                            }
                        ) {
                            filter {
                                UsersTable::uid eq client.auth.currentUserOrNull()!!.id
                            }
                        }
                    }catch (e: Exception){
                        basket.update(
                            "${client.auth.currentUserOrNull()!!.email}.jpg",
                            byteArray,
                            options = { }
                        )
                        client.from("UsersTable").update(
                            {
                                UsersTable::image setTo basket.publicUrl("${client.auth.currentUserOrNull()!!.email}.jpg")

                            }
                        ) {
                            filter {
                                UsersTable::uid eq client.auth.currentUserOrNull()!!.id
                            }
                        }
                    }
                }
                _userState.value = UserState.Success("ВАУ КРУТО добавлена фото")
            } catch (e: Exception) {
                _userState.value = UserState.Error("Error: ${e.message}")
                Log.d("Что-то надо там", e.message!!)
            }
        }
    }

    fun updatePeople(firstname: String, genderId: Int?, birthDate: String) {
        viewModelScope.launch {
            try {
                _userState.value = UserState.Loading
                client.from("UsersTable").update({
                    UsersTable::firstName setTo firstname
                    UsersTable::genderId setTo genderId
                    UsersTable::birthDate setTo birthDate
                })
                {
                    filter { UsersTable::uid eq client.auth.currentUserOrNull()!!.id }
                }
                _userState.value = UserState.Success("УРА МЫ ОБНОВИЛИСЬ НЕГРЫ")
                Log.d("ЧТо нибудь нужное и полезное нигер", "БЕЗУспешное обновление дауна")

            } catch (e: Exception) {
                _userState.value = UserState.Error("Error ${e.message}")
                Log.d("ЧТо нибудь", "${e.message}")
            }
        }
    }

    fun selectPeople() {
        viewModelScope.launch {
            try {
                _userState.value = UserState.Loading
                _user.value = client.from("UsersTable").select {
                    filter {
                        UsersTable::uid eq
                                client.auth.currentUserOrNull()!!.id
                    }
                }.decodeList<UsersTable>()
                _userState.value = UserState.Success("Успешное получение дауна")
                Log.d("ЧТо нибудь нужное и полезное нигер", "БЕЗУспешное получение дауна")

            } catch (e: Exception) {
                _userState.value = UserState.Error("Error ${e.message}")
                Log.d("ЧТо нибудь", "${e.message}")
            }
        }
    }

    fun isUserLoggedIn(
        context: Context
    ) {
        viewModelScope.launch {
            try {
                val token = getToken(context)
                if (token.isNullOrEmpty()) {
                    _userState.value = UserState.Error("Пользователь не вошёл в систему")
                } else {
                    client.auth.retrieveUser(token)
                    client.auth.refreshCurrentSession()
                    saveToken(context)
                    _userState.value = UserState.Success("Пользователь уже вошёл в систему")
                    Log.d("ЧТо нибудь", "Какая-то ошибка")
                }

            } catch (e: Exception) {
                _userState.value = UserState.Error("Error${e.message}")
                Log.d("ЧТо нибудь", "${e.message}")
            }
        }
    }
}
