package com.example.oscellamobile.screens

import android.util.Log
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
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.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
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.draw.shadow
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
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.rememberAsyncImagePainter
import com.example.oscellamobile.domain.utlis.Constant
import com.google.accompanist.systemuicontroller.rememberSystemUiController
import io.github.jan.supabase.postgrest.from
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import com.example.oscellamobile.R
import coil.compose.AsyncImagePainter
import coil.request.ImageRequest
import coil.size.Size
import com.example.oscellamobile.models.Advantages_of_the_cloud
import com.example.oscellamobile.models.Cloud_advantage
import com.example.oscellamobile.models.Сloud_gaming
import com.example.oscellamobile.models.Users
import io.github.jan.supabase.gotrue.auth


@Composable
fun CloudList(navHost: NavHostController) {

    var cloud by remember { mutableStateOf<List<Сloud_gaming>>(listOf()) }
    var advantage by remember { mutableStateOf<List<Cloud_advantage>>(listOf()) }
    var cloudadvantage by remember { mutableStateOf<List<Advantages_of_the_cloud>>(listOf()) }
    var user by remember {mutableStateOf<List<Users>>(listOf())}

    LaunchedEffect(Unit) {
        withContext(Dispatchers.IO) {
            try {
                cloud = Constant.supabase.from("Сloud_gaming").select().decodeList<Сloud_gaming>()
                advantage = Constant.supabase.from("Cloud_advantage").select().decodeList<Cloud_advantage>()
                cloudadvantage = Constant.supabase.from("Advantages_of_the_cloud").select().decodeList<Advantages_of_the_cloud>()
                user = Constant.supabase.from("Users").select().decodeList<Users>()
                cloud.forEach { Cloud ->
                    Log.d("C", Cloud.cloud_name)
                }
            } catch (e: Exception) {
                Log.e("C", "Ошибка загрузки данных", e)
            }
        }
    }

    val systemUiController = rememberSystemUiController()

    LaunchedEffect(Unit) {
        systemUiController.isStatusBarVisible = false
        delay(5000)
        systemUiController.isStatusBarVisible = false
    }

    Canvas(
        modifier = Modifier
            .fillMaxWidth()
            .fillMaxHeight()
    ) {
        val gradient = Brush.linearGradient(
            colors = listOf(
                Color(0xFFFF9F1C),
                Color(0xFFE71D36)
            ),
            start = Offset(size.width, 1200f),
            end = Offset(150f, size.height)
        )

        drawRect(brush = gradient)
    }

    Column(
        modifier = Modifier
            .fillMaxWidth()
            .fillMaxHeight()
    ) {
        Spacer(modifier = Modifier.height(10.dp))
        Row {
            Spacer(modifier = Modifier.width(13.dp))
            Text(text = "Osccela", fontSize = 40.sp, fontFamily = kdamFontFamily)
            Spacer(modifier = Modifier.width(145.dp))
            Column(
                verticalArrangement = Arrangement.Center,
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                Image(
                    painter = painterResource(id = R.drawable.personall),
                    contentDescription = "Описание изображения",
                    modifier = Modifier.size(90.dp)
                        .clickable(onClick = {
                            navHost.navigate("PersonalView")
                        })
                )

                val userId = Constant.supabase.auth.currentUserOrNull()?.id
                val userIdString = userId.toString()

                LazyColumn(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    items(user) { US ->
                        if (userIdString == US.user) {
                            Text(
                                US.login,
                                fontFamily = kdamFontFamily,
                                fontSize = 20.sp,
                                color = Color.Black,
                                textAlign = TextAlign.Center,
                                modifier = Modifier.fillMaxWidth()
                            )
                        }
                    }
                }
            }
        }
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .height(70.dp)
                .padding(10.dp, 0.dp, 10.dp, 0.dp)
                .background(color = Color(0xFFFDFFFC), shape = RoundedCornerShape(5.dp)),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Spacer(Modifier.width(10.dp))
            Button(
                onClick = {navHost.navigate("MainWindow/0")},
                modifier = Modifier
                    .shadow(100.dp)
                    .width(93.dp)
                    .height(45.dp)
                    .background(brush = gradientButton, shape = RoundedCornerShape(5.dp)),
                colors = ButtonDefaults.buttonColors(
                    containerColor = Color.Transparent
                )
            ) {
                Box(
                    modifier = Modifier.fillMaxSize(),
                    contentAlignment = Alignment.Center
                ) {
                    Text(
                        "Игры",
                        color = Color(0xFFFDFFFC),
                        fontFamily = playfairdisplay,
                        fontSize = 17.sp
                    )
                }
            }

            Button(
                onClick = {navHost.navigate("CompanyList")},
                modifier = Modifier
                    .shadow(100.dp)
                    .width(135.dp)
                    .height(45.dp)
                    .background(brush = gradientButton, shape = RoundedCornerShape(5.dp)),
                colors = ButtonDefaults.buttonColors(
                    containerColor = Color.Transparent
                )
            ) {
                Box(
                    modifier = Modifier.fillMaxSize(),
                    contentAlignment = Alignment.Center
                ) {
                    Text(
                        "Компании",
                        color = Color(0xFFFDFFFC),
                        fontFamily = playfairdisplay,
                        fontSize = 17.sp
                    )
                }
            }

            Button(
                onClick = {},
                modifier = Modifier
                    .shadow(100.dp)
                    .width(107.dp)
                    .height(45.dp)
                    .background(brush = gradientButton, shape = RoundedCornerShape(5.dp)),
                colors = ButtonDefaults.buttonColors(
                    containerColor = Color.Transparent
                )
            ) {
                Box(
                    modifier = Modifier.fillMaxSize(),
                    contentAlignment = Alignment.Center
                ) {
                    Text(
                        "Облако",
                        color = Color(0xFFFDFFFC),
                        fontFamily = playfairdisplay,
                        fontSize = 17.sp
                    )
                }
            }
            Spacer(Modifier.width(10.dp))
        }
        Spacer(Modifier.height(100.dp))
        LazyColumn {
            items(
                cloud,
                key = { Cloud -> Cloud.id },
            ) { Cloud ->
                CloudItem(
                    cloud = Cloud,
                    advantage = advantage,
                    cloudadvantage = cloudadvantage,
                    navHost = navHost
                )
            }
        }
    }
}

@Composable
fun CloudItem(
    cloud: Сloud_gaming,
    advantage: List<Cloud_advantage>,
    cloudadvantage: List<Advantages_of_the_cloud>,
    navHost: NavHostController
) {
    val imageState = rememberAsyncImagePainter(
        model = ImageRequest.Builder(LocalContext.current).data(cloud.picture)
            .size(Size.ORIGINAL).build()
    ).state

    Card(
        modifier = Modifier
            .padding(20.dp, 10.dp)
            .background(color = Color(0xFFFDFFFC), shape = RoundedCornerShape(15.dp)),
    ) {
        Row(
            modifier = Modifier.padding(10.dp)
        ) {
            Column {
                Text(
                    text = "Плюсы облака:",
                    fontSize = 14.sp,
                    fontFamily = kdamFontFamily,
                    color = Color(0xFF7F807E)
                )

                val CloudId = cloud.id
                val cloudForGame = cloudadvantage.filter { it.id_cloud == CloudId }
                val labelIds = cloudForGame.map { it.id_advantage }
                val labels = labelIds.mapNotNull { id ->
                    advantage.find { it.id == id }
                }
                for (advantage in labels) {
                    Spacer(modifier = Modifier.padding(7.dp))
                    Box(
                        modifier = Modifier
                            .width(107.dp)
                            .background(
                                color = Color(0xFF2EC4B6),
                                shape = RoundedCornerShape(20.dp)
                            ),
                        contentAlignment = Alignment.Center
                    ) {
                        Text(
                            text = advantage.advantage,
                            color = Color(0xFFFDFFFC),
                            fontFamily = caveat,
                            fontSize = 20.sp,
                            textAlign = TextAlign.Center
                        )
                    }
                }
            }

            Spacer(modifier = Modifier.width(10.dp))
            Column(
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                Text(
                    text = cloud.cloud_name,
                    fontSize = 20.sp,
                    fontFamily = kdamFontFamily,
                    color = Color(0xFF7F807E),
                    textAlign = TextAlign.Center
                )

                if (imageState is AsyncImagePainter.State.Success) {
                    Image(
                        painter = imageState.painter,
                        contentDescription = "Описание изображения",
                        modifier = Modifier
                            .width(230.dp)
                            .clip(RoundedCornerShape(20.dp))

                    )
                }
            }
        }
        Column {
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(5.dp)
                    .background(brush = gradientBox, shape = RoundedCornerShape(10.dp))
            ) {
                Text(
                    text = cloud.description,
                    fontSize = 9.sp,
                    textAlign = TextAlign.Center,
                    fontFamily = ibmplexmono
                )
            }
            Spacer(modifier = Modifier.height(5.dp))
        }
        Row(
            modifier = Modifier
                .height(60.dp)
        ) {
            Spacer(modifier = Modifier.width(200.dp))
            Button(
                onClick = {navHost.navigate("AboutCloud/${cloud.id}")},
                modifier = Modifier
                    .background(
                        color = Color(0xFFE71D36),
                        shape = RoundedCornerShape(20.dp)
                    ),
                colors = ButtonDefaults.buttonColors(
                    containerColor = Color.Transparent
                )
            ) {
                Text(
                    text = "Подробности",
                    textAlign = TextAlign.Center,
                    fontFamily = playfairdisplay,
                    fontSize = 16.sp,
                    color = Color(0xFFFDFFFC)
                )
            }
        }
    }
}
