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.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.lazy.LazyColumn
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.material3.CircularProgressIndicator
import androidx.compose.material3.Text
import androidx.compose.foundation.lazy.items
import androidx.compose.material.DrawerValue
import androidx.compose.material.ModalDrawer
import androidx.compose.material.rememberDrawerState
import androidx.compose.material3.Divider
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.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.Publicthings
import com.example.exvesta.model.Season_dublicate
import com.example.exvesta.model.Style_dublicate
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.withContext
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material.*
import androidx.compose.ui.graphics.Brush
import com.example.exvesta.Screans.Responses.Auth
import com.example.exvesta.Screans.Responses.ResponseUser
import com.example.exvesta.model.Consists_wardrob
import com.example.exvesta.model.Things_user
import com.example.exvesta.model.Users
import com.example.exvesta.model.Wardob
import io.github.jan.supabase.gotrue.auth
import kotlinx.coroutines.launch


@OptIn(ExperimentalMaterialApi::class)
@Composable
fun Home(navHost: NavHostController) {
    var subdubtype by remember { mutableStateOf<List<Type_subtype_dublicate>>(listOf()) }
    var dubtype by remember { mutableStateOf<List<Type_dublicate>>(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 cwardrobs by remember { mutableStateOf<List<Consists_wardrob>>(listOf()) }
    var wardrobs by remember { mutableStateOf<List<Wardob>>(listOf()) }
    var userthings by remember { mutableStateOf<List<Things_user>>(listOf()) }
    val context = LocalContext.current
    val viewModel  = remember { ResponseUser(context) }
    var ThingName 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("") }
    var selectwardrob by remember { mutableStateOf<Users?>(null) }
    var users by remember { mutableStateOf<List<Users>>(listOf()) }
    LaunchedEffect(Unit) {
        withContext(Dispatchers.IO) {
            cwardrobs  = Constants.supabase.from("Consists_wardrob")
                .select().decodeList<Consists_wardrob>()
            wardrobs  = Constants.supabase.from("Wardob")
                .select().decodeList<Wardob>()
            userthings  = Constants.supabase.from("Things_user")
                .select().decodeList<Things_user>()
            publicthings = Constants.supabase.from("Publicthings")
                .select().decodeList<Publicthings>()
            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()

    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 = { /*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 = { navHost.navigate("Bowss")  },
                        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
                ) { publicthing ->
                    val imageState = rememberAsyncImagePainter(
                        model = ImageRequest.Builder(LocalContext.current).data(publicthing.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
                                    ) {
                                        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


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

                                if (subtype != null) {
                                    val typeid = subtype.id_type
                                    val type = dubtype.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(1.dp))
                                Text(
                                    "Артикул: ${publicthing.article}",
                                    fontSize = 18.sp,
                                    modifier = Modifier.padding(start = 8.dp),
                                    color = Color(0xFF92A2B0)
                                )

                                Spacer(modifier = Modifier.height(8.dp))
                                Row(
                                    horizontalArrangement = Arrangement.SpaceAround
                                )
                                {
                                    Text(
                                        "Рэйтинг: ${publicthing.rating}",
                                        fontSize = 18.sp,
                                        modifier = Modifier.padding(start = 8.dp),
                                        color = Color(0xFF92A2B0)
                                    )



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


                                            if (authorizedUser  != null) {

                                                selectwardrob = authorizedUser
                                                selectSeason = season
                                                selectStyle = style
                                                selectSubtype = subtype
                                                ThingName = publicthing.title
                                                imageUri = (publicthing.img?:null).toString()

                                                Log.d("MyApp", "Adding public thing with details: " +
                                                        "Wardrobe ID: ${selectwardrob!!.id}, " +
                                                        "Style ID: ${selectStyle!!.id}, " +
                                                        "Subtype ID: ${selectSubtype!!.id}, " +
                                                        "Title: $ThingName, " +
                                                        "Season ID: ${selectSeason!!.id}, " +
                                                        "Image URI: $imageUri")

                                                selectwardrob!!.id?.let {
                                                    viewModel.addpublickthing(
                                                        userthing = userthings,
                                                        conwar = cwardrobs,
                                                        id_wardrob = it,
                                                        selectstyle = selectStyle!!.id,
                                                        selectsubtype = selectSubtype!!.id,
                                                        selecttitle = ThingName,
                                                        selectseason = selectSeason!!.id,
                                                        selectimg = imageUri

                                                    )
                                                }
                                            }
                                            else {
                                                Log.e("MyApp", "No authorized user found for User ID: $authorizedUser")
                                            }
                                        },
                                        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 = 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 })

        }
    }
}



    @Composable
 public  fun DrawerContent(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)
                )
            }
            Spacer(modifier = Modifier.height(32.dp))
            // Кнопки
            Button(
                onClick = { navHost.navigate("MyBows")  },
                modifier = Modifier
                    .fillMaxWidth()
                    .height(48.dp),
                colors = ButtonDefaults.buttonColors(
                    Color(0xFFF0F0F0),
                    contentColor = Color(0xFF92A2B0)
                )
            ) {
                Text("Мои образы")
            }
            Spacer(modifier = Modifier.height(8.dp))
            Button(
                onClick = { navHost.navigate("Wardrob")  },
                modifier = Modifier
                    .fillMaxWidth()
                    .height(48.dp),
                colors = ButtonDefaults.buttonColors(
                    Color(0xFFF0F0F0),
                    contentColor = Color(0xFF92A2B0)
                )
            ) {
                Text("Коллекция")
            }
            Spacer(modifier = Modifier.height(8.dp))
            Button(
                onClick = { navHost.navigate("Home")  },
                modifier = Modifier
                    .fillMaxWidth()
                    .height(48.dp),
                colors = ButtonDefaults.buttonColors(
                    Color(0xFFF0F0F0),
                    contentColor = Color(0xFF92A2B0)
                )
            ) {
                Text("Лента")
            }
        }
    }
