package com.example.exvesta.Screans

import android.util.Log
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.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.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material.DrawerValue
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.rememberDrawerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
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.Color
import androidx.compose.ui.unit.dp
import androidx.navigation.NavHostController

//noinspection UsingMaterialAndMaterial3Libraries
import androidx.compose.material.*
import androidx.compose.runtime.*

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Menu
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
import coil.compose.AsyncImagePainter
import coil.compose.rememberAsyncImagePainter
import coil.request.ImageRequest
import coil.size.Size
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
import com.example.exvesta.model.Season_dublicate
import com.example.exvesta.model.Style
import com.example.exvesta.model.Style_dublicate
import com.example.exvesta.model.Things_user
import com.example.exvesta.model.Type
import com.example.exvesta.model.Type_dublicate
import com.example.exvesta.model.Type_subtype
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.postgrest.from
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

@Composable
fun Wardrob(navHost: NavHostController) {
    var drawerState = rememberDrawerState(DrawerValue.Closed)
    val scope = rememberCoroutineScope()
    var isFiltersVisible by remember { mutableStateOf(false) }
    var filteredPublicThings by remember { mutableStateOf<List<Wardob>>(listOf()) }
    var subdubtype by remember { mutableStateOf<List<Type_subtype>>(listOf()) }
    var type 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 isFilterSheetVisible by remember { mutableStateOf(false) }
    var wardrobs by remember { mutableStateOf<List<Wardob>>(listOf()) }
    var cwardrob by remember { mutableStateOf<List<Consists_wardrob>>(listOf()) }
    var users by remember { mutableStateOf<List<Users>>(listOf()) }
    LaunchedEffect(Unit) {
        withContext(Dispatchers.IO) {
            userthings  = Constants.supabase.from("Things_user")
                .select().decodeList<Things_user>()
            wardrobs  = Constants.supabase.from("Wardob")
                .select().decodeList<Wardob>()
            cwardrob  = Constants.supabase.from("Consists_wardrob")
                .select().decodeList<Consists_wardrob>()
            subdubtype = Constants.supabase.from("Type_subtype")
                .select().decodeList<Type_subtype>()
            type = Constants.supabase.from("Type")
                .select().decodeList<Type>()
            season = Constants.supabase.from("Season")
                .select().decodeList<Season>()
            style = Constants.supabase.from("Style")
                .select().decodeList<Style>()
            wardrobs.forEach { it ->
                Log.d("ts", it.toString())
            }
        }
        filteredPublicThings = wardrobs

    }
    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 { drawerState.close() } // Закрываем 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 = { /*TODO*/ },
                        border = BorderStroke(1.dp, Color(0xFF92A2B0)),
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(vertical = 8.dp),
                        colors = ButtonDefaults.buttonColors(Color.White)
                    ) {
                        Text(text = "+ добавить вещь", color = Color(0xFF92A2B0))
                    }

                }
            }
            if (filtersApplied) {
                Button(
                    onClick = {
                        filteredPublicThings = wardrobs
                        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))




            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceAround
            ) {
                // Кнопка "вещи"
                Box(
                    modifier = Modifier
                        .weight(1f)
                        .padding(bottom = 4.dp) // Паддинг для отступа от нижней тени
                        .clip(RoundedCornerShape(16.dp))
                ) {
                    // Тень
                    Box(
                        modifier = Modifier
                            .shadow(8.dp, RoundedCornerShape(30.dp))


                    )

                    // Кнопка
                    Button(
                        onClick = { /*TODO*/ },
                        modifier = Modifier
                            .fillMaxWidth()

                            .shadow(
                                0.dp,
                                shape = CircleShape,
                                clip = false
                            )// Убираем тень у кнопки
                            .background(
                                brush = Brush.horizontalGradient(
                                    colors = listOf(
                                        Color(0xFFF1F1F3),
                                        Color(0xFFFFFFFF),
                                    )
                                ), shape = ButtonDefaults.shape
                            ), // Убираем тень у кнопки
                        colors = ButtonDefaults.buttonColors(containerColor = Color.Transparent)

                    ) {
                        Text(text = "вещи", color = Color(0xFF92A2B0))
                    }
                }

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

                // Кнопка "образы"
                Box(
                    modifier = Modifier
                        .weight(1f)
                        .padding(bottom = 4.dp) // Паддинг для отступа от нижней тени
                        .clip(RoundedCornerShape(16.dp))
                ) {
                    // Тень
                    Box(
                        modifier = Modifier
                            .shadow(8.dp, RoundedCornerShape(30.dp))
                    )

                    // Кнопка
                    Button(
                        onClick = { /*TODO*/ },
                        modifier = Modifier
                            .fillMaxWidth()

                            .background(
                                brush = Brush.horizontalGradient(
                                    colors = listOf(
                                        Color(0xFFF1F1F3),
                                        Color(0xFFFFFFFF),
                                    )
                                ), shape = ButtonDefaults.shape
                            ), // Убираем тень у кнопки
                        colors = ButtonDefaults.buttonColors(containerColor = Color.Transparent),

                        ) {
                        Text(text = "образы", color = Color(0xFF92A2B0))
                    }
                }
            }



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

            LazyColumn(

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

                items(
                    filteredPublicThings

                ) { wardrob ->
                    val userid = wardrob.id
                    val conidwar = cwardrob.find { it.id == userid  }
val user =
         if(conidwar!= null) {
            if (conidwar.id_wardrob == wardrob.id) {


                 val imageState = rememberAsyncImagePainter(
                  model = ImageRequest.Builder(LocalContext.current).data(userthing.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
                        ) {
                            androidx.compose.material3.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


                        )
                    }
                    androidx.compose.material3.Divider(
                        modifier = Modifier.padding(vertical = 8.dp),
                        color = Color.LightGray,
                        thickness = 1.dp
                    )
                    Spacer(modifier = Modifier.height(8.dp))
                    Text(
                        "Название: ${userthing.title}",
                        fontSize = 18.sp,
                        modifier = Modifier.padding(start = 8.dp),
                        color = Color(0xFF92A2B0)
                    )
                    val seasonid = userthing.id_season
                    val season = season.find { it.id == seasonid }
                    val styleid = userthing.style
                    val style = style.find { it.id == styleid }
                    val subtypeid = userthing.subtype
                    val subtype = subdubtype.find { it.id == subtypeid }

                    if (subtype != null) {
                        val typeid = subtype.id_type
                        val type = type.find { it.id == typeid }



                        if (season != null && style != null && type != null) {
                            Text(
                                "Категории: ${style.title_style}, ${type.title_type},  ${subtype.sub_type}, ${season.title_season}",
                                fontSize = 18.sp,
                                modifier = Modifier.padding(start = 8.dp),
                                color = Color(0xFF92A2B0)
                            )


                        }
                    }


                    Spacer(modifier = Modifier.height(8.dp))
                    Row(
                        horizontalArrangement = Arrangement.SpaceAround
                    )
                    {


                        Button(
                            onClick = { navHost.navigate("Registration") },
                            modifier = Modifier
                                .width(200.dp)
                                .height(50.dp)
                                .padding(start = 50.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 (isFilterSheetVisible) {
        Column {
            Filters(
                onApplyFilters = { selectedSubtype, selectedSeason, selectedStyle ->
                    // Применяем фильтры и обновляем отображение
                    filteredPublicThings = 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 })

        }
    }



}


