package com.example.lectionsupabase.view.mainActivity.components

import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
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.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.ArrowBack
import androidx.compose.material.icons.filled.ArrowForward
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.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
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.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.Benchs
import com.example.lectionsupabase.model.Movie
import io.github.jan.supabase.postgrest.from

@Composable
fun Benchs(navHost: NavHostController) {
    var benchs by remember { mutableStateOf<List<Benchs>>(listOf()) }
    var loadingBench by remember { mutableStateOf(true) }
    var loadingUsers by remember { mutableStateOf(true) }
    var users by remember { mutableStateOf<List<Admin>>(listOf()) }
    val montserratSemiBold = FontFamily(Font(R.font.mon_semibold))
    val montserratRegular = FontFamily(Font(R.font.mon_regular))
    val montserratMedium = FontFamily(Font(R.font.mon_medium))

    LaunchedEffect(Unit) {
        try {
            benchs = Constants.supabase.from("Benchs")
                .select()
                .decodeList<Benchs>()
            loadingBench = false
        } catch (e: Exception) {
            println("Error loading benches: ${e.message}")
            loadingBench = 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)
            .padding(top = 20.dp),
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(vertical = 6.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            // Стрелка влево
            IconButton(
                onClick = { navHost.navigate("Exhibition")},
                modifier = Modifier.padding(end = 8.dp)
            ) {
                Icon(
                    imageVector = Icons.Default.ArrowBack,
                    contentDescription = "Назад",
                    tint = Color.Black
                )
            }

            // Текст "Скамейки" по центру
            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("Maps") },
                modifier = Modifier.padding(start = 8.dp)
            ) {
                Icon(
                    imageVector = Icons.Default.ArrowForward,
                    contentDescription = "Перейти к киноафише",
                    tint = Color.Black
                )
            }
        }

        if (loadingBench) {
            Box(
                modifier = Modifier.fillMaxSize(),
                contentAlignment = Alignment.Center
            ) {
                CircularProgressIndicator(modifier = Modifier.size(72.dp))
            }
        } else {
            LazyColumn(
                modifier = Modifier
                    .weight(1f),
                verticalArrangement = Arrangement.spacedBy(6.dp)
            ) {
                items(benchs, key = { bench -> bench.id }) { bench ->
                    Card(
                        modifier = Modifier
                            .width(440.dp)
                            .padding(4.dp), // Отступы для карточки
                        elevation = CardDefaults.cardElevation(0.dp),
                        shape = RoundedCornerShape(55.dp),
                        colors = CardDefaults.cardColors(containerColor = Color.White),
                        border = BorderStroke(0.5.dp, Color.LightGray)
                    ) {
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(10.dp)
                                .padding(start = 2.dp),// Отступы внутри карточки
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            val painter = rememberImagePainter(
                                data = bench.picture,
                                builder = {
                                    crossfade(true)
                                }
                            )

                            Image(
                                painter = painter,
                                contentDescription = "Фото скамейки",
                                modifier = Modifier
                                    .size(88.dp) // Устанавливаем размер фотографии
                                    .clip(CircleShape), // Делаем фото круглым
                                contentScale = ContentScale.Crop
                            )

                            Spacer(modifier = Modifier.width(8.dp)) // Отступ между фото и текстом

                            Column(
                                modifier = Modifier.weight(1f) // Занимаем оставшееся пространство
                            ) {
                                Text(
                                    text = "Район: ${bench.district}",
                                    style = MaterialTheme.typography.titleMedium,
                                    fontSize = 13.sp,
                                    fontFamily = montserratRegular
                                )
                                Text(
                                    text = "Координаты: ${bench.coordinates}",
                                    style = MaterialTheme.typography.titleMedium,
                                    fontSize = 13.sp,
                                    fontFamily = montserratRegular
                                )
                                Text(
                                    text = "Состояние: ${bench.state}",
                                    style = MaterialTheme.typography.titleMedium,
                                    fontSize = 13.sp,
                                    fontFamily = montserratRegular
                                )
                                Text(
                                    text = "Посмотреть на карте",
                                    style = MaterialTheme.typography.titleMedium,
                                    fontWeight = FontWeight.SemiBold,
                                    fontSize = 13.sp,
                                    color = Color(0xFF72C3F1),
                                    modifier = Modifier.clickable { /* Действие при нажатии */ }
                                )
                            }
                        }
                    }
                }
            }
        }
        Panel(navHost)
    }
}