package com.example.tasks.viewModels

import android.content.Context
import android.util.Log
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.tasks.components.Constants
import com.example.tasks.components.SharedPreferenceHelper
import com.example.tasks.model.Seller
import com.example.tasks.model.User
import com.example.tasks.model.UserState
import io.github.jan.supabase.gotrue.OtpType
import io.github.jan.supabase.gotrue.auth
import io.github.jan.supabase.gotrue.providers.builtin.Email
import io.github.jan.supabase.gotrue.providers.builtin.OTP
import io.github.jan.supabase.postgrest.from
import io.github.jan.supabase.storage.storage
import io.github.jan.supabase.storage.upload
import kotlinx.coroutines.launch
import kotlin.time.Duration.Companion.minutes


class AuthViewModel : ViewModel() {
    private val _userState = mutableStateOf<UserState>(UserState.Loading)
    val userState: State<UserState> = _userState
    var users = listOf<User>()
    var sellers = listOf<Seller>()
    fun onSignInEmailCode(context: Context, emailUser: String) {
        viewModelScope.launch {
            try {
                _userState.value = UserState.Loading
                Constants.supabase.auth.signInWith(OTP) {
                    email = emailUser
                }
                saveToken(context)
                _userState.value = UserState.Success("Success sing in")
                Log.d("my_tag","Success")


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

            }

        }
    }
    fun onSignInEmailPassword(context: Context, emailUser: String, userPassword:String) {
        viewModelScope.launch {
            try {
                _userState.value = UserState.Loading
                Constants.supabase.auth.signInWith(Email) {
                    email = emailUser
                    password = userPassword
                }
                saveToken(context)
                _userState.value = UserState.Success("Success sing in")
                Log.d("my_tag","Success")


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

            }

        }
    }
    fun onSignUpEmailPassword(context: Context, emailUser: String, userPassword:String) {
        viewModelScope.launch {
            try {
                _userState.value = UserState.Loading
                Constants.supabase.auth.signUpWith(Email) {
                    email = emailUser
                    password = userPassword
                }
                saveToken(context)
                _userState.value = UserState.Success("Success sing up")
                Log.d("my_tag","Success")


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

            }

        }
    }

    fun checkForRegistration() {
        viewModelScope.launch {
            try {
                _userState.value = UserState.Loading
                users = Constants.supabase.from("Users")
                    .select() {
                        filter {
                            User::UID eq Constants.supabase.auth.currentUserOrNull()!!.id
                        }
                    }
                    .decodeList<User>()
                sellers = Constants.supabase.from("Sellers")
                    .select() {
                        filter {
                            Seller::UID eq Constants.supabase.auth.currentUserOrNull()!!.id
                        }
                    }
                    .decodeList<Seller>()

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

    private fun saveToken(context: Context) {
        viewModelScope.launch {
            val accessToken = Constants.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")

    }

    fun verifyOTP(emailUser: String, token: String) {
        viewModelScope.launch {
            try {
                _userState.value = UserState.Loading
                Constants.supabase.auth.verifyEmailOtp(
                    type = OtpType.Email.EMAIL,
                    email = emailUser,
                    token = token
                )
                _userState.value = UserState.Success("the correct code")
                Log.d("o", "gooood")

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

            }

        }
    }


    fun isUserLoggedIn(context: Context) {
        viewModelScope.launch {
            try {
                val token = getToken(context)
                if (token.isNullOrEmpty()) {
                    _userState.value = UserState.Error("User is not logged in")
                } else {
                    Constants.supabase.auth.retrieveUser(token)
                    Constants.supabase.auth.refreshCurrentSession()
                    saveToken(context)
                    _userState.value = UserState.Success("User is logged in")
                }

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

    fun addUser(
        name: String,
        surname: String,
        patronymic: String,
        date_of_birth: String,
        gender: String,

    ) {
        viewModelScope.launch {
            try {
                _userState.value = UserState.Loading
                val basket = Constants.supabase.storage["avatars"]
                if (gender == "Женский") {
                    Constants.supabase.from("Users").insert(
                        User(
                            LastName = surname,
                            FirstName = name,
                            DateOfBirth = date_of_birth,
                            Gender = 1,
                            UID = Constants.supabase.auth.currentUserOrNull()!!.id,
                            Patronymic = patronymic,
                            avatar = basket.publicUrl("${Constants.supabase.auth.currentUserOrNull()!!.email}.jpg")
                        )
                    )
                } else {
                    Constants.supabase.from("Users").insert(
                        User(
                            LastName = surname,
                            FirstName = name,
                            DateOfBirth = date_of_birth,
                            Gender = 2,
                            UID = Constants.supabase.auth.currentUserOrNull()!!.id,
                            Patronymic = patronymic,
                            avatar = basket.publicUrl("${Constants.supabase.auth.currentUserOrNull()!!.email}.jpg")
                        )


                    )
                }


                _userState.value = UserState.Success("The user has been successfully added")

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

            }

        }

    }

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

                _userState.value = UserState.Loading
                val basket = Constants.supabase.storage["avatars"]
                basket.upload(
                    "${Constants.supabase.auth.currentUserOrNull()!!.email}.jpg",
                    byteArray,
                    true
                )
                _userState.value = UserState.Success("The avatar has been successfully added")
            }catch (e:Exception){
                _userState.value = UserState.Error("Error: ${e.message}")
                Log.d("my_tag", e.message!!)
            }
        }
    }

    fun logout(context: Context) {
        val sharedPref = SharedPreferenceHelper(context)
        viewModelScope.launch {
            try {
                _userState.value = UserState.Loading
                Constants.supabase.auth.signOut()
                sharedPref.clearPreferences()
                _userState.value = UserState.Success("Logged out successfully!")
            } catch (e: Exception) {
                _userState.value = UserState.Error(e.message ?: "")
                Log.d("my_tag",e.message!!)
            }
        }
    }
}

