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.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
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.LazyRow
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.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.example.oscellamobile.models.Game
import io.github.jan.supabase.postgrest.from
import kotlinx.coroutines.Dispatchers
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.Link
import com.example.oscellamobile.models.Game_Cloud
import com.example.oscellamobile.models.Users
import com.example.oscellamobile.models.Сloud_gaming
import io.github.jan.supabase.gotrue.auth

@Composable
fun AboutCloud(navHost: NavHostController, id: Int) {
    var clouds by remember { mutableStateOf<List<Сloud_gaming>>(listOf()) }
    var game by remember { mutableStateOf<List<Game>>(listOf()) }
    var gamecloud by remember { mutableStateOf<List<Game_Cloud>>(listOf()) }
    var user by remember{mutableStateOf<List<Users>>(listOf())}
    LaunchedEffect(Unit) {
        withContext(Dispatchers.IO) {
            try {
                clouds = Constant.supabase.from("Сloud_gaming").select().decodeList<Сloud_gaming>()
                game = Constant.supabase.from("Game").select().decodeList<Game>()
                gamecloud = Constant.supabase.from("Game_Cloud").select().decodeList<Game_Cloud>()
                user = Constant.supabase.from("Users").select().decodeList<Users>()
                clouds.forEach { Cloud ->
                    Log.d("C", Cloud.cloud_name)
                }
            } catch (e: Exception) {
                Log.e("C", "Ошибка загрузки данных", e)
            }
        }
    }

    val filteredCloud = clouds.filter { it.id == id}

    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()
                            )
                        }
                    }
                }
            }
        }
        LazyColumn {
            items(
                filteredCloud,
                key = { cloud -> cloud.id }
            ) { cloud ->
                CloudItem(cloud, game, gamecloud, navHost)
            }
        }
    }
}

@Composable
fun CloudItem(
    cloud: Сloud_gaming,
    game: List<Game>,
    gamecloud: List<Game_Cloud>,
    navHost: NavHostController
) {
    val viewModel = Link()
    val imageState = rememberAsyncImagePainter(
        model = ImageRequest.Builder(LocalContext.current).data(cloud.picture)
            .size(Size.ORIGINAL).build()
    ).state

    Card(
        Modifier.width(400.dp)
            .padding(10.dp, 10.dp, 10.dp, 10.dp)
            .background(color = Color(0xFFFDFFFC), shape = RoundedCornerShape(20.dp)),
    )
    {
        Column(
            modifier = Modifier.fillMaxWidth()
        ) {
            Column(
                modifier = Modifier.fillMaxWidth(),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                Text(
                    cloud.cloud_name,
                    textAlign = TextAlign.Center,
                    fontFamily = kdamFontFamily,
                    fontSize = 30.sp,
                    color = Color(0xFF7F807E)
                )
                Spacer(modifier = Modifier.height(10.dp))
                if (imageState is AsyncImagePainter.State.Success) {
                    Image(
                        painter = imageState.painter,
                        contentDescription = "Описание изображения",
                        modifier = Modifier
                            .width(300.dp)
                            .clip(RoundedCornerShape(20.dp))
                    )
                }
            }
                Spacer(modifier = Modifier.height(10.dp))
                Column(
                    modifier = Modifier.padding(5.dp, 0.dp, 0.dp, 5.dp)
                ) {
                    Text(
                        text = "Ссылка:",
                        textAlign = TextAlign.Left,
                        fontFamily = ibmplexmono,
                        fontSize = 20.sp,
                        color = Color.Black,
                    )
                    Spacer(modifier = Modifier.height(5.dp))
                    viewModel.LinkText(cloud.link)
                }

                Spacer(modifier = Modifier.height(10.dp))
                if (cloud.desc != null) {
                    Column(
                        modifier = Modifier.padding(5.dp, 0.dp, 0.dp, 5.dp)
                    ) {
                        Text(
                            text = "Описание облачного гейминга:",
                            textAlign = TextAlign.Left,
                            fontFamily = ibmplexmono,
                            fontSize = 20.sp,
                            color = Color.Black,
                        )
                        Spacer(modifier = Modifier.height(5.dp))
                        Text(
                            cloud.desc!!,
                            textAlign = TextAlign.Center,
                            fontFamily = ibmplexmono,
                            fontSize = 12.sp,
                            color = Color.Black
                        )
                    }
                }
                Spacer(modifier = Modifier.height(10.dp))
                if (cloud.Features != null) {
                    Column(
                        modifier = Modifier.padding(5.dp, 0.dp, 0.dp, 5.dp)
                    ) {
                        Text(
                            text = "Особенности:",
                            textAlign = TextAlign.Left,
                            fontFamily = ibmplexmono,
                            fontSize = 20.sp,
                            color = Color.Black,
                        )
                        Spacer(modifier = Modifier.height(5.dp))
                        Text(
                            cloud.Features!!,
                            textAlign = TextAlign.Left,
                            fontFamily = ibmplexmono,
                            fontSize = 12.sp,
                            color = Color.Black
                        )
                    }
                }
                val CloudId = cloud.id
                val gameincloud = gamecloud.filter { it.cloud == CloudId }
                var gamee = gameincloud.map { it.game }
                val games = gamee.mapNotNull { id ->
                    game.find { it.id == id }
                }
                if (!games.isEmpty()) {
                    Text(
                        text = "Игры:",
                        textAlign = TextAlign.Left,
                        fontFamily = ibmplexmono,
                        fontSize = 20.sp,
                        color = Color.Black,
                    )
                    Row(
                        horizontalArrangement = Arrangement.Center,
                        verticalAlignment = Alignment.CenterVertically
                    ) {

                        LazyRow(
                            modifier = Modifier.background(Color.Transparent)
                        ) {
                            items(games) { games ->
                                Card(

                                    modifier = Modifier.background(
                                        color = Color.White,
                                        shape = RoundedCornerShape(20.dp)
                                    )
                                        .padding(30.dp, 30.dp, 30.dp, 30.dp),

                                    ) {
                                    Column(
                                        verticalArrangement = Arrangement.Center,
                                        modifier = Modifier.background(Color.Transparent)
                                    ) {
                                        val imageState1 = rememberAsyncImagePainter(
                                            model = ImageRequest.Builder(LocalContext.current)
                                                .data(games.picture)
                                                .size(Size.ORIGINAL).build()
                                        ).state
                                        Spacer(modifier = Modifier.height(5.dp))
                                        Text(
                                            games.name_game,
                                            fontSize = 20.sp,
                                            fontFamily = kdamFontFamily,
                                            color = Color(0xFF7F807E),
                                            modifier = Modifier.background(Color.Transparent),
                                            textAlign = TextAlign.Center
                                        )
                                        if (imageState1 is AsyncImagePainter.State.Success) {
                                            Image(
                                                painter = imageState1.painter,
                                                contentDescription = "Описание изображения",
                                                modifier = Modifier
                                                    .width(300.dp)
                                                    .clip(RoundedCornerShape(20.dp))
                                                    .background(Color.Transparent)
                                            )
                                        }
                                        Spacer(modifier = Modifier.height(7.dp))
                                        Button(
                                            onClick = { navHost.navigate("AboutGame/${games.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)
                                            )
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

        }
    }
}