package com.example.development.mainActivity.components

import android.util.Log
import android.widget.ScrollView
import androidx.annotation.Nullable
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.horizontalScroll
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.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Star
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
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 com.example.development.R
import com.example.development.domain.utils.Constants
import com.example.development.mainActivity.MainViewModel
import com.example.development.model.Review
import com.example.development.model.User
import com.example.development.ui.theme.OldStandart
import io.github.jan.supabase.gotrue.auth
import io.github.jan.supabase.postgrest.from
import io.github.jan.supabase.storage.BucketItem
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

@Composable
fun MainPage(navController: NavHostController, viewModel: MainViewModel)
{
    val context = LocalContext.current
    var reviews by remember { mutableStateOf<List<Review>>(listOf()) }
    var bucket: ByteArray? = null
    var bytes: ByteArray? = null
    var files: List<BucketItem>? = null

    var rating by remember { mutableStateOf(0f) }
    val flag = remember { mutableStateOf(false) }

    LaunchedEffect(Unit) {
        withContext(Dispatchers.IO) {
            reviews = Constants.supabase.from("reviews")
                .select()
                {
                    filter {
                        Review::estimation eq 5
                    }
                }.decodeList<Review>()
            reviews.forEach { it ->
                Log.d("P", it.comment)
            }
        }
    }
    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(top = 50.dp)
                    .background(color = Color(230, 235, 239, 50))
                    .fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceAround
            )
            {
                Button(
                    modifier = Modifier
                        .padding(0.dp)
                        .width(100.dp),
                    onClick = {navController.navigate("MenuPage")},
                    colors = ButtonDefaults.buttonColors(
                        containerColor = Color(230, 235, 239, 0),
                        contentColor = Color.Gray
                    ),
                    border = BorderStroke(0.dp, color = Color(230, 235, 239, 0))
                )
                {
                    Text(
                        "Меню",
                        fontSize = 16.sp,
                        color = Color.White,
                        fontWeight = FontWeight.Normal,
                        fontFamily = OldStandart
                    )
                }
                Button(
                    modifier = Modifier
                        .padding(0.dp)
                        .width(170.dp),
                    onClick = {navController.navigate("TableReserve")},
                    colors = ButtonDefaults.buttonColors(
                        containerColor = Color(230, 235, 239, 0),
                        contentColor = Color.Gray
                    ),
                    border = BorderStroke(0.dp, color = Color(230, 235, 239, 0))
                )
                {
                    Text(
                        "Забронировать стол",
                        fontSize = 16.sp,
                        color = Color.White,
                        fontWeight = FontWeight.Normal,
                        fontFamily = OldStandart,
                        softWrap = true,
                        textAlign = TextAlign.Center
                    )
                }

                Button(
                    modifier = Modifier
                        .padding(0.dp),
                    onClick = {navController.navigate("UserProfile")},
                    colors = ButtonDefaults.buttonColors(
                        containerColor = Color(230, 235, 239, 0),
                        contentColor = Color.Gray
                    ),
                    border = BorderStroke(0.dp, color = Color(230, 235, 239, 0))
                )
                {
                    Text(
                        "Профиль",
                        fontSize = 16.sp,
                        color = Color.White,
                        fontWeight = FontWeight.Normal,
                        fontFamily = OldStandart
                    )
                }
            }
            Column(modifier = Modifier
                .verticalScroll(rememberScrollState())
                .padding(top = 40.dp), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally)
            {
                Text(
                    "О ресторане",
                    fontSize = 26.sp,
                    color = Color(255,215,0),
                    fontWeight = FontWeight.Normal,
                    textAlign = TextAlign.Center,
                    fontFamily = OldStandart,
                    modifier = Modifier.padding(bottom = 20.dp)
                )
                Text(
                    "Ресторан “Чёрная жемчужина” - это уникальное\nместо, где гурманы могут насладиться изысканными\nморепродуктами и погрузиться в атмосферу морского приключения.\n" +
                            "Интерьер ресторана, оформленный в морской тематике, создает ощущение, что вы находитесь на борту роскошной яхты. Здесь можно не только утолить голод, но и расслабиться, наслаждаясь живой музыкой и уютной атмосферой, которая наполняет сердце теплом и спокойствием."
                    ,
                    fontSize = 16.sp,
                    color = Color.White,
                    fontWeight = FontWeight.Normal,
                    fontFamily = OldStandart,
                    softWrap = true,
                    textAlign = TextAlign.Center
                )
                Text(
                    "Наше меню",
                    fontSize = 26.sp,
                    color = Color(255,215,0),
                    fontWeight = FontWeight.Normal,
                    textAlign = TextAlign.Center,
                    fontFamily = OldStandart,
                    modifier = Modifier.padding(top = 20.dp, bottom = 20.dp)
                )
                Row(modifier = Modifier.horizontalScroll(rememberScrollState()), verticalAlignment = Alignment.Top, horizontalArrangement = Arrangement.Center)
                {
                    Image(painter = painterResource(id = R.drawable.img),
                        contentDescription = "",
                        contentScale = ContentScale.FillWidth,
                        modifier = Modifier
                            .width(200.dp)
                            .height(200.dp))
                    Image(painter = painterResource(id = R.drawable.img_1),
                        contentDescription = "",
                        contentScale = ContentScale.FillWidth,
                        modifier = Modifier
                            .width(200.dp)
                            .height(200.dp))
                    Image(painter = painterResource(id = R.drawable.img_2),
                        contentDescription = "",
                        contentScale = ContentScale.FillWidth,
                        modifier = Modifier
                            .width(200.dp)
                            .height(200.dp))
                }
                Text("В основе меню “Чёрная жемчужина” - изысканная морская кухня, предлагающая широкий выбор свежих морепродуктов, включая устрицы, мидии и креветки. Здесь можно попробовать филе рыбы, запеченное с ароматными травами, а также разнообразные блюда с рисом и пастой, приготовленные с добавлением лучших морских деликатесов. Особое внимание уделяется десертам: нежные муссы и фруктовые тарталетки создаются из натуральных ингредиентов, чтобы завершить трапезу на сладкой ноте.",
                    fontSize = 16.sp,
                    color = Color.White,
                    fontWeight = FontWeight.Normal,
                    fontFamily = OldStandart,
                    softWrap = true,
                    textAlign = TextAlign.Center,
                    modifier = Modifier.padding(top = 10.dp, bottom = 20.dp))
                Button(modifier = Modifier
                    .width(width = 270.dp)
                    .height(height = 40.dp),
                    onClick = {navController.navigate("MenuPage")},
                    shape = RoundedCornerShape(23.dp),
                    border = BorderStroke(0.dp, Color(0xFFEBEBEB)),
                    colors = ButtonDefaults.buttonColors(
                        containerColor = Color(255,215,0),
                        contentColor = Color.White)
                )
                {
                    Text("ПОСМОТРЕТЬ МЕНЮ",
                        fontSize = 20.sp,
                        color = Color.White,
                        fontWeight = FontWeight.Normal,
                        fontFamily = OldStandart)
                }
                Text(
                    "Отзывы",
                    fontSize = 26.sp,
                    color = Color(255,215,0),
                    fontWeight = FontWeight.Normal,
                    textAlign = TextAlign.Center,
                    fontFamily = OldStandart,
                    modifier = Modifier.padding(top = 20.dp, bottom = 20.dp)
                )
                LazyRow {
                    items(
                        reviews,
                        key = { reviews -> reviews.id!! },
                    ) { reviews ->
                        var user by remember { mutableStateOf<List<User>>(listOf()) }
                        LaunchedEffect(Unit) {
                            withContext(Dispatchers.IO) {
                                user = Constants.supabase.from("users")
                                    .select(){
                                        filter{
                                            User::UID eq reviews.user
                                        }
                                    }.decodeList<User>()
                                user.forEach { it ->
                                    it.UID?.let { it1 -> Log.d("P", it1) }
                                }
                            }
                        }
                        Column(modifier = Modifier.width(300.dp).height(200.dp)
                            .padding(bottom = 10.dp, end = 5.dp)
                            .clip(RoundedCornerShape(15.dp))
                            .background(color = Color(236,236,236,180)),
                            verticalArrangement = Arrangement.Center,
                            horizontalAlignment = Alignment.CenterHorizontally)
                        {
                            LazyRow {
                                items(
                                    user,
                                    key = { user -> user.UID!! },
                                ) { user ->
                                    Text(
                                        user.name + " " + user.surname,
                                        modifier = Modifier.padding(8.dp),
                                        color = Color.Black,
                                        fontSize = 18.sp,
                                        fontWeight = FontWeight.Normal,
                                        fontFamily = OldStandart
                                    )
                                }
                            }
                            Text(
                                reviews.created_at.toString(),
                                modifier = Modifier.padding(8.dp),
                                color = Color.Black,
                                fontSize = 18.sp,
                                fontWeight = FontWeight.Normal,
                                fontFamily = OldStandart
                            )
                            if (reviews.estimation == 1)
                            {
                                Row(modifier = Modifier.padding(5.dp))
                                {
                                    Icon(Icons.Default.Star, contentDescription = "Одна звезда")
                                }
                            }
                            if (reviews.estimation == 2)
                            {
                                Row(modifier = Modifier.padding(5.dp))
                                {
                                    Icon(Icons.Default.Star, contentDescription = "Одна звезда")
                                    Icon(Icons.Default.Star, contentDescription = "Вторая звезда")
                                }
                            }
                            if (reviews.estimation == 3)
                            {
                                Row(modifier = Modifier.padding(5.dp))
                                {
                                    Icon(Icons.Default.Star, contentDescription = "Одна звезда")
                                    Icon(Icons.Default.Star, contentDescription = "Вторая звезда")
                                    Icon(Icons.Default.Star, contentDescription = "Третья звезда")
                                }
                            }
                            if (reviews.estimation == 4)
                            {
                                Row(modifier = Modifier.padding(5.dp))
                                {
                                    Icon(Icons.Default.Star, contentDescription = "Одна звезда")
                                    Icon(Icons.Default.Star, contentDescription = "Вторая звезда")
                                    Icon(Icons.Default.Star, contentDescription = "Третья звезда")
                                    Icon(Icons.Default.Star, contentDescription = "Четвертая звезда")
                                }
                            }
                            if (reviews.estimation == 5)
                            {
                                Row(modifier = Modifier.padding(5.dp))
                                {
                                    Icon(Icons.Default.Star, contentDescription = "Одна звезда")
                                    Icon(Icons.Default.Star, contentDescription = "Вторая звезда")
                                    Icon(Icons.Default.Star, contentDescription = "Третья звезда")
                                    Icon(Icons.Default.Star, contentDescription = "Четвертая звезда")
                                    Icon(Icons.Default.Star, contentDescription = "Пятая звезда")
                                }
                            }
                            Text(
                                reviews.comment,
                                modifier = Modifier.padding(8.dp),
                                color = Color.Black,
                                fontSize = 18.sp,
                                fontWeight = FontWeight.Normal,
                                fontFamily = OldStandart
                            )
                        }
                    }
                }
                Button(modifier = Modifier
                    .width(width = 270.dp)
                    .height(height = 40.dp),
                    onClick = {navController.navigate("Reviews")},
                    shape = RoundedCornerShape(23.dp),
                    border = BorderStroke(0.dp, Color(0xFFEBEBEB)),
                    colors = ButtonDefaults.buttonColors(
                        containerColor = Color(255,215,0),
                        contentColor = Color.White)
                )
                {
                    Text("ВСЕ ОТЗЫВЫ",
                        fontSize = 20.sp,
                        color = Color.White,
                        fontWeight = FontWeight.Normal,
                        fontFamily = OldStandart)
                }
                Text(
                    "Контакты",
                    fontSize = 26.sp,
                    color = Color(255,215,0),
                    fontWeight = FontWeight.Normal,
                    textAlign = TextAlign.Center,
                    fontFamily = OldStandart,
                    modifier = Modifier.padding(top = 30.dp)
                )
                Text("Адрес:\nНижний Новгород, ул. Нижне-волжская наб., д. 1В\nРежим работы:\n11:00 - 22:00\nТелефон:\n+7 (904) 061 32 18",
                    fontSize = 15.sp,
                    color = Color.White,
                    fontWeight = FontWeight.Normal,
                    fontFamily = OldStandart,
                    softWrap = true,
                    textAlign = TextAlign.Left)
                Image(painter = painterResource(id = R.drawable.img_3),
                    contentDescription = "",
                    contentScale = ContentScale.FillHeight,
                    modifier = Modifier)
            }
        }
    }
}

