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.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.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.DrawerValue
import androidx.compose.material.ExperimentalMaterialApi
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.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.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 io.github.jan.supabase.postgrest.from
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext


@OptIn(ExperimentalMaterialApi::class)
@Composable
fun Bowss(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 recpubthingsList by remember { mutableStateOf<List<Publicthings>>(listOf()) }
    var filteredPublicThings by remember { mutableStateOf<List<Publicthings>>(listOf()) }
    var selectedBow by remember { mutableStateOf<Bows?>(null) }

    var showDialog by remember { mutableStateOf(false) }
    var userthings by remember { mutableStateOf<List<Things_user>>(listOf()) }
    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)
            }
        }
        filteredPublicThings = publicthings

    }
    var filtersApplied by remember { mutableStateOf(false) }
    var isFilterSheetVisible by remember { mutableStateOf(false) }
    var drawerState = rememberDrawerState(DrawerValue.Closed)
    val scope = rememberCoroutineScope()

    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 = {
                        isFilterSheetVisible = true
                    },
                    border = BorderStroke(1.dp, Color(0xFF92A2B0)),
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(vertical = 8.dp),
                    colors = ButtonDefaults.buttonColors(Color(0xFFF1F1F3))
                ) {
                    Text(text = "+ добавить фильтр", color = Color(0xFF92A2B0))

                }

            }
            if (filtersApplied) {
                Button(
                    onClick = {
                        filteredPublicThings = publicthings
                        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 = { navHost.navigate("Home")  },
                        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(
                bows
                ) { bow->
                    val iconb = bow.id
                    val cobow = conbows.filter { it.id_bow ==bow.id }
                    if(cobow!=null && bow.status==true){
                        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)) // Отступ между кнопками


                                        }
                                    }

                                }

                            }

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


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

                }

            }


        }

    }
    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) {
        ThingsListScreen(bow = selectedBow!!, things=userthings , conb = conbows, onDismiss = { showDialog = false })
    }
}



@Composable
public fun ThingsListScreen(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 && bow.status == true) {
                    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
                )
            }
        }
    }
}