package com.example.development.mainActivity

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.util.Log
import androidx.compose.runtime.State
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.development.domain.utils.Constants
import com.example.development.model.User
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 kotlinx.coroutines.launch
import kotlinx.datetime.LocalDate
import java.io.ByteArrayOutputStream
import java.text.SimpleDateFormat
import java.time.format.DateTimeFormatter
import java.util.Date

class MainViewModel():ViewModel() {
    private val _users = mutableStateOf(listOf<User>())
    val users: State<List<User>> = _users
    val titleImage = mutableStateOf("")

    fun onSignInEmailCode(emailUser: String) {
        viewModelScope.launch {
            try {
                Constants.supabase.auth.signInWith(OTP) {
                    email = emailUser
                    createUser = false
                }
            } catch (e: Exception) {
                println(e.message.toString())
            }
        }
    }

    fun onSignInEmailPassword(emailUser: String, passwordUser: String) {
        viewModelScope.launch {
            try {
                val user = Constants.supabase.auth.signInWith(Email) {
                    email = emailUser
                    password = passwordUser
                }
                println(user.toString())
                println(Constants.supabase.auth.currentUserOrNull()!!.id)
                println("Success")
                FindUser()
            } catch (e: Exception) {
                println("Error")
                println(e.message.toString())
            }
        }
    }

    fun onSignUpEmail(emailUser: String, passwordUser: String) {
        viewModelScope.launch {
            try {
                var user = Constants.supabase.auth.signUpWith(Email) {
                    email = emailUser
                    password = passwordUser
                }
                println(user.toString())
                println(Constants.supabase.auth.currentUserOrNull()!!.id)
                println("Success")
            } catch (e: Exception) {
                println("Error")
                println(e.message.toString())
            }

        }
    }

    fun FindUser() {
        viewModelScope.launch {
            try {
                _users.value = Constants.supabase.from("users").select {
                    filter {
                        User::UID eq Constants.supabase.auth.currentUserOrNull()!!.id
                    }
                }.decodeList<User>()
                var result = "Пользователь найден"
                println(result)
            } catch (e: Exception) {
                println("Пользователь не найден")
                println(e.message.toString())
            }
        }
    }

    fun CreateUser(
        firstName: String,
        secondName: String,
        phoneNumber: String
    ) {
        viewModelScope.launch {
            try {
                Constants.supabase.from("users").insert(
                    User(
                        role = 1,
                        firstName = firstName,
                        secondName = secondName,
                        email = Constants.supabase.auth.currentUserOrNull()!!.email.toString(),
                        phoneNumber = phoneNumber,
                        image = "",
                        UID = Constants.supabase.auth.currentUserOrNull()!!.id
                    )
                )
                println("Success")
            } catch (e: Exception) {
                println("Error")
                println(e.message.toString())
            }
        }
    }

    fun UpdatePersonalData(
        firstName: String,
        secondName: String,
        email: String,
        phoneNumber: String,
        image: String
    ) {
        viewModelScope.launch {
            try {
                Constants.supabase.from("users").update(
                    {
                        User::firstName setTo firstName
                        User::secondName setTo secondName
                        User::email setTo email
                        User::phoneNumber setTo phoneNumber
                    }
                )
            } catch (e: Exception) {

            }
        }
    }

    fun checkForRegistration() {
        viewModelScope.launch {
            try {
                var flag = false
                _users.value = Constants.supabase.from("Users")
                    .select() {
                        filter {
                            User::UID eq Constants.supabase.auth.currentUserOrNull()!!.id
                        }
                    }.decodeList<User>()
                flag = true
                println("Пользователь найден")
            } catch (e: Exception) {
                var flag = false
                println("Error")
                println(e.message.toString())
            }
        }
    }

    fun upadatePassword(pass: String) {
        viewModelScope.launch {
            try {
                Constants.supabase.auth.updateUser { password = pass }
                println("Success")
            } catch (e: Exception) {
                println("Error")
                println(e.message.toString())
            }
        }
    }

    fun addAvatar(byteArray: ByteArray) {
        viewModelScope.launch {
            try {
                titleImage.value = getRandomString(10)
                val basket = Constants.supabase.storage["image of users"]
                basket.upload(
                    "${Constants.supabase.auth.currentUserOrNull()!!.email}.jpg",
                    byteArray,
                    true
                )
                println("Картинка успешно добавлена")
            } catch (e: Exception) {
                println("Картинка не добавлена")
                println(e.message.toString())
            }
        }
    }

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

    fun logout(context: Context) {
        viewModelScope.launch {
            try {
                Constants.supabase.auth.signOut()
                println("Пользователь успешно вышел из аккаунта")
            }
            catch (e: Exception) {
                println("Ошибка при выходе из аккаунта")
                println(e.message.toString())
            }
        }
    }

    fun bitmapToByteArray(context: Context, uri: Uri): ByteArray {
        val inputStream = context.contentResolver.openInputStream(uri)
        val bitmap = BitmapFactory.decodeStream(inputStream)
        val baos = ByteArrayOutputStream()
        bitmap.compress(Bitmap.CompressFormat.JPEG, 50, baos)
        return baos.toByteArray()
    }

}