@file:OptIn(ExperimentalMaterial3Api::class)

package com.example.oscellamobile.screens

import android.annotation.SuppressLint
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.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.layout.widthIn
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.foundation.verticalScroll
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Snackbar
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults
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.NavHost
import androidx.navigation.NavHostController
import coil.compose.rememberAsyncImagePainter
import com.example.oscellamobile.domain.utlis.Constant
import com.example.oscellamobile.models.Game
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.compose.rememberImagePainter
import coil.request.ImageRequest
import coil.size.Size
import com.example.oscellamobile.Link
import com.example.oscellamobile.YouTube
import com.example.oscellamobile.models.Comments
import com.example.oscellamobile.models.Game_Cloud
import com.example.oscellamobile.models.Minimum_system_requirements
import com.example.oscellamobile.models.Recommended_system_requirements
import com.example.oscellamobile.models.Screnshot
import com.example.oscellamobile.models.Users
import com.example.oscellamobile.models.Сloud_gaming
import io.github.jan.supabase.gotrue.auth
import io.github.jan.supabase.realtime.Column
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import org.intellij.lang.annotations.JdkConstants
import java.time.format.TextStyle

@Composable
fun AboutGame(navHost: NavHostController, id: Int) {
    var games by remember { mutableStateOf<List<Game>>(listOf()) }
    var min by remember{mutableStateOf<List<Minimum_system_requirements>>(listOf())}
    var rec by remember{mutableStateOf<List<Recommended_system_requirements>>(listOf())}
    var cloudgame by remember{mutableStateOf<List<Game_Cloud>>(listOf())}
    var cloud by remember{mutableStateOf<List<Сloud_gaming>>(listOf())}
    var screen by remember { mutableStateOf<List<Screnshot>>(listOf())}
    var user by remember { mutableStateOf<List<Users>>(listOf()) }
    var comm by remember { mutableStateOf<List<Comments>>(listOf()) }

    LaunchedEffect(Unit) {
        withContext(Dispatchers.IO) {
            try {
                games = Constant.supabase.from("Game").select().decodeList<Game>()
                min = Constant.supabase.from("Minimum_system_requirements").select().decodeList<Minimum_system_requirements>()
                rec = Constant.supabase.from("Recommended_system_requirements").select().decodeList<Recommended_system_requirements>()
                cloudgame = Constant.supabase.from("Game_Cloud").select().decodeList<Game_Cloud>()
                cloud = Constant.supabase.from("Сloud_gaming").select().decodeList<Сloud_gaming>()
                screen = Constant.supabase.from("Screnshot").select().decodeList<Screnshot>()
                user = Constant.supabase.from("Users").select().decodeList<Users>()
                comm = Constant.supabase.from("Comments").select().decodeList<Comments>()
                games.forEach { Game ->
                    Log.d("C", Game.name_game)
                }
            } catch (e: Exception) {
                Log.e("C", "Ошибка загрузки данных", e)
            }
        }
    }

    val filteredGames = games.filter { it.id == id }

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

        LazyColumn {
            items(
                filteredGames,
                key = { game -> game.id }
            ) { game ->
                GameItem(
                    game = game,
                    min = min,
                    rec = rec,
                    gamecloud = cloudgame,
                    cloud = cloud,
                    screen = screen,
                    userrr = user,
                    comm = comm,
                    navHost = navHost
                )
            }
        }
    }
}
@Composable
fun GameItem(
    game: Game,
    min: List<Minimum_system_requirements>,
    rec: List<Recommended_system_requirements>,
    gamecloud: List<Game_Cloud>,
    cloud: List<Сloud_gaming>,
    screen: List<Screnshot>,
    userrr: List<Users>,
    comm: List<Comments>,
    navHost: NavHostController
) {
    val viewModel = Link()
    val imageState = rememberAsyncImagePainter(
        model = ImageRequest.Builder(LocalContext.current).data(game.picture)
            .size(Size.ORIGINAL).build()
    ).state

    Card(
        Modifier.width(400.dp).fillMaxHeight()
            .padding(10.dp, 10.dp, 10.dp, 10.dp)
            .background(color = Color(0xFFFDFFFC), shape = RoundedCornerShape(20.dp)),
    )
    {
        val userId = Constant.supabase.auth.currentUserOrNull()?.id
        val userIdString = userId.toString()
        val userr = userrr.find { it.user == userIdString }
        Column(
            modifier = Modifier.fillMaxWidth().fillMaxHeight()
        ) {
            Column(
                modifier = Modifier.fillMaxWidth(),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                Text(
                    game.name_game,
                    textAlign = TextAlign.Center,
                    fontFamily = kdamFontFamily,
                    fontSize = 30.sp,
                    color = Color(0xFF7F807E)
                )
                Spacer(modifier = Modifier.height(5.dp)) // Space between Text and Image
                if (imageState is AsyncImagePainter.State.Success) {
                    Image(
                        painter = imageState.painter,
                        contentDescription = "Описание изображения",
                        modifier = Modifier
                            .width(380.dp)
                            .clip(RoundedCornerShape(20.dp)),
                    )
                }
            }
            Text(
                text = "Системные требования к игре:",
                textAlign = TextAlign.Left,
                fontFamily = ibmplexmono,
                fontSize = 20.sp,
                color = Color.Black,
            )
            var GameID = game.id
            val cloudingame = gamecloud.filter { it.game == GameID }
            val clouddd = cloudingame.map { it.cloud }
            val clouds = clouddd.mapNotNull { id ->
                cloud.find { it.id == id }
            }
            val pictureforgame = screen.filter { it.game == GameID }
            var minn = min.find { it.id_game == GameID }
            var recc = rec.find { it.id_game == GameID }
            Column(
                modifier = Modifier.padding(5.dp)
            ) {
                if (minn != null) {
                    Text(
                        text = "Минимальные системные требования:",
                        fontFamily = ibmplexmono,
                        fontSize = 10.sp,
                        color = Color.Black,
                        textAlign = TextAlign.Left
                    )
                    Text(
                        text = "·Операционная система: " + minn.OS,
                        fontFamily = ibmplexmono,
                        fontSize = 10.sp,
                        color = Color.Black,
                        textAlign = TextAlign.Left
                    )
                    Text(
                        text = "·Процессор: " + minn.processor,
                        fontFamily = ibmplexmono,
                        fontSize = 10.sp,
                        color = Color.Black,
                        textAlign = TextAlign.Left
                    )
                    Text(
                        text = "·Оперативная память: " + minn.RAM,
                        fontFamily = ibmplexmono,
                        fontSize = 10.sp,
                        color = Color.Black,
                        textAlign = TextAlign.Left
                    )
                    Text(
                        text = "·Видеокарта: " + minn.graphic_card,
                        fontFamily = ibmplexmono,
                        fontSize = 10.sp,
                        color = Color.Black,
                        textAlign = TextAlign.Left
                    )
                    Text(
                        text = "·Свободное место на диске: " + minn.free_space,
                        fontFamily = ibmplexmono,
                        fontSize = 10.sp,
                        color = Color.Black,
                        textAlign = TextAlign.Left
                    )
                }
            }
            Column(
                modifier = Modifier.padding(5.dp)
            ) {
                if (recc != null) {
                    Text(
                        text = "Рекомендуемые системные требования:",
                        fontFamily = ibmplexmono,
                        fontSize = 10.sp,
                        color = Color.Black,
                        textAlign = TextAlign.Left
                    )
                    Text(
                        text = "·Операционная система: " + recc.OS,
                        fontFamily = ibmplexmono,
                        fontSize = 10.sp,
                        color = Color.Black,
                        textAlign = TextAlign.Left
                    )
                    Text(
                        text = "·Процессор: " + recc.processor,
                        fontFamily = ibmplexmono,
                        fontSize = 10.sp,
                        color = Color.Black,
                        textAlign = TextAlign.Left
                    )
                    Text(
                        text = "·Оперативная память: " + recc.RAM,
                        fontFamily = ibmplexmono,
                        fontSize = 10.sp,
                        color = Color.Black,
                        textAlign = TextAlign.Left
                    )
                    Text(
                        text = "·Видеокарта: " + recc.graphic_card,
                        fontFamily = ibmplexmono,
                        fontSize = 10.sp,
                        color = Color.Black,
                        textAlign = TextAlign.Left
                    )
                    Text(
                        text = "·Свободное место на диске: " + recc.free_space,
                        fontFamily = ibmplexmono,
                        fontSize = 10.sp,
                        color = Color.Black,
                        textAlign = TextAlign.Left
                    )
                }
            }
            Column(
                modifier = Modifier.padding(5.dp, 0.dp, 0.dp, 0.dp)
            ) {
                Text(
                    text = "Доступность игры:",
                    textAlign = TextAlign.Left,
                    fontFamily = ibmplexmono,
                    fontSize = 20.sp,
                    color = Color.Black,
                )
                Text(
                    text = "Официальный источник:",
                    fontFamily = ibmplexmono,
                    fontSize = 15.sp,
                    color = Color.Black,
                    textAlign = TextAlign.Left
                )
                viewModel.LinkText(game.link_oficial)
                if (game.link_torrent != null) {
                    Text(
                        text = "Сторонний источник:",
                        fontFamily = ibmplexmono,
                        fontSize = 15.sp,
                        color = Color.Black,
                        textAlign = TextAlign.Left
                    )
                    viewModel.LinkText(game.link_torrent)
                }
            }
            Column(
                modifier = Modifier.padding(5.dp, 0.dp, 0.dp, 0.dp)
            )
            {
                Text(
                    text = "Наличие игры в облачном гейминге:",
                    textAlign = TextAlign.Left,
                    fontFamily = ibmplexmono,
                    fontSize = 20.sp,
                    color = Color.Black,
                )
                for (cloud in clouds) {
                    viewModel.LinkText(cloud.link)
                }
            }
            Column(
                modifier = Modifier.padding(5.dp, 0.dp, 0.dp, 0.dp)
            ) {
                if (game.description != null) {
                    Text(
                        text = "Описание игры:",
                        textAlign = TextAlign.Left,
                        fontFamily = ibmplexmono,
                        fontSize = 20.sp,
                        color = Color.Black,
                    )
                    Text(
                        game.description,
                        textAlign = TextAlign.Center,
                        fontFamily = ibmplexmono,
                        fontSize = 12.sp,
                        color = Color.Black,
                    )
                }
            }
            Column(
                modifier = Modifier.padding(5.dp, 0.dp, 0.dp, 0.dp)
            ) {
                Text(
                    text = "Скриншоты из игры:",
                    textAlign = TextAlign.Left,
                    fontFamily = ibmplexmono,
                    fontSize = 20.sp,
                    color = Color.Black,
                )
                Row(
                    modifier = Modifier
                        .background(color = Color(0xFFFDFFFC), shape = RoundedCornerShape(20.dp))
                        .height(220.dp)
                        .fillMaxWidth(),
                    horizontalArrangement = Arrangement.Center,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    LazyRow(
                        modifier = Modifier.fillMaxWidth()
                    ) {
                        items(pictureforgame) { screenshot ->
                            Image(
                                painter = rememberImagePainter(screenshot.picture),
                                contentDescription = "Описание изображения",
                                modifier = Modifier
                                    .width(380.dp)
                                    .height(200.dp)
                                    .clip(RoundedCornerShape(20.dp))
                                    .padding(4.dp)
                            )
                        }
                    }
                }
            }
            Column(
                modifier = Modifier.padding(5.dp, 0.dp, 0.dp, 0.dp)
            )
            {
                Text(
                    text = "Трейлер игры:",
                    textAlign = TextAlign.Left,
                    fontFamily = ibmplexmono,
                    fontSize = 20.sp,
                    color = Color.Black,
                )
                Row(
                    modifier = Modifier
                        .background(color = Color(0xFFFDFFFC), shape = RoundedCornerShape(20.dp))
                        .height(220.dp)
                        .fillMaxWidth(),
                    horizontalArrangement = Arrangement.Center,
                    verticalAlignment = Alignment.CenterVertically
                )
                {
                    val viewModel = YouTube()
                    if (game.video != null) {
                        viewModel.VideoPlayerFromUrl(game.video)
                    }
                }
            }
            Column(modifier = Modifier.padding(5.dp).fillMaxHeight()) {
                Text("Оставьте отзыв:", textAlign = TextAlign.Left, fontFamily = ibmplexmono, fontSize = 20.sp, color = Color.Black)
                var rating by remember { mutableStateOf(0) }
                val comment = remember { mutableStateOf("") }

                Column(
                    modifier = Modifier
                        .background(color = Color.White, shape = RoundedCornerShape(20.dp))
                        .padding(16.dp),
                    horizontalAlignment = Alignment.CenterHorizontally,
                    verticalArrangement = Arrangement.Center
                ) {
                    Row(horizontalArrangement = Arrangement.Center) {
                        for (i in 1..5) {
                            val color = if (i <= rating) Color(0xFFFF9F1C) else Color.Gray
                            val size = 40.dp

                            Canvas(
                                modifier = Modifier
                                    .size(size)
                                    .clickable(onClick = { rating = i })
                            ) {
                                drawStar(center = center, radius = size.toPx() / 2, color = color)
                            }
                        }
                    }

                    Spacer(modifier = Modifier.height(16.dp))

                    TextField(
                        value = comment.value,
                        onValueChange = { newText -> comment.value = newText },
                        placeholder = { Text("Comment", fontSize = 24.sp, fontFamily = kdamFontFamily) },
                        shape = RoundedCornerShape(20.dp),
                        colors = TextFieldDefaults.textFieldColors(
                            focusedIndicatorColor = Color.Transparent,
                            unfocusedIndicatorColor = Color.Transparent
                        ),
                        textStyle = androidx.compose.ui.text.TextStyle(
                            fontSize = 20.sp,
                            fontFamily = kdamFontFamily
                        ),
                        modifier = Modifier.width(330.dp)
                    )

                    var showReviewScreen by remember { mutableStateOf(false) }
                    if (showReviewScreen) {
                        ReviewScreen(navHost, userrr, game, rating, comment.value, onDismiss = { showReviewScreen = false })
                    }

                    Button(
                        onClick = {
                            showReviewScreen = true
                        },
                        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)
                        )
                    }
                }

                val comments = comm.filter { it.id_game == GameID }
                LazyRow(
                ) {
                    items(comments) { Comm ->
                        val user = userrr.find { it.id == Comm.id_user }
                        Column {
                            Row(
                                modifier = Modifier.background(
                                    color = Color.White,
                                    shape = RoundedCornerShape(20.dp)
                                )
                                    .widthIn(max = 400.dp)
                                    .fillMaxHeight()
                                    .padding(5.dp, 5.dp),
                                horizontalArrangement = Arrangement.Center
                            ) {
                                Column(
                                    verticalArrangement = Arrangement.Center
                                ) {
                                    Row {
                                        Star(Comm.estimation)
                                    }
                                    Image(
                                        painter = painterResource(id = R.drawable.personall),
                                        contentDescription = "Описание изображения",
                                        modifier = Modifier.size(50.dp)
                                    )
                                    Text(
                                        user?.login ?: "",
                                        fontFamily = kdamFontFamily,
                                        fontSize = 15.sp,
                                        color = Color.Black
                                    )
                                }
                                Row(
                                    horizontalArrangement = Arrangement.Center,
                                    modifier = Modifier.padding(5.dp, 10.dp, 0.dp, 0.dp)
                                ) {
                                    Text(
                                        Comm.description,
                                        fontFamily = kdamFontFamily,
                                        fontSize = 20.sp,
                                        color = Color.Black,
                                        textAlign = TextAlign.Center
                                    )

                                }
                                Spacer(modifier = Modifier.width(50.dp))
                            }
                            if(user?.user != null) {
                                if(user.user == userIdString)
                                {
                                    Button(
                                        onClick = {
                                            CoroutineScope(Dispatchers.Main).launch {
                                                deleteComm(userIdString, Comm.description, userrr, navHost, game)
                                            }
                                        },
                                        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)
                                        )
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}


suspend fun Comment(user: Int, game: Int, est: Int, desc: String)
{
    val new_comm = Comments(
        id_user = user,
        id_game = game,
        estimation = est,
        description = desc
    )
    withContext(Dispatchers.IO) {
    Constant.supabase.from("Comments").insert(new_comm)
    }
}

@Composable
fun Star(est: Int)
{
    for(i in 1..est) {
        val size = 10.dp
        Canvas(
            modifier = Modifier
                .size(30.dp)
        ) {
            drawStar(
                center = center,
                radius = size.toPx() / 2,
                color = Color(0xFFFF9F1C)
            )
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
suspend fun deleteComm(user: String, Comm: String, User: List<Users>, navHost: NavHostController, game: Game)
{
    val user = User.find { it.user == user }
    if(user != null) {
        withContext(Dispatchers.IO) {
            Constant.supabase.from("Comments").delete {
                filter {
                    (Comments::id_user eq user.id)
                    (Comments::description eq Comm)
                }
            }
        }
        navHost.navigate("AboutGame/${game.id}")
    }
}

@SuppressLint("CoroutineCreationDuringComposition")
@Composable
fun ReviewScreen(
    navHost: NavHostController,
    userr: List<Users>,
    game: Game,
    rating: Int,
    comment: String,
    onDismiss: () -> Unit
) {
    val userId = Constant.supabase.auth.currentUserOrNull()?.id
    val userIdString = userId.toString()
    val userr = userr.find { it.user == userIdString }

    var isCommenting by remember { mutableStateOf(false) }
    var snackbarVisible by remember { mutableStateOf(false) }
    var snackbarMessage by remember { mutableStateOf("") }

    if (rating == 0 || comment.isEmpty()) {
        snackbarMessage = "Пожалуйста, поставьте оценку и напишите комментарий."
        snackbarVisible = true
    } else {
        isCommenting = true
        CoroutineScope(Dispatchers.Main).launch {
            Comment(userr?.id ?: 0, game.id, rating, comment)
            isCommenting = false
            onDismiss()
            navHost.navigate("AboutGame/${game.id}")
        }
    }

    if (snackbarVisible) {
        Snackbar(
            action = {
                Button(onClick = {
                    snackbarVisible = false
                    onDismiss()
                },modifier = Modifier
                    .background(color = Color(0xFFE71D36), shape = RoundedCornerShape(20.dp)),
                    colors = ButtonDefaults.buttonColors(containerColor = Color.Transparent)) {
                    Text("Закрыть")
                }
            },
            modifier = Modifier.padding(8.dp)
        ) { Text(snackbarMessage,
            textAlign = TextAlign.Center,
            fontFamily = playfairdisplay,
            fontSize = 16.sp,
            color = Color(0xFFFDFFFC)) }
    }
}


