package com.example.exvesta.Screans

import android.content.Intent
import android.net.Uri
import android.provider.MediaStore
import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.core.app.ActivityCompat.startActivityForResult
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.navigation.NavController
import androidx.navigation.NavHostController

import com.example.exvesta.domain.utils.Constants
import com.example.exvesta.domain.utils.Constants.supabase
import com.example.exvesta.model.Consists_wardrob
import com.example.exvesta.model.Publicthings
import com.example.exvesta.model.Season
import com.example.exvesta.model.Style
import com.example.exvesta.model.Things_user
import com.example.exvesta.model.Type_subtype
import io.github.jan.supabase.gotrue.providers.builtin.OTP
import kotlinx.coroutines.launch

import android.content.Context
import androidx.compose.foundation.layout.Column
import androidx.compose.runtime.mutableStateListOf
import io.github.jan.supabase.gotrue.auth
import io.github.jan.supabase.gotrue.providers.builtin.Email
import io.github.jan.supabase.postgrest.from
import io.github.jan.supabase.storage.storage
import okhttp3.MediaType
import okhttp3.OkHttpClient
import okhttp3.RequestBody

import androidx.core.content.ContextCompat
import io.github.jan.supabase.postgrest.query.Columns
import io.github.jan.supabase.postgrest.query.Order
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow

import okhttp3.*
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import java.io.File
import java.sql.DriverManager
import java.sql.PreparedStatement


class  Auth(private val context: Context): ViewModel() {
    private val _userThingsState = MutableStateFlow<List<Things_user>>(listOf())
    val userThingsState: StateFlow<List<Things_user>> = _userThingsState
    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, navHost: NavHostController) {
        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")
                navHost.navigate("Home")
            } 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 deleteItem(userthing: Things_user) {
        var response: List<Things_user>
        response = ArrayList()
        viewModelScope.launch {

            try {
                Constants.supabase.from("Things_user").delete {

                    filter {
                        Things_user::id eq userthing.id
                    }
                }

            } catch (e: Exception) {
                println("Error")
                println(e.message.toString())
            }
        }

    }

    fun insertItem(season: Int, styles: Int, title: String, subtype: Int, imgUri: Uri?) {
        viewModelScope.launch {
            try {
                imgUri?.let { imageUri ->
                    val inputStream = context.contentResolver.openInputStream(imageUri)
                    inputStream?.use { stream ->
                        val byteArray =
                            stream.readBytes() // Читаем содержимое файла в массив байтов
                        val bucket =
                            Constants.supabase.storage.from("exvesta") // Укажите имя вашего бакета

                        val fileName = imageUri.lastPathSegment
                            ?: "default_image_name.jpg" // Получаем имя файла из Uri
                        val imageUrl =
                            "https://vkxcxcimqqswxqxncmof.supabase.co/storage/v1/object/public/exvesta/$fileName"

                        // Загружаем файл в бакет
                        val uploadResponse =
                            bucket.upload(fileName, byteArray) // Используем имя файла
                        Log.d("UploadResponse", uploadResponse.toString())

                        // Создаем объект Things_user
                        val thing = Things_user(
                            id = null,
                            style = styles,
                            title = title,
                            subtype = subtype,
                            img = imageUrl,
                            id_season = season,
                            no = false,
                            public_status = false
                        )

                        // Вставка элемента в базу данных
                        val insertResponse = Constants.supabase.from("Things_user").insert(thing)
                        Log.d("InsertResponse1", insertResponse.toString())

                    }


                }
                refreshUserThings()
            } catch (e: Exception) {
                println("Error during insertion: ${e.message}")
            }
        }
    }

    fun refreshUserThings() {
        viewModelScope.launch {
            try {
                val refreshedThings = Constants.supabase.from("Things_user")
                    .select()
                    .decodeList<Things_user>()
                // Здесь вы можете использовать LiveData или StateFlow, чтобы обновить UI
                // Например, если вы используете StateFlow:
                _userThingsState.value = refreshedThings
            } catch (e: Exception) {
                println("Error refreshing user things: ${e.message}")
            }
        }
    }

    fun addc(
        idWardrob: Int,
        firstId: Int
    ) {

        Log.d("firstId", firstId.toString())
        viewModelScope.launch {
            try {

                val conw = Consists_wardrob(
                    id = null,
                    id_thing = firstId,
                    id_wardrob = idWardrob
                )
                val insertRespons = Constants.supabase.from("Consists_wardrob").insert(conw)
                refreshUserThings()
            } catch (e: Exception) {
                println("Error during insertion: ${e.message}")
            }
        }
    }
    private var _filteredSortedThings = mutableStateListOf<Things_user>()
    val filteredSortedThings: List<Things_user> get() = _filteredSortedThings

    fun FilterAndSortThings(  userthings: List<Things_user>,   newThingName: String,){
        _filteredSortedThings.clear()
       _filteredSortedThings.addAll(
           userthings
               .filter { thing ->
                   // Фильтрация по имени
                   newThingName.isEmpty() || thing.title.contains(newThingName, ignoreCase = true)
               }
       )
     }
}