package com.example.exvesta.Screans

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.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
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.layout.wrapContentSize
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.DrawerValue
import androidx.compose.material.DropdownMenu
import androidx.compose.material.DropdownMenuItem
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
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.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Divider
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.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.domain.utils.Constants
import com.example.exvesta.model.Bows
import com.example.exvesta.model.Consists_bows
import com.example.exvesta.model.Publicthings
import com.example.exvesta.model.Season_dublicate
import com.example.exvesta.model.Style_dublicate
import com.example.exvesta.model.Things_user
import com.example.exvesta.model.Type_dublicate
import com.example.exvesta.model.Type_subtype_dublicate
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
import androidx.compose.material3.OutlinedTextField
import com.example.exvesta.Screans.Responses.Auth
import com.example.exvesta.Screans.Responses.ResponseUser

@Composable
fun MyBows(navHost: NavHostController) {
    var subdubtype by remember { mutableStateOf<List<Type_subtype_dublicate>>(listOf()) }
    var dubtype by remember { mutableStateOf<List<Type_dublicate>>(listOf()) }
    var bows by remember { mutableStateOf<List<Bows>>(listOf()) }
    var conbows by remember { mutableStateOf<List<Consists_bows>>(listOf()) }
    var seasondub by remember { mutableStateOf<List<Season_dublicate>>(listOf()) }
    var publicthings by remember { mutableStateOf<List<Publicthings>>(listOf()) }
    var styledub by remember { mutableStateOf<List<Style_dublicate>>(listOf()) }
    var filteredPublicThings by remember { mutableStateOf<List<Publicthings>>(listOf()) }
    var selectedBow by remember { mutableStateOf<Bows?>(null) }
    var users by remember { mutableStateOf<List<Users>>(listOf()) }
    var showDialog by remember { mutableStateOf(false) }
    var showadd by remember { mutableStateOf(false) }
    var userthings by remember { mutableStateOf<List<Things_user>>(listOf()) }
    var itemToDelete by remember { mutableStateOf<Bows?>(null) }
    var openDialog by remember { mutableStateOf(false) }
    LaunchedEffect(Unit) {
        withContext(Dispatchers.IO) {
            userthings  = Constants.supabase.from("Things_user")
                .select().decodeList<Things_user>()
            publicthings = Constants.supabase.from("Publicthings")
                .select().decodeList<Publicthings>()
            bows  = Constants.supabase.from("Bows")
                .select().decodeList<Bows>()
            conbows  = Constants.supabase.from("Consists_bows")
                .select().decodeList<Consists_bows>()
            subdubtype = Constants.supabase.from("Type_subtype_dublicate")
                .select().decodeList<Type_subtype_dublicate>()
            dubtype = Constants.supabase.from("Type_dublicate")
                .select().decodeList<Type_dublicate>()
            seasondub = Constants.supabase.from("Season_dublicate")
                .select().decodeList<Season_dublicate>()
            styledub = Constants.supabase.from("Style_dublicate")
                .select().decodeList<Style_dublicate>()
            publicthings.forEach { it ->
                Log.d("ts", it.title)
                users = Constants.supabase.from("Users")
                    .select().decodeList<Users>()
            }
        }
        filteredPublicThings = publicthings

    }
    var filtersApplied by remember { mutableStateOf(false) }
    var isFilterSheetVisible by remember { mutableStateOf(false) }
    var drawerState = rememberDrawerState(DrawerValue.Closed)
    val scope = rememberCoroutineScope()
    val context = LocalContext.current
    val viewModel = remember { ResponseUser(context) }
    ModalDrawer(
        drawerState = drawerState,
        drawerContent = {
            DrawerContent(navHost)

        },
    ) {
        Column(
            modifier = Modifier

                .fillMaxSize()
                .background(Color.White)
                .padding(16.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Spacer(modifier = Modifier.height(20.dp))
            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")
                }

                Button(
                    onClick = {showadd = true

                    },
                    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))




            Spacer(modifier = Modifier.height(10.dp))
            val userId = Constants.supabase.auth.currentUserOrNull()?.id
            val authorizedUser  = users.find { it.user == userId }


            if (authorizedUser  != null) {
                LazyColumn(

                    modifier = Modifier
                        .fillMaxSize(1f)
                        .padding(10.dp)
                ) {

                    items(
                        bows
                    ) { bow ->
                        val iconb = bow.id
                        val cobow = conbows.filter { it.id_bow == bow.id }
                        if (cobow != null && bow.id_user ==authorizedUser.id) {
                            val imageState = rememberAsyncImagePainter(
                                model = ImageRequest.Builder(LocalContext.current).data(bow.img)
                                    .size(Size.ORIGINAL).build()
                            ).state

                            Box(
                                modifier = Modifier
                                    .shadow(8.dp, RoundedCornerShape(30.dp))
                            ) {
                                Box(
                                    modifier = Modifier
                                        .background(

                                            Color.White,

                                            shape = RoundedCornerShape(30.dp)
                                        )
                                        .padding(8.dp)
                                        .wrapContentSize(Alignment.Center)

                                ) {

                                    Column(
                                    )
                                    {
                                        if (imageState is AsyncImagePainter.State.Error) {
                                            Box(
                                                modifier = Modifier
                                                    .fillMaxWidth()

                                                    .height(250.dp),
                                                contentAlignment = Alignment.Center
                                            ) {
                                                LazyRow {
                                                    items(cobow) { conbo ->
                                                        val thingid = conbo.id_components
                                                        val thing =
                                                            userthings.find { it.id == thingid }
                                                        if (thing != null) {

                                                            val imageState =
                                                                rememberAsyncImagePainter(
                                                                    model = ImageRequest.Builder(
                                                                        LocalContext.current
                                                                    )
                                                                        .data(thing.img)
                                                                        .size(Size.ORIGINAL).build()
                                                                ).state
                                                            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)
//                                    .clip(RoundedCornerShape(8.dp))
                                                                    ,
                                                                    painter = imageState.painter,
                                                                    contentDescription = "",
                                                                    contentScale = ContentScale.Crop


                                                                )
                                                            }


                                                        }
                                                    }
                                                }
                                            }
                                        }

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


                                            )
                                        }
                                        Divider(
                                            modifier = Modifier.padding(vertical = 8.dp),
                                            color = Color.LightGray,
                                            thickness = 1.dp
                                        )
                                        Spacer(modifier = Modifier.height(8.dp))
                                        Text(
                                            "Название: ${bow.title_bow}",
                                            fontSize = 18.sp,
                                            modifier = Modifier.padding(start = 8.dp),
                                            color = Color(0xFF92A2B0)
                                        )


                                        Spacer(modifier = Modifier.height(8.dp))
                                        Row(
                                            modifier = Modifier
                                                .fillMaxWidth()
                                                .padding(horizontal = 16.dp), // Добавляем отступы по горизонтали
                                            horizontalArrangement = Arrangement.Center // Центрируем содержимое по горизонтали
                                        ) {
                                            Column(
                                                horizontalAlignment = Alignment.CenterHorizontally // Центрируем содержимое по вертикали
                                            ) {
                                                Button(
                                                    onClick = {
                                                        selectedBow = bow
                                                        showDialog = true // Показываем диалог
                                                    },
                                                    modifier = Modifier
                                                        .width(200.dp)
                                                        .height(40.dp),
                                                    colors = ButtonDefaults.buttonColors(
                                                        Color(0xFF6F4A48),
                                                        contentColor = Color.White
                                                    ),
                                                    shape = ButtonDefaults.shape
                                                ) {
                                                    Text(
                                                        text = "подробности",
                                                        fontSize = 16.sp,
                                                        fontWeight = FontWeight.Medium
                                                    )
                                                }

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

                                                Button(
                                                    onClick = {
                                                        itemToDelete = bow
                                                        openDialog = true
                                                    },
                                                    modifier = Modifier
                                                        .width(200.dp)
                                                        .height(40.dp),
                                                    colors = ButtonDefaults.buttonColors(
                                                        Color(0xFF6F4A48), // Цвет фона кнопки удалить
                                                        contentColor = Color.White
                                                    ),
                                                    shape = ButtonDefaults.shape
                                                ) {
                                                    Text(
                                                        text = "удалить",
                                                        fontSize = 16.sp,
                                                        fontWeight = FontWeight.Medium
                                                    )
                                                }
                                            }
                                        }

                                    }

                                }

                                Spacer(modifier = Modifier.height(16.dp))


                            }
                            Spacer(modifier = Modifier.height(20.dp))
                        }

                    }

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

                                viewModel.deleteBow(it) // Вызов функции удаления из ViewModel

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

        }

    }
    if (isFilterSheetVisible) {
        Column {
            Filters(
                onApplyFilters = { selectedSubtype, selectedSeason, selectedStyle ->
                    // Применяем фильтры и обновляем отображение
                    filteredPublicThings = publicthings.filter { publicThing ->
                        (selectedSubtype == null || publicThing.id_subtype == selectedSubtype.id) &&
                                (selectedSeason == null || publicThing.seson_id == selectedSeason.id)&&
                                (selectedStyle == null || publicThing.id_style == selectedStyle.id)
                    }

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

        }
    }
    if (showDialog && selectedBow != null) {
        ThingListScreen(bow = selectedBow!!, things=userthings , conb = conbows, onDismiss = { showDialog = false })
    }
    if (showadd) {
        AddBow(  things=userthings, onDismiss = { showadd = false })
    }
}



@Composable
public fun ThingListScreen(bow: Bows, things: List<Things_user>, conb: List<Consists_bows>, onDismiss: () -> Unit) {
    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(
                Brush.verticalGradient(
                    colors = listOf(
                        Color(0xFFF4F4F4),
                        Color(0xFFE7D2A9),
                        Color(0xFFC1A88B),
                        Color(0xFF6F4A48)
                    )
                )
            )
    ) {
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(bottom = 90.dp), // Отступ снизу для кнопки
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Spacer(modifier = Modifier.height(50.dp))

            LazyColumn(modifier = Modifier.padding(16.dp)) {
                val cobow = conb.filter { it.id_bow == bow.id }
                if (cobow != null) {
                    items(cobow) { conbo ->
                        Box(
                            modifier = Modifier
                                .shadow(8.dp, RoundedCornerShape(30.dp))
                        ) {
                            Box(
                                modifier = Modifier
                                    .background(
                                        Color.White,
                                        shape = RoundedCornerShape(30.dp)
                                    )
                                    .padding(8.dp)
                                    .wrapContentSize(Alignment.Center)
                            ) {
                                Column {
                                    val thingid = conbo.id_components
                                    val thing = things.find { it.id == thingid }
                                    if (thing != null) {
                                        if (thing.id == conbo.id_components) {
                                            val imageState = rememberAsyncImagePainter(
                                                model = ImageRequest.Builder(LocalContext.current)
                                                    .data(thing.img)
                                                    .size(Size.ORIGINAL).build()
                                            ).state
                                            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
                                            )
                                            Spacer(modifier = Modifier.height(8.dp))
                                            Text(
                                                "Название: ${thing.title}",
                                                fontSize = 18.sp,
                                                modifier = Modifier.padding(start = 8.dp),
                                                color = Color(0xFF92A2B0)
                                            )
                                        }
                                    }
                                }
                            }
                        }
                        Spacer(modifier = Modifier.height(16.dp))
                    }
                }
            }

        }

        // Кнопка "Закрыть" внизу экрана
        Box(
            modifier = Modifier
                .align(Alignment.BottomCenter)
                .padding(16.dp)
                .padding(bottom = 40.dp)
        ) {
            Button(
                onClick = onDismiss,
                colors = ButtonDefaults.buttonColors(
                    Color(0xFFD05656),
                    contentColor = Color.White
                ),
                shape = ButtonDefaults.shape
            ) {
                Text(
                    text = "Закрыть",
                    fontSize = 16.sp,
                    fontWeight = FontWeight.Medium
                )
            }
        }
    }
}
@Composable
public fun AddBow(things: List<Things_user>, onDismiss: () -> Unit) {
    var expanded3 by remember { mutableStateOf(false) }
    var expanded1 by remember { mutableStateOf(false) }
    var expanded2 by remember { mutableStateOf(false) }
    var public by remember { mutableStateOf(false) }
    var newThingName by remember { mutableStateOf("") }
    var selectedThingId1 by remember { mutableStateOf<Things_user?>(null) }
    var selectedThingId2 by remember { mutableStateOf<Things_user?>(null) }
    var selectedThingId3 by remember { mutableStateOf<Things_user?>(null) }
    var newThingName1 by remember { mutableStateOf("") }
    var newThingName2 by remember { mutableStateOf("") }
    var newThingName3 by remember { mutableStateOf("") }
    var imageUri by remember { mutableStateOf<Uri?>(null) }
    val imagePickerLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.GetContent(),
        onResult = { uri: Uri? ->
            imageUri = uri
        }
    )
    var selectwardrob by remember { mutableStateOf<Wardob?>(null) }
    val context = LocalContext.current
    val viewModel = remember { ResponseUser(context) }

    var users by remember { mutableStateOf<List<Users>>(listOf()) }
    LaunchedEffect(Unit) {
        withContext(Dispatchers.IO) {
//

            users = Constants.supabase.from("Users")
                .select().decodeList<Users>()
//            cwardrobs.forEach { it ->
//                Log.d("ts", it.toString())

        }



    }
    val selectedThings = listOf(selectedThingId1, selectedThingId2, selectedThingId3) // ID выбранных вещей

    var selectedthing by remember { mutableStateOf<Things_user?>(null) }
    Column(
        modifier = Modifier
            .fillMaxHeight()
            .fillMaxWidth()
            .background(
                Brush.verticalGradient(
                    colors = listOf(
                        Color(0xFFF4F4F4),
                        Color(0xFFE7D2A9),
                        Color(0xFFC1A88B),
                        Color(0xFF6F4A48)
                    )
                )
            ),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {

        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),
                        ),
                        shape = RoundedCornerShape(30.dp)
                    )

                    // Выбор изображения
                    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)) // Отступ между текстом и кнопкой


                    Spacer(modifier = Modifier.height(10.dp)) // Отступ между текстом и кнопкой
                    Box(modifier = Modifier.fillMaxWidth()) {
                        Button(
                            onClick = { expanded3 = true },
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(8.dp)
                                .background(
                                    color = Color.White,
                                    shape = ButtonDefaults.shape
                                ) // Белый цвет и закругленные края
                                .border(1.dp, Color.Gray, RoundedCornerShape(8.dp)) // Серый контур
                                .height(48.dp), // Высота кнопки
                            colors = ButtonDefaults.buttonColors(containerColor = Color.Transparent)
                        ) {
                            Text(
                                text = if (newThingName1.isNotEmpty()) newThingName1 else "Выберите вещь 1", // Плейсхолдер
                                color = Color(0xFF92A2B0),
                                fontSize = 16.sp
                            )
                        }

                        DropdownMenu(
                            expanded = expanded3,
                            onDismissRequest = { expanded3 = false }
                        ) {
                            things.forEach { thing ->
                                DropdownMenuItem(
                                    onClick = {
                                        selectedThingId1 = thing// Сохраняем ID выбранной вещи
                                        newThingName1 = thing.title
                                        expanded3 = false
                                    }
                                ) {
                                    Text(thing.title)
                                }
                            }
                        }
                    }





                    Spacer(modifier = Modifier.height(10.dp)) // Отступ между текстом и кнопкой
                    Box(modifier = Modifier.fillMaxWidth()) {
                        Button(
                            onClick = { expanded1 = true },
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(8.dp)
                                .background(
                                    color = Color.White,
                                    shape = ButtonDefaults.shape
                                ) // Белый цвет и закругленные края
                                .border(1.dp, Color.Gray, RoundedCornerShape(8.dp)) // Серый контур
                                .height(48.dp) // Высота кнопки
                            ,
                            colors = ButtonDefaults.buttonColors(containerColor = Color.Transparent)
                        ) {
                            Text(
                                text = if (newThingName2.isNotEmpty()) newThingName2 else "Выберите вещь 2", // Плейсхолдер
                                color = Color(0xFF92A2B0),
                                fontSize = 16.sp
                            )
                        }

                        DropdownMenu(
                            expanded = expanded1,
                            onDismissRequest = { expanded1 = false }
                        ) {
                            things.forEach { thing ->
                                DropdownMenuItem(
                                    onClick = {
                                        selectedThingId2 = thing
                                        newThingName2 = thing.title
                                        expanded1 = false
                                    }
                                ) {
                                    Text(thing.title)
                                }
                            }
                        }
                    }
                    Spacer(modifier = Modifier.height(10.dp)) // Отступ между текстом и кнопкой

                    Box(modifier = Modifier.fillMaxWidth()) {
                        Button(
                            onClick = { expanded2 = true },
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(8.dp)
                                .background(
                                    color = Color.White,
                                    shape = ButtonDefaults.shape
                                ) // Белый цвет и закругленные края
                                .border(1.dp, Color.Gray, RoundedCornerShape(8.dp)) // Серый контур
                                .height(48.dp) // Высота кнопки
                            ,
                            colors = ButtonDefaults.buttonColors(containerColor = Color.Transparent)
                        ) {
                            Text(
                                text = if (newThingName3.isNotEmpty()) newThingName3 else "Выберите вещь 3", // Плейсхолдер
                                color = Color(0xFF92A2B0),
                                fontSize = 16.sp
                            )
                        }

                        DropdownMenu(
                            expanded = expanded2,
                            onDismissRequest = { expanded2 = false }
                        ) {
                            things.forEach { thing ->
                                DropdownMenuItem(
                                    onClick = {
                                        selectedThingId3 = thing
                                        newThingName3 = thing.title
                                        expanded2 = false
                                    }
                                ) {
                                    Text(thing.title)
                                }
                            }
                        }
                    }

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

                    Text("Публиковать?")
                    Row{
                        Row(
                            verticalAlignment = Alignment.CenterVertically,
                            modifier = Modifier
                                .selectable(
                                    selected = public,
                                    onClick = { public = true }
                                )
                                .padding(top = 14.dp)
                        ) {
                            androidx.compose.material3.RadioButton(
                                selected = public,
                                onClick = { public = true }
                            )
                            Text(
                                text = "Да",
                                fontSize = 16.sp,
                                modifier = Modifier.padding(start = 0.dp), // Отступ слева от радиокнопки
                                color = Color(0xFF92A2B0)
                            )
                        }

                        Row(
                            verticalAlignment = Alignment.CenterVertically,
                            modifier = Modifier
                                .selectable(
                                    selected = !public,
                                    onClick = { public = false }
                                )
                                .padding(top = 14.dp)
                        ) {
                            androidx.compose.material3.RadioButton(
                                selected = !public,
                                onClick = { public = false }
                            )
                            Text(
                                text = "Нет",
                                fontSize = 16.sp,
                                modifier = Modifier.padding(start = 0.dp), // Отступ слева от радиокнопки
                                color = Color(0xFF92A2B0)
                            )
                        }
                    }

                    Box(
                        modifier = Modifier
                            .fillMaxSize() // Заполняем весь доступный размер
                    ) {
                        Column(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(bottom = 50.dp), // Отступ внизу для всего столбца
                            verticalArrangement = Arrangement.Bottom // Располагаем кнопки внизу
                        ) {
                            Column(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(bottom = 50.dp), // Отступ внизу для всего столбца
                                horizontalAlignment = Alignment.CenterHorizontally // Центрируем содержимое по вертикали
                            ) {

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

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

                                Button(

                                    onClick = {
                                        // Логирование значений перед вызовом addBow
                                        Log.d(
                                            "AddBow",
                                            "Creating new bow with the following parameters:"
                                        )
                                        Log.d("AddBow", "newThingName: $newThingName")
                                        Log.d("AddBow", "selectedThings: $selectedThings")
                                        Log.d("AddBow", "imageUri: $imageUri")
                                        Log.d(
                                            "AddBow",
                                            "authorizedUser .id: ${authorizedUser?.id ?: "null"}"
                                        )

                                        if (authorizedUser != null) {
                                            viewModel.addBow(
                                                newThingName,
                                                selectedThings,
                                                imageUri,
                                                authorizedUser.id ?: 0,
                                                pub = public
                                            )
                                            Log.d(
                                                "AddBow",
                                                "Bow created successfully"
                                            ) // Логирование успешного создания
                                        } else {
                                            Log.w(
                                                "AddBow",
                                                "User  is not authorized, bow creation failed"
                                            ) // Логирование ошибки
                                        }
                                    },
                                    colors = ButtonDefaults.buttonColors(
                                        Color(0xFFD05656),
                                        contentColor = Color.White
                                    ),
                                    shape = ButtonDefaults.shape
                                ) {
                                    Text(
                                        text = "Создать",
                                        fontSize = 16.sp,
                                        fontWeight = FontWeight.Medium
                                    )
                                }
                                Spacer(modifier = Modifier.height(10.dp))
                                Button(
                                    onClick = onDismiss,
                                    colors = ButtonDefaults.buttonColors(
                                        Color(0xFFD05656),
                                        contentColor = Color.White
                                    ),
                                    shape = ButtonDefaults.shape
                                ) {
                                    Text(
                                        text = "Закрыть",
                                        fontSize = 16.sp,
                                        fontWeight = FontWeight.Medium
                                    )
                                }
                            }
                        }
                    }

                }
            }

        }
    }
}
@Composable
fun DeleteBowConfirmationDialog(
    openDialog: Boolean,
    bows: Bows,
    onConfirm: (Bows) -> Unit,
    onDismiss: () -> Unit,
    navHost: NavHostController
) {

    if (openDialog) {
        AlertDialog(
            onDismissRequest = onDismiss,
            title = {
                Text(text = "Подтверждение удаления")
            },
            text = {
                Text("Вы уверены, что хотите удалить этот образ?")
            },
            confirmButton = {
                Button(onClick = {
                    onConfirm(bows) // Вызов функции для удаления элемента
                    onDismiss() // Закрыть диалог после подтверждения
                    navHost.navigate("MyBows")
                },
                    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("Нет")
                }
            }
        )
    }
}


