package com.example.development.mainActivity.components

import android.util.Log
import android.widget.ArrayAdapter
import android.widget.LinearLayout
import android.widget.Spinner
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.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
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.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.TextUnit
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.development.R
import com.example.development.domain.utils.Constants
import com.example.development.mainActivity.MainViewModel
import com.example.development.model.Category
import io.github.jan.supabase.storage.BucketItem
import com.example.development.model.Menu
import com.example.development.ui.theme.OldStandart
import io.github.jan.supabase.postgrest.from
import io.ktor.util.Identity.decode
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

fun filterMenuItemsByCategory(menuItems: List<Menu>, categoryId: Int): List<Menu>
{
    return menuItems.filter {it.category == categoryId}
}

@Composable
fun MenuPage(navController: NavHostController, viewModel: MainViewModel)
{
    var menu by remember { mutableStateOf<List<Menu>>(listOf()) }
    var bucket: ByteArray? = null
    var bytes: ByteArray? = null
    var files: List<BucketItem>? = null
    var category by remember {mutableStateOf<List<Category>>(listOf())}
    var selectedCategory by remember {mutableStateOf<Int?>(null)}
    var expanded by remember { mutableStateOf(false) }

    LaunchedEffect(Unit) {
        withContext(Dispatchers.IO) {
            category = Constants.supabase.from("menu_categories")
                .select().decodeList<Category>()
        }
    }

    LaunchedEffect(Unit) {
        withContext(Dispatchers.IO) {
            menu = Constants.supabase.from("menu")
                .select().decodeList<Menu>()
        }
    }

    Box(
        contentAlignment = Alignment.TopCenter,
        modifier = Modifier
            .fillMaxSize()
    )
    {
        Image(
            painter = painterResource(id = R.drawable.fone),
            contentDescription = "",
            contentScale = ContentScale.FillWidth,
            modifier = Modifier
                .fillMaxWidth()
                .fillMaxHeight()
        )
        Column(
            modifier = Modifier.fillMaxSize(),
            verticalArrangement = Arrangement.Top,
            horizontalAlignment = Alignment.CenterHorizontally
        )
        {
            Row(modifier = Modifier
                .padding(30.dp)
                .fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceAround
                ){
                Column()
                {
                    IconButton(onClick = { expanded = true })
                    {
                        Icon(Icons.Default.Menu, contentDescription = "Показать категории")
                    }
                    DropdownMenu(expanded = expanded,
                        onDismissRequest = {expanded = false}) {
                        category.forEach{
                                category ->  DropdownMenuItem(onClick = {}, text = {category.name})
                        }
                    }
                }
                Text("МЕНЮ",
                    color = Color(255, 215, 0),
                    modifier = Modifier.padding(30.dp),
                    fontSize = 30.sp,
                    fontWeight = FontWeight.Bold,
                    fontFamily = OldStandart
                )
                Button(
                    modifier = Modifier
                        .padding(0.dp),
                    onClick = {navController.navigate("MainPage")},
                    colors = ButtonDefaults.buttonColors(
                        containerColor = Color(255, 215, 0, 0),
                        contentColor = Color.Gray
                    ),
                    border = BorderStroke(0.dp, color = Color(255, 215, 0, 0))
                )
                {
                    Image(
                        painter = painterResource(id = R.drawable.home),
                        contentDescription = "",
                        contentScale = ContentScale.FillWidth,
                        modifier = Modifier
                            .width(60.dp)
                            .height(60.dp)
                    )
                }

            }

            val filteredMenuItems = selectedCategory?.let{
                filterMenuItemsByCategory(menu, it)
            }?:menu

            LazyColumn {
                items(
                    filteredMenuItems,
                    key = { menu -> menu.id },
                ){
                    item ->
                    Column(
                        Modifier
                            .fillMaxWidth()
                            .clip(RoundedCornerShape(15.dp))
                            .background(color = Color.White)) {
                        Column(modifier = Modifier.padding(1.dp))
                        {
                            val imageState = rememberAsyncImagePainter(
                                model = ImageRequest.Builder(LocalContext.current).data(item.image)
                                    .size(Size.ORIGINAL).build()
                            ).state
                            if (imageState is AsyncImagePainter.State.Error) {
                                Box(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .height(200.dp),
                                    contentAlignment = Alignment.Center
                                ) {
                                    CircularProgressIndicator()
                                }
                            }

                            if (imageState is AsyncImagePainter.State.Success) {
                                Image(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .height(200.dp),
                                    painter = imageState.painter,
                                    contentDescription = "",
                                    contentScale = ContentScale.Crop
                                )
                            }
                        }
                        Column(modifier = Modifier.padding(1.dp))
                        {
                            Text(
                                item.name,
                                modifier = Modifier.padding(8.dp),
                                color = Color.Gray,
                                fontWeight = FontWeight.Normal,
                                fontFamily = OldStandart
                            )
                            Text(
                                item.description,
                                modifier = Modifier.padding(8.dp),
                                color = Color.Gray,
                                fontWeight = FontWeight.Normal,
                                fontFamily = OldStandart
                            )
                            Text(
                                item.structure,
                                modifier = Modifier.padding(8.dp),
                                color = Color.Gray,
                                fontWeight = FontWeight.Normal,
                                fontFamily = OldStandart
                            )
                            Text(
                                item.weight.toString(),
                                modifier = Modifier.padding(8.dp),
                                color = Color.Gray,
                                fontWeight = FontWeight.Normal,
                                fontFamily = OldStandart
                            )
                            Text(
                                "Цена: " + item.price.toString(),
                                modifier = Modifier.padding(8.dp),
                                color = Color.Gray,
                                fontWeight = FontWeight.Normal,
                                fontFamily = OldStandart
                            )
                        }
                    }
                }
            }
        }
    }
}