package com.example.exvesta.Screans.Admin

import android.net.Uri
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
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.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
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.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.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.rememberImagePainter
import com.example.exvesta.domain.utils.Constants
import com.example.exvesta.model.Consists_wardrob
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.withContext
import androidx.compose.material3.OutlinedTextField
@OptIn(ExperimentalLayoutApi::class)
@Composable
public fun AddPub(things: List<Publicthings>, onDismiss: () -> Unit,  navHost: NavHostController) {

    var newThingName by remember { mutableStateOf("") }
    var filteredPublicThings by remember { mutableStateOf<List<Consists_wardrob>>(listOf()) }
    var subdubtype by remember { mutableStateOf<List<Type_subtype_dublicate>>(listOf()) }
    var types by remember { mutableStateOf<List<Type_dublicate>>(listOf()) }
    var season by remember { mutableStateOf<List<Season_dublicate>>(listOf()) }
    var style by remember { mutableStateOf<List<Style_dublicate>>(listOf()) }
    var article by remember { mutableStateOf("") }
    var selectSeason by remember { mutableStateOf<Season_dublicate?>(null) }
    var selectStyle by remember { mutableStateOf<Style_dublicate?>(null) }
    var selectSubtype by remember { mutableStateOf<Type_subtype_dublicate?>(null) }
    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 { viewModelAdmin(context) }

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


            users = Constants.supabase.from("Users")
                .select().decodeList<Users>()
            subdubtype = Constants.supabase.from("Type_subtype_dublicate")
                .select().decodeList<Type_subtype_dublicate>()
            types = Constants.supabase.from("Type_dublicate")
                .select().decodeList<Type_dublicate>()
            season= Constants.supabase.from("Season_dublicate")
                .select().decodeList<Season_dublicate>()
            style = Constants.supabase.from("Style_dublicate")
                .select().decodeList<Style_dublicate>()

        }



    }

    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
    ) {
        Spacer(modifier = Modifier.height(50.dp))
        Button(
            onClick = { onDismiss() }, // Закрыть выбор фильтров
            modifier = Modifier.padding(top = 16.dp)
                .fillMaxWidth()
                .background( Color(0xFFD05656),shape = ButtonDefaults.shape),
            colors = ButtonDefaults.buttonColors(containerColor = Color.Transparent)
        ) {
            Text("Закрыть ")
        }

        Spacer(modifier = Modifier.height(20.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),
                        ),

                        shape = RoundedCornerShape(30.dp)
                    )
                    Spacer(modifier = Modifier.height(10.dp))
                    OutlinedTextField(
                        value = article,
                        onValueChange = { article = 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))
                    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,
                                    article= article
                                )
                                // Закрываем панель
                                navHost.navigate("HomeAdmin")
                            },
                            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)) // Отступ между кнопками

//                                        }
                    }
                }

            }

        }
    }
}








@Composable
public  fun DrawerContentAdmin(navHost: NavHostController) {
    var users by remember { mutableStateOf<List<Users>>(listOf()) }
    LaunchedEffect(Unit) {
        withContext(Dispatchers.IO) {
            users = Constants.supabase.from("Users")
                .select().decodeList<Users>()
        }}
    Column(
        modifier = Modifier
            .fillMaxHeight()
            .fillMaxWidth()

            .background(
                Brush.verticalGradient(
                    colors = listOf(
                        Color(0xFFF1F1F3),
                        Color(0xFFF1F1F3),
                        Color(0xFFF1F1F3),
                        Color(0xFFF1F1F3),
                        Color(0xFFF1F1F3),
                        Color(0xFFEDE3CF),
                        Color(0xFFEBDBBC),
                        Color(0xFF6F4A48)
                    ),

                    )
            )
        ,
        verticalArrangement = Arrangement.Top,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Spacer(modifier = Modifier.height(60.dp))
        Text(
            text = "EXVESTA",
            fontSize = 30.sp,
            fontWeight = FontWeight.Medium,
            color = Color(0xFF92A2B0)
        )
        Spacer(modifier = Modifier.height(16.dp))
        // Аватар пользователя
        Box(
            modifier = Modifier
                .shadow(8.dp, CircleShape)
        ) {
            Box(
                modifier = Modifier
                    .size(150.dp)
                    .clip(CircleShape)
                    .background(Color(0xFFFFFFFF)),
                contentAlignment = Alignment.Center
            ){}
        }
        Spacer(modifier = Modifier.height(16.dp))
        val username = Constants.supabase.auth.currentUserOrNull()?.id
        val authorizedUser  = users.find { it.user == username }
        if (authorizedUser!=null){
            val name = authorizedUser.Name

            Text(
                text = "${name}",
                fontSize = 16.sp,
                fontWeight = FontWeight.Medium,
                color = Color(0xFF92A2B0)
            )
        }

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

                    navHost.navigate("HomeAdmin")
                },
                    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("Нет")
                }
            }
        )
    }
}
