package com.example.exvesta.Screans

//noinspection UsingMaterialAndMaterial3Libraries

import android.Manifest
import android.content.pm.PackageManager
import android.net.Uri
import android.util.Log
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.AlertDialog
import androidx.compose.material.Card
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.material.Divider
import androidx.compose.material.DrawerValue
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.ModalBottomSheetLayout
import androidx.compose.material.ModalBottomSheetValue
import androidx.compose.material.ModalDrawer
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material.rememberDrawerState
import androidx.compose.material.rememberModalBottomSheetState
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect

import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.content.ContextCompat
import androidx.navigation.NavHostController
import coil.compose.AsyncImagePainter
import coil.compose.rememberAsyncImagePainter
import coil.compose.rememberImagePainter
import coil.request.ImageRequest
import coil.size.Size
import com.example.exvesta.Screans.Responses.Auth
import com.example.exvesta.Screans.Responses.ResponseUser
import com.example.exvesta.domain.utils.Constants
import com.example.exvesta.model.Consists_wardrob
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
import com.example.exvesta.model.Type_subtype
import com.example.exvesta.model.Users
import com.example.exvesta.model.Wardob
import io.github.jan.supabase.gotrue.auth
import io.github.jan.supabase.postgrest.from
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

@OptIn(ExperimentalMaterialApi::class, ExperimentalLayoutApi::class)
@Composable
fun Wardrob(navHost: NavHostController) {
    var drawerState = rememberDrawerState(DrawerValue.Closed)
    var isBottomSheetVisible by remember { mutableStateOf(false) }
    val scope = rememberCoroutineScope()
    var isFiltersVisible by remember { mutableStateOf(false) }
    var filteredPublicThings by remember { mutableStateOf<List<Consists_wardrob>>(listOf()) }
    var subdubtype by remember { mutableStateOf<List<Type_subtype>>(listOf()) }
    var types by remember { mutableStateOf<List<Type>>(listOf()) }
    var season by remember { mutableStateOf<List<Season>>(listOf()) }
    var userthings by remember { mutableStateOf<List<Things_user>>(listOf()) }
    var style by remember { mutableStateOf<List<Style>>(listOf()) }
    var filtersApplied by remember { mutableStateOf(false) }
    var wardrobs by remember { mutableStateOf<List<Wardob>>(listOf()) }
    var cwardrobs by remember { mutableStateOf<List<Consists_wardrob>>(listOf()) }
    var users by remember { mutableStateOf<List<Users>>(listOf()) }
    var openDialog by remember { mutableStateOf(false) }
    var itemToDelete by remember { mutableStateOf<Things_user?>(null) }
    var newThingName by remember { mutableStateOf("") }
    var selectSeason by remember { mutableStateOf<Season?>(null) }
    var selectStyle by remember { mutableStateOf<Style?>(null) }
    var selectSubtype by remember { mutableStateOf<Type_subtype?>(null) }
    var imageUri by remember { mutableStateOf<Uri?>(null) }
    var selectwardrob by remember { mutableStateOf<Wardob?>(null) }
    val context = LocalContext.current
    val viewModel  = remember { ResponseUser(context) }
//    val userthings by viewModel.userThingsState.collectAsState() // Подписываемся на состояние

var rememberthings   by remember { mutableStateOf<List<Things_user>>(listOf()) }
    var isFilterSheetVisible by remember { mutableStateOf(false) }

    LaunchedEffect(Unit) {
        withContext(Dispatchers.IO) {
            userthings  = Constants.supabase.from("Things_user")
                .select().decodeList<Things_user>()
            rememberthings  = Constants.supabase.from("Things_user")
                .select().decodeList<Things_user>()
            wardrobs  = Constants.supabase.from("Wardob")
                .select().decodeList<Wardob>()
            cwardrobs  = Constants.supabase.from("Consists_wardrob")
                .select().decodeList<Consists_wardrob>()
            subdubtype = Constants.supabase.from("Type_subtype")
                .select().decodeList<Type_subtype>()
            types = Constants.supabase.from("Type")
                .select().decodeList<Type>()
            season = Constants.supabase.from("Season")
                .select().decodeList<Season>()
            style = Constants.supabase.from("Style")
                .select().decodeList<Style>()
            users = Constants.supabase.from("Users")
                .select().decodeList<Users>()
//            cwardrobs.forEach { it ->
//                Log.d("ts", it.toString())

            }
//          viewModel.refreshUserThings()


    }

    filteredPublicThings = cwardrobs
    val imagePickerLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.GetContent(),
        onResult = { uri: Uri? ->
            imageUri = uri
        }
    )
    val permissionLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.RequestPermission(),
        onResult = { isGranted: Boolean ->
            if (isGranted) {
                // Если разрешение предоставлено, открываем галерею
                imagePickerLauncher.launch("image/*")
            } else {
                // Обработка случая, когда разрешение не предоставлено
                Log.e("Permission", "Разрешение на чтение хранилища не предоставлено")
            }
        }
    )




    // Функция для проверки разрешений
    @Composable
    fun checkPermission() {
        when {
            ContextCompat.checkSelfPermission(LocalContext.current, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED -> {
                // Если разрешение уже предоставлено, открываем галерею
                imagePickerLauncher.launch("image/*")
            }
            else -> {
                // Запрашиваем разрешение
                permissionLauncher.launch(Manifest.permission.READ_EXTERNAL_STORAGE)
            }
        }
    }

    ModalDrawer(
        drawerState = drawerState,
        drawerContent = {
            DrawerContent(navHost)
        },
    ) {

        Column(
            modifier = Modifier
                .fillMaxSize()
                .background(Color.White)
                .padding(16.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(vertical = 16.dp),
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.Start
            ) {
                IconButton(onClick = {
                    scope.launch { drawerState.open() }
                }) {
                    Icon(imageVector = Icons.Filled.Menu, contentDescription = "Menu")
                }


                Column(){
                    Button(
                        onClick = {

                            scope.launch {  isFilterSheetVisible = true } // Закрываем drawer
                        },
                        border = BorderStroke(1.dp, Color(0xFF92A2B0)),
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(vertical = 8.dp),
                        colors = ButtonDefaults.buttonColors(Color.White)
                    ) {
                        Text(text = "+ добавить фильтр", color = Color(0xFF92A2B0))
                    }


                    Button(
                        onClick = { isBottomSheetVisible = true  },
                        border = BorderStroke(1.dp, Color(0xFF92A2B0)),
                        modifier = Modifier
                            .fillMaxWidth()
                      ,
                        colors = ButtonDefaults.buttonColors(Color.White)
                    ) {
                        Text(text = "+ добавить вещь", color = Color(0xFF92A2B0))
                    }

                }

            }



            if (filtersApplied) {
                Button(
                    onClick = {
//                        userthings = rememberthings
                        filtersApplied = false
                    },
                    border = BorderStroke(1.dp, Color(0xFF92A2B0)),
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(vertical = 8.dp),
                    colors = ButtonDefaults.buttonColors(Color(0xFFF1F1F3))
                ) {
                    Text(text = "сбросить фильтры", color = Color(0xFF92A2B0))
                }
            }
            Spacer(modifier = Modifier.height(10.dp))











            val userId = Constants.supabase.auth.currentUserOrNull()?.id
            val authorizedUser  = users.find { it.user == userId }


            if (authorizedUser  != null) {
                val userWardrobes = wardrobs.filter { it.id_user == authorizedUser.id } // Предполагается, что у вас есть поле userId в Wardob

                // Если у пользователя есть гардеробы, выбираем первый
                if (userWardrobes.isNotEmpty()) {
                    selectwardrob = userWardrobes.first() // Сохраняем первый гардероб в selectwardrob
                } else {
                    // Обработка случая, когда у пользователя нет гардеробов
                    Log.d("Wardrob", "У пользователя нет гардеробов.")
                }
                // Group items by type
                 val itemsByType = filteredPublicThings.groupBy { userthing ->
                    val thing = userthings.find { it.id == userthing.id_thing }
                    thing?.subtype?.let { subtype ->
                        subdubtype.find { it.id == subtype }?.id_type
                    }

                }

                LazyColumn(modifier = Modifier.fillMaxSize().padding(10.dp)) {
                    items(types) { type ->
                        val typeItems = itemsByType[type.id] ?: emptyList()

                        if (typeItems.isNotEmpty()) {
                            Text(
                                text = type.title_type,

                                modifier = Modifier.padding(8.dp)
                            )

                            LazyRow {
                                items(typeItems) { userthing ->
                                    val thing = userthings.find { it.id == userthing.id_thing }
                                    if (thing != null) {
                                        val imageState = rememberAsyncImagePainter(
                                            model = ImageRequest.Builder(LocalContext.current)
                                                .data(thing.img)
                                                .size(Size.ORIGINAL).build()
                                        ).state

                                        Card(
                                            modifier = Modifier
                                                .padding(8.dp)
                                                .width(330.dp)
                                                .shadow(8.dp, RoundedCornerShape(30.dp)),
                                            shape = RoundedCornerShape(30.dp),
                                            backgroundColor = Color.White
                                        ) {
                                            Column {
                                                if (imageState is AsyncImagePainter.State.Error) {
                                                    Box(
                                                        modifier = Modifier
                                                            .fillMaxWidth()
                                                            .height(250.dp),
                                                        contentAlignment = Alignment.Center
                                                    ) {
                                                        CircularProgressIndicator()
                                                    }
                                                }

                                                if (imageState is AsyncImagePainter.State.Success) {
                                                    Image(
                                                        modifier = Modifier
                                                            .fillMaxWidth()
                                                            .height(250.dp),
                                                        painter = imageState.painter,
                                                        contentDescription = "",
                                                        contentScale = ContentScale.Crop
                                                    )
                                                }

                                                Divider(
                                                    modifier = Modifier.padding(vertical = 8.dp),
                                                    color = Color.LightGray,
                                                    thickness = 1.dp
                                                )

                                                Text(
                                                    "Название: ${thing.title}",
                                                    fontSize = 18.sp,
                                                    modifier = Modifier.padding(start = 8.dp),
                                                    color = Color(0xFF92A2B0)
                                                )

                                                // Display categories
                                                val seasonid = thing.id_season
                                                val seasonItem = season.find { it.id == seasonid }
                                                val styleid = thing.style
                                                val styleItem = style.find { it.id == styleid }
                                                val subtypeid = thing.subtype
                                                val subtypeItem =
                                                    subdubtype.find { it.id == subtypeid }

                                                if (subtypeItem != null) {
                                                    val typeid = subtypeItem.id_type
                                                    val typeItem = types.find { it.id == typeid }
                                                    if (seasonItem != null && styleItem != null && typeItem != null) {
                                                        Text(
                                                            "Категории: ${styleItem.title_style}, ${typeItem.title_type}, ${subtypeItem.sub_type}, ${seasonItem.title_season}",
                                                            fontSize = 18.sp,
                                                            modifier = Modifier.padding(start = 8.dp),
                                                            color = Color(0xFF92A2B0)
                                                        )
                                                    }
                                                }


                                                Button(
                                                    onClick = {
                                                        itemToDelete = thing
                                                        openDialog = true
                                                    },
                                                    modifier = Modifier
                                                        .padding(8.dp)
                                                        .align(Alignment.CenterHorizontally),
                                                        colors = ButtonDefaults.buttonColors(
                                                            Color(0xFF6F4A48),
                                                    contentColor = Color.White
                                                ),
                                                shape = ButtonDefaults.shape
                                                ) {


                                                    Text("Удалить")
                                                }






                                            }
                                        }

                                    }

                                }

                            }


                        }
                    }

                }
                if (itemToDelete != null) {
                    DeleteConfirmationDialog(
                        openDialog = openDialog,
                        userthing = itemToDelete!!, // Уверены, что itemToDelete не null
                        onConfirm = { item ->
                            item?.let {

                                    viewModel.deleteItem(it, status = itemToDelete!!.public_status!!) // Вызов функции удаления из ViewModel

                            }
                            openDialog = false // Закрыть диалог
                            itemToDelete = null // Сбросить элемент после удаления
                        },
                        onDismiss = {
                            openDialog = false // Закрыть диалог при отмене
                            itemToDelete = null // Сбросить элемент после закрытия диалога
                        },
                        navHost
                    )
                }
            }

        }
        if (isBottomSheetVisible) {
            ModalBottomSheetLayout(
                sheetState = rememberModalBottomSheetState(ModalBottomSheetValue.Expanded),
                sheetContent = {
                    Column(   modifier = Modifier
                        .fillMaxHeight()
                        .fillMaxWidth()
                        .background(
                            Brush.verticalGradient(
                                colors = listOf(
                                    Color(0xFFF4F4F4),
                                    Color(0xFFE7D2A9),
                                    Color(0xFFC1A88B),
                                    Color(0xFF6F4A48)
                                )
                            )
                        )) {
                        Spacer(modifier = Modifier.height(50.dp))
                        Box(
                            modifier = Modifier
                                .fillMaxWidth() // Бокс на всю ширину
                                .padding(start = 16.dp, end = 16.dp)
                                .background(
                                    color = Color.White,
                                    shape = RoundedCornerShape(16.dp) // Закругленные края
                                )
                                .padding(16.dp) // Отступы внутри бокса
                        ) {

                            // Отображение выбранного изображения


                            LazyColumn(horizontalAlignment = Alignment.CenterHorizontally) {
                                item {
                                    Text("Добавить новую вещь", fontWeight = FontWeight.Bold)

                                                                // Поле для ввода названия вещи
                                                           OutlinedTextField(
                                                                    value = newThingName,
                                                                    onValueChange = { newThingName = it },
                                                                    label = { Text("Название вещи") },
                                                                    modifier = Modifier.fillMaxWidth()
                                                                    ,
                                                                    colors = TextFieldDefaults.colors(
                                                                        unfocusedContainerColor =  Color(0xFFFEFAF3),
                                                                        focusedContainerColor = Color(0xFFFFFFFF),
                                                                        unfocusedIndicatorColor = Color(0xFFB9A791),
                                                                        focusedIndicatorColor = Color(0xFFA18B72),
                                                                    )
                                                                )

                                                                // Выбор изображения
                                                                Button(onClick = {
                                                                    imagePickerLauncher.launch("image/*")
                                                              },         colors = ButtonDefaults.buttonColors(
                                                                        Color(0xFF6F4A48),
                                                                    contentColor = Color.White
                                                                ),
                                                                    modifier = Modifier
                                                                   .fillMaxWidth(),
                                                                    shape = ButtonDefaults.shape) {
                                                                    Text("Выбрать изображение")
                                                                }
                                                                imageUri?.let {
                                                                    Image(
                                                                        painter = rememberImagePainter(it),
                                                                        contentDescription = "Выбранное изображение",
                                                                        modifier = Modifier
                                                                            .fillMaxWidth()
                                                                            .height(200.dp)
                                                                            .clip(RoundedCornerShape(8.dp))
                                                                            .padding(vertical = 8.dp)
                                                                    )
                                                                }
                                    Spacer(modifier = Modifier.height(10.dp))
                                    Text(
                                        text = "Фильтры",
                                        fontSize = 16.sp,
                                        fontWeight = FontWeight.Medium,
                                        color = Color(0xFF92A2B0)
                                    )
                                    androidx.compose.material3.Divider(
                                        modifier = Modifier.padding(vertical = 8.dp),
                                        color = Color.LightGray,
                                        thickness = 1.dp
                                    )


                                    Spacer(modifier = Modifier.height(10.dp)) // Отступ между текстом и кнопкой

                                    // Текст "Сезон"
                                    Box(

                                        modifier = Modifier
//                                .align(Alignment.Start)
                                            .fillMaxWidth()
                                    ) {
                                        Text("Сезон")


                                        FlowRow(
                                            modifier = Modifier
                                                .fillMaxWidth()
                                                .padding(10.dp)
                                        ) {
                                            season.forEach { seasondub ->
                                                Row(
                                                    verticalAlignment = Alignment.CenterVertically,
                                                    modifier = Modifier
                                                        .padding(4.dp) // Отступы между элементами
                                                        .selectable(
                                                            selected = (seasondub == selectSeason),
                                                            onClick = { selectSeason = seasondub }
                                                        )
                                                ) {
                                                    androidx.compose.material3.RadioButton(
                                                        selected = (seasondub == selectSeason),
                                                        onClick = { selectSeason = seasondub }
                                                    )
                                                    Text(
                                                        text = seasondub.title_season,
                                                        fontSize = 16.sp,
                                                        modifier = Modifier.padding(start = 8.dp),
                                                        color = Color(0xFF92A2B0)
                                                    )
                                                }
                                            }
                                        }
                                    }
                                    Spacer(modifier = Modifier.height(10.dp))
                                    Box(

                                        modifier = Modifier
//                                .align(Alignment.Start)
                                            .fillMaxWidth()

                                    ) {
                                        Text("Стиль")
                                    }
                                    Box(

                                        modifier = Modifier
//                                .align(Alignment.Start)
                                            .fillMaxWidth()
                                            .padding(10.dp)
                                    ) {
                                        FlowRow(
                                            modifier = Modifier
                                                .fillMaxWidth()
                                                .padding(10.dp)
                                        ) {
                                            style.forEach { styledub ->
                                                Box(
                                                    modifier = Modifier
                                                        .padding(4.dp) // Отступы между элементами
                                                        .background(
                                                            Color(0xFFF1F1F3),
                                                            shape = RoundedCornerShape(20.dp)
                                                        )
                                                        .width(145.dp)// Задаем одинаковую ширину для всех элементов
                                                        .height(38.dp) // Устанавливаем фиксированную высоту для всех элементов
                                                ) {
                                                    Row(
                                                        verticalAlignment = Alignment.CenterVertically,
                                                        modifier = Modifier

                                                            .selectable(
                                                                selected = (styledub == selectStyle),
                                                                onClick = { selectStyle = styledub }
                                                            )
                                                    ) {
                                                        androidx.compose.material3.RadioButton(
                                                            selected = (styledub == selectStyle),
                                                            onClick = { selectStyle = styledub }
                                                        )
                                                        Text(
                                                            text = styledub.title_style,
                                                            fontSize = 16.sp,
                                                            modifier = Modifier.padding(start = 0.dp), // Отступ слева от радиокнопки
                                                            color = Color(0xFF92A2B0)
                                                        )
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    Box(

                                        modifier = Modifier
//                                .align(Alignment.Start)
                                            .fillMaxWidth()

                                    ) {
                                        Text("Типы")
                                    }

                                    FlowRow(
                                        modifier = Modifier
                                            .fillMaxWidth()
                                            .padding(10.dp)
                                    )
                                    {
                                        types.forEach { typedub ->

                                            Box(
                                                modifier = Modifier
                                                    .padding(4.dp) // Отступы между элементами
                                                    .background(
                                                        Color(0xFFF1F1F3),
                                                        shape = RoundedCornerShape(20.dp)
                                                    )
                                                    .width(145.dp)// Задаем одинаковую ширину для всех элементов
                                                    .height(245.dp) // Устанавливаем фиксированную высоту для всех элементов
                                            ) {

                                                Text(text = typedub.title_type)



                                                LazyColumn {
                                                    items(
                                                        subdubtype,
                                                        key = { subdubtype -> subdubtype.id },
                                                    ) { subtypedub ->
                                                        if (subtypedub.id_type == typedub.id) {
                                                            Row(
                                                                verticalAlignment = Alignment.CenterVertically,
                                                                modifier = Modifier

                                                                    .selectable(
                                                                        selected = (subtypedub ==  selectSubtype),
                                                                        onClick = { selectSubtype = subtypedub }
                                                                    )
                                                                    .padding(top = 14.dp)



                                                            ) {
                                                                androidx.compose.material3.RadioButton(
                                                                    selected = (subtypedub == selectSubtype),
                                                                    onClick = {
                                                                        selectSubtype = subtypedub
                                                                    }
                                                                )
                                                                Text(
                                                                    text = subtypedub.sub_type,
                                                                    fontSize = 16.sp,
                                                                    modifier = Modifier.padding(start = 0.dp), // Отступ слева от радиокнопки
                                                                    color = Color(0xFF92A2B0)

                                                                )
                                                            }
                                                        }

                                                    }

                                                }


                                            }

                                        }



                                    }
                                    Column(
                                        modifier = Modifier
                                            .fillMaxWidth()
                                            .padding(bottom = 50.dp), // Отступ внизу для всего столбца
                                        verticalArrangement = Arrangement.Bottom // Располагаем кнопки внизу
                                    ) {
                                        Button(
                                            onClick = {
                                                viewModel.insertItem(
                                                    season = selectSeason?.id ?: 0,
                                                    styles = selectStyle?.id ?: 0,
                                                    title = newThingName,
                                                    subtype = selectSubtype?.id ?: 0,
                                                    imgUri = imageUri,
                                                    idWardrob = selectwardrob?.id ?: 0,
                                                )
                                                // Закрываем панель
                                                navHost.navigate("Wardrob")
                                            },
                                            modifier = Modifier
                                                .fillMaxWidth()
                                                .height(50.dp)
                                                .padding(horizontal = 20.dp)
                                                .background(
                                                    brush = Brush.horizontalGradient(
                                                        colors = listOf(
                                                            Color(0xFF6F4A48),
                                                            Color(0xFFE7D2A9),
                                                        )
                                                    ),
                                                    shape = ButtonDefaults.shape
                                                ),
                                            colors = ButtonDefaults.buttonColors(containerColor = Color.Transparent),
                                        ) {
                                            Text("Добавить")
                                        }

                                        Spacer(modifier = Modifier.height(10.dp)) // Отступ между кнопками


                                    }
                                }

                            }








                        }
                    }
                },
                content = {

                },

                )

        }
    }
    if (isFilterSheetVisible) {
        Column {
            FiltersUser(
                onApplyFilter = { selectedSubtype, selectedSeason, selectedStyle ->
                    // Получаем текущего авторизованного пользователя
                    val userId = Constants.supabase.auth.currentUserOrNull()?.id
                    val authorizedUser  = users.find { it.user == userId }

                    if (authorizedUser  != null) {

                        userthings = userthings.filter { userthing ->
                            (selectedSubtype == null || userthing.subtype == selectedSubtype.id) &&
                                    (selectedSeason == null || userthing.id_season == selectedSeason.id) &&
                                    (selectedStyle == null || userthing.style == selectedStyle.id)
                        }


                    }

                    isFilterSheetVisible = false // Закрываем окно фильтров
                    filtersApplied = true
                },
                onDismiss = { isFilterSheetVisible = false }
            )
        }
    }



}
@Composable
fun FilterAndSortThings(
    userthings: List<Things_user>,
    newThingName: String,
    selectSeason: Season?,
    selectStyle: Style?,
    selectSubtype: Type_subtype?,
    onResult: (List<Things_user>) -> Unit
) {
    val filteredSortedThings = userthings
        .filter { thing ->
            // Фильтрация по имени
            newThingName.isEmpty() || thing.title.contains(newThingName, ignoreCase = true)
        }
        .filter { thing ->
            // Фильтрация по сезону
            selectSeason == null || thing.id_season == selectSeason?.id
        }
        .filter { thing ->
            // Фильтрация по стилю
            selectStyle == null || thing.style == selectStyle?.id
        }
        .filter { thing ->
            // Фильтрация по подтипу
            selectSubtype == null || thing.subtype == selectSubtype?.id
        }
        .sortedWith(compareBy(
            { it.title },         // Сортировка по названию
            { it.id_season },    // Затем по сезону
            { it.style },        // Затем по стилю
            { it.subtype }       // И затем по подтипу
        ))

    // Возвращаем результат через callback
    onResult(filteredSortedThings)
}
@Composable
fun DeleteConfirmationDialog(
    openDialog: Boolean,
    userthing: Things_user,
    onConfirm: (Things_user) -> Unit,
    onDismiss: () -> Unit,
    navHost: NavHostController
) {
    val context = LocalContext.current
    val viewModel  = remember { ResponseUser(context) }
    if (openDialog) {
        AlertDialog(
            onDismissRequest = onDismiss,
            title = {
                Text(text = "Подтверждение удаления")
            },
            text = {
                Text("Вы уверены, что хотите удалить эту вещь?")
            },
            confirmButton = {
                Button(onClick = {
                    onConfirm(userthing) // Вызов функции для удаления элемента
                    onDismiss() // Закрыть диалог после подтверждения

                    navHost.navigate("Wardrob")
                },
                    colors = ButtonDefaults.buttonColors(
                        Color(0xFF8BC34A),
                        contentColor = Color.White
                    ),
                    shape = ButtonDefaults.shape
                ) {
                    Text("Да")
                }
            },
            dismissButton = {
                Button(onClick = onDismiss,
                    colors = ButtonDefaults.buttonColors(
                        Color(0xFFF44336),
                        contentColor = Color.White
                    ),
                    shape = ButtonDefaults.shape) {
                    Text("Нет")
                }
            }
        )
    }
}


