package com.example.lectionsupabase.view.mainActivity.components
import androidx.compose.foundation.Image
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.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowForward
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.graphics.Color
import androidx.compose.ui.layout.ContentScale
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.rememberImagePainter
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 loadingUsers by remember { mutableStateOf(true) }
    var users by remember { mutableStateOf<List<Admin>>(listOf()) }

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

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

    // Основное содержимое экрана
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp)
    ) {
        // Верхняя панель с заголовком и кнопкой перехода
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(vertical = 16.dp),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.SpaceBetween
        ) {
            Text(
                text = "Рестораны",
                style = MaterialTheme.typography.headlineMedium,
                fontWeight = FontWeight.Bold,
                color = MaterialTheme.colorScheme.onBackground
            )
            IconButton(
                onClick = { navHost.navigate("Cinema") }
            ) {
                Icon(
                    imageVector = Icons.Default.ArrowForward,
                    contentDescription = "Перейти к киноафише",
                    tint = MaterialTheme.colorScheme.primary
                )
            }
        }

        // Загрузка автомобилей
        if (loadingRest) {
            Box(
                modifier = Modifier.fillMaxSize(),
                contentAlignment = Alignment.Center
            ) {
                CircularProgressIndicator(modifier = Modifier.size(72.dp))
            }
        } else {
            // Список автомобилей
            LazyColumn(
                modifier = Modifier
                    .fillMaxHeight(0.9f) // Оставляем немного места для кнопки
                    .padding(bottom = 16.dp),
                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(8.dp),
                        colors = CardDefaults.cardColors(containerColor = Color(0XFFcce6ff))
                    ) {
                        Column(modifier = Modifier.fillMaxWidth()) {
                            Text(
                                text = "${restaurant.name}",
                                style = MaterialTheme.typography.titleMedium,
                                fontWeight = FontWeight.SemiBold,
                                fontSize = 18.sp,
                                modifier = Modifier.padding(16.dp)
                            )
                            Text(
                                text = "${restaurant.location}",
                                style = MaterialTheme.typography.titleMedium,
                                fontWeight = FontWeight.SemiBold,
                                fontSize = 18.sp,
                                modifier = Modifier.padding(16.dp)
                            )
                            Text(
                                text = "${restaurant.cuisin}",
                                style = MaterialTheme.typography.titleMedium,
                                fontWeight = FontWeight.SemiBold,
                                fontSize = 18.sp,
                                modifier = Modifier.padding(16.dp)
                            )
                            val painter = rememberImagePainter(
                                data = restaurant.picture,
                                builder = {
                                    crossfade(true)
                                }
                            )

                            Image(
                                painter = painter,
                                contentDescription = "Фото ресторана",
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .height(200.dp),
                                contentScale = ContentScale.Crop
                            )
                        }
                    }
                }
            }
        }


//        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)
//                }
//            }
        }
    }




