package com.example.tasks.viewModels

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.model.Product
import com.example.tasks.model.Seller
import com.example.tasks.model.User
import com.example.tasks.model.UserState
import io.github.jan.supabase.gotrue.auth
import io.github.jan.supabase.postgrest.from
import io.github.jan.supabase.storage.storage
import kotlinx.coroutines.launch

class DatabaseViewModel : ViewModel() {
    private val _userState = mutableStateOf<UserState>(UserState.Loading)
    val userState: State<UserState> = _userState
    private val _users = mutableStateOf(listOf<User>())
    val users: State<List<User>> = _users
    private val _sellers = mutableStateOf(listOf<Seller>())
    val sellers: State<List<Seller>> = _sellers
    private val _products = mutableStateOf(listOf<Product>())
    val products: State<List<Product>> = _products
    val titleImage = mutableStateOf("")

    fun profileData() {
        viewModelScope.launch {
            try {
                _userState.value = UserState.Loading
                _users.value = Constants.supabase.from("Users").select {
                    filter {
                        User::UID eq Constants.supabase.auth.currentUserOrNull()!!.id
                    }
                }.decodeList<User>()
                Log.d("my_tag", "ГУУУУД")
                _userState.value = UserState.Success("Профиль найден")

            } catch (e: Exception) {
                _userState.value = UserState.Error("Профиль не найден")
                Log.d("mu_tag", e.message!!)
            }
        }
    }

    fun profileDataSeller() {
        viewModelScope.launch {
            try {
                _userState.value = UserState.Loading
                _sellers.value = Constants.supabase.from("Sellers").select {
                    filter {
                        Seller::UID eq Constants.supabase.auth.currentUserOrNull()!!.id
                    }
                }.decodeList<Seller>()
                Log.d("my_tag", "ГУУУУД")
                _userState.value = UserState.Success("Профиль найден")

            } catch (e: Exception) {
                _userState.value = UserState.Error("Профиль не найден")
                Log.d("mu_tag", e.message!!)
            }
        }
    }

    fun addAvatar(byteArray: ByteArray) {
        viewModelScope.launch {
            try {
                titleImage.value = getRandomString(10)
                _userState.value = UserState.Loading
                val basket = Constants.supabase.storage["product"]
                basket.upload(
                    "${titleImage.value}.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("m1_tag", e.message!!)
            }
        }
    }

    fun cleanUsers() {
        viewModelScope.launch {
            try {
                _users.value = listOf()
            } catch (w: Exception) {
                println(w.message)
            }
        }
    }


    fun updateSeller(title: String, inn: String, country: String) {
        viewModelScope.launch {
            try {
                _userState.value = UserState.Loading
                Constants.supabase.from("Sellers").update(
                    {
                        Seller::title_organization setTo title
                        Seller::inn setTo inn
                        Seller::country setTo country
                    }
                ) {
                    filter {
                        Seller::UID eq Constants.supabase.auth.currentUserOrNull()!!.id
                    }
                }
                Log.d("my_tag", "ГУУУУД")
                _userState.value = UserState.Success("Данные обновлены")

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

    }

    fun allProducts() {
        viewModelScope.launch {
            try {
                _userState.value = UserState.Loading


                _products.value = Constants.supabase.from("products").select().decodeList<Product>()

                Log.d("my_tag", "ГУУУУД")
                _userState.value = UserState.Success("Выбраны все товары")

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

    fun sellerProducts() {
        viewModelScope.launch {
            try {
                _userState.value = UserState.Loading
                _sellers.value = Constants.supabase.from("Sellers").select() {
                    filter {
                        Seller::UID eq Constants.supabase.auth.currentUserOrNull()!!.id
                    }

                }.decodeList<Seller>()


                _products.value = Constants.supabase.from("products").select() {
                    filter {
                        Product::seller eq _sellers.value.last().id
                    }
                }.decodeList<Product>()

                Log.d("my_tag", "ГУУУУД")
                _userState.value = UserState.Success("Выбраны все товары")

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

    fun addProducts(title: String, description: String?, price: Double) {
        viewModelScope.launch {
            try {

                _userState.value = UserState.Loading
                _sellers.value = Constants.supabase.from("Sellers").select() {
                    filter {
                        Seller::UID eq Constants.supabase.auth.currentUserOrNull()!!.id
                    }

                }.decodeList<Seller>()
                val basket = Constants.supabase.storage["product"]

                Constants.supabase.from("products").insert(
                    Product(
                        title = title,
                        description = description,
                        price = price,
                        image = basket.publicUrl("${titleImage.value}.jpg"),
                        seller = _sellers.value.last().id!!
                    )
                )


                _userState.value = UserState.Success("The user has been successfully added")
            } catch (e: Exception) {
                _userState.value = UserState.Error(e.message!!)
                Log.d("my_tag", e.message!!)


            }
        }


    }

    fun updateCard(title: String, description: String?, price: Double, id:Int) {
        viewModelScope.launch {
            try {
                _userState.value = UserState.Loading



                Constants.supabase.from("products").update(
                    {
                        Product::title setTo title
                        Product::description setTo description
                        Product::price setTo price
                    }
                ) {
                    filter {
                        Product::id eq id
                    }
                }
                Log.d("my_tag", "ГУУУУД")
                _userState.value = UserState.Success("Данные обновлены")

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

    }

    fun updateCustomer(name: String, surname: String, patronymic: String?) {
        viewModelScope.launch {
            try {
                _userState.value = UserState.Loading

                Constants.supabase.from("Users").update(
                    {
                        User::LastName setTo surname
                        User::FirstName setTo name
                        User::Patronymic setTo patronymic
                    }
                ) {
                    filter {
                        User::UID eq Constants.supabase.auth.currentUserOrNull()!!.id
                    }
                }
                Log.d("my_tag", "ГУУУУД")
                _userState.value = UserState.Success("Данные обновлены")

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

    }
}

fun getRandomString(length: Int): String {
    val allowedChars = ('A'..'Z') + ('a'..'z') + ('0'..'9')
    return (1..length)
        .map { allowedChars.random() }
        .joinToString("")
}