package com.example.lectionsupabase.view.mainActivity.components
import androidx.compose.animation.animateContentSize
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.material.BottomNavigation
import androidx.compose.material.BottomNavigationItem
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.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.ArrowForward
import androidx.compose.material.icons.filled.Email
import androidx.compose.material.icons.filled.Person
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
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.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import androidx.navigation.NavHostController
import coil.compose.rememberImagePainter
import com.example.lectionsupabase.R
import com.example.lectionsupabase.domain.utils.Constants
import com.example.lectionsupabase.model.Admin
import com.example.lectionsupabase.model.Cars
import com.example.lectionsupabase.model.Restaurants
import io.github.jan.supabase.gotrue.auth
import io.github.jan.supabase.postgrest.from

@Composable
fun Restaurants(navHost: NavHostController) {
    var restaurants by remember { mutableStateOf<List<Restaurants>>(listOf()) }
    var loadingRest by remember { mutableStateOf(true) }
    var users by remember { mutableStateOf<List<Admin>>(listOf()) }
    val montserratSemiBold = FontFamily(Font(R.font.mon_semibold))
    var selectedIndex by remember { mutableStateOf(0) }
    val montserratRegular = FontFamily(Font(R.font.mon_regular))
    val montserratMedium = FontFamily(Font(R.font.mon_medium))

    // Загружаем список ресторанов
    LaunchedEffect(Unit) {
        try {
            restaurants = Constants.supabase.from("Restaurants")
                .select()
                .decodeList<Restaurants>()
            loadingRest = false
        } catch (e: Exception) {
            println("Error loading restaurants: ${e.message}")
            loadingRest = false
        }
    }

    // Загружаем список администраторов
    LaunchedEffect(Unit) {
        try {
            users = Constants.supabase.from("Admin")
                .select()
                .decodeList<Admin>()
        } catch (e: Exception) {
            println("Error loading users: ${e.message}")
        }
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp)
            .padding(top = 20.dp),
    ) {
        // Заголовок
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(vertical = 6.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            // Стрелка влево
            IconButton(
                onClick = { navHost.navigate("previous_screen") },
                modifier = Modifier.padding(end = 8.dp)
            ) {
                Icon(
                    imageVector = Icons.Default.ArrowBack,
                    contentDescription = "Назад",
                    tint = Color.White
                )
            }

            Text(
                text = "Рестораны",
                style = MaterialTheme.typography.headlineMedium,
                fontWeight = FontWeight.Bold,
                color = MaterialTheme.colorScheme.onBackground,
                textAlign = TextAlign.Center,
                fontSize = 20.sp,
                fontFamily = montserratSemiBold,
                modifier = Modifier.weight(1f)
            )

            // Стрелка вправо
            IconButton(
                onClick = { navHost.navigate("Cinema") },
                modifier = Modifier.padding(start = 8.dp)
            ) {
                Icon(
                    imageVector = Icons.Default.ArrowForward,
                    contentDescription = "Перейти к киноафише",
                    tint = Color.Black
                )
            }
        }

        // Загрузка ресторанов
        if (loadingRest) {
            Box(
                modifier = Modifier.fillMaxSize(),
                contentAlignment = Alignment.Center
            ) {
                CircularProgressIndicator(modifier = Modifier.size(72.dp))
            }
        } else {
            // Список ресторанов
            LazyColumn(
                modifier = Modifier
                    .weight(1f),

                verticalArrangement = Arrangement.spacedBy(16.dp)
            ) {
                items(restaurants, key = { restaurant -> restaurant.id }) { restaurant ->
                    Card(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(8.dp),
                        elevation = CardDefaults.cardElevation(0.dp),
                        shape = RoundedCornerShape(20.dp),
                        colors = CardDefaults.cardColors(containerColor = Color.White),
                        border = BorderStroke(0.5.dp, Color.LightGray)
                    ) {
                        Column(modifier = Modifier.fillMaxWidth()) {
                            val painter = rememberImagePainter(
                                data = restaurant.picture,
                                builder = {
                                    crossfade(true)
                                }
                            )

                            Image(
                                painter = painter,
                                contentDescription = "Фото ресторана",
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .height(190.dp),
                                contentScale = ContentScale.Crop
                            )
                            Spacer(modifier = Modifier.height(10.dp))
                            // Информация о ресторане
                            Text(
                                text = "Название: ${restaurant.name}",
                                style = MaterialTheme.typography.titleMedium,
                                fontSize = 14.sp,
                                modifier = Modifier.padding(horizontal = 10.dp)
                                    .padding(start = 3.dp),
                                fontFamily = montserratRegular
                            )
                            Text(
                                text = "Адрес: ${restaurant.location}",
                                style = MaterialTheme.typography.titleMedium,
                                fontSize = 14.sp,
                                modifier = Modifier.padding(horizontal = 10.dp)
                                    .padding(start =  3.dp),
                                fontFamily = montserratRegular
                            )
                            Text(
                                text = "Кухня: ${restaurant.cuisin}",
                                style = MaterialTheme.typography.titleMedium,
                                fontSize = 14.sp,
                                modifier = Modifier.padding(horizontal = 10.dp)
                                    .padding(start = 3.dp),
                                fontFamily = montserratRegular
                            )
                            Text(
                                text = "Посмотреть на карте",
                                style = MaterialTheme.typography.titleMedium,
                                fontWeight = FontWeight.SemiBold,
                                fontSize = 14.sp,
                                modifier = Modifier
                                    .padding(horizontal = 10.dp)
                                    .padding(start = 3.dp)
                                    .clickable {
                                        navHost.navigate("Maps_rest") // Замените "MapScreen" на ваш маршрут
                                    },
                                fontFamily = montserratMedium,
                                color = Color(0xFF72C3F1)
                            )
                            Spacer(modifier = Modifier.height(15.dp))
                        }
                    }
                }
            }
        }

        Panel(navHost)
        }
    }



//        val userId = Constants.supabase.auth.currentUserOrNull()?.id
//        val userIdString = userId?.toString() ?: ""
//
//        if (!loadingUsers && userId != null) {
//            val user = users.find { it.id_user == userIdString }
//            if (user != null) {
//                Spacer(modifier = Modifier.weight(1f)) // Занимаем оставшееся пространство для размещения кнопки внизу
//                Button(
//                    onClick = { navHost.navigate("InsertCar") },
//                    modifier = Modifier
//                        .fillMaxWidth()
//                        .height(56.dp)
//                        .padding(8.dp)
//                        .padding(bottom = 24.dp),
//                shape = RoundedCornerShape(12.dp), // Кнопка с более квадратными углами
//                    colors = ButtonDefaults.buttonColors(
//                        containerColor = Color(0XFFcce6ff),
//                        contentColor = Color.White
//                    )
//                ) {
//                    Text("Добавить новый автомобиль", fontSize = 18.sp)
//                }
//            }




