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.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.NavController
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.Favourites
import com.example.oscellamobile.models.Favorite
import com.example.oscellamobile.models.Users
import io.github.jan.supabase.gotrue.auth
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch

@Composable
fun PersonalView (navHost: NavHostController) {
    var user by remember{mutableStateOf<List<Users>>(listOf())}
    var game by remember { mutableStateOf<List<Game>>(listOf()) }
    var fav by remember { mutableStateOf<List<Favorite>>(listOf()) }


    val gradientButton1 = Brush.linearGradient(
        colors = listOf(
            Color(0xFF2EC4B6),
            Color(0xFFE71D36)
        ),
        start = Offset(30f, 30f),
        end = Offset(200f, 200f)
    )

    LaunchedEffect(Unit) {
        withContext(Dispatchers.IO) {
            try {
                user = Constant.supabase.from("Users").select().decodeList<Users>()
                game = Constant.supabase.from("Game").select().decodeList<Game>()
                fav = Constant.supabase.from("Favorite").select().decodeList<Favorite>()
                user.forEach { User ->
                    Log.d("C", User.user)
                }
            } catch (e: Exception) {
                Log.e("C", "Ошибка загрузки данных", e)
            }
        }
    }

    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(150.dp)
                )

                val userId = Constant.supabase.auth.currentUserOrNull()?.id
                val userIdString = userId.toString()
                user = user.filter { it.user ==  userIdString}
                var UserId = user.find { it.user == userIdString }
                fav = fav.filter { it.id_user == UserId?.id }
                LazyColumn(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    items(user) { US ->
                            Text(
                                US.login,
                                fontFamily = kdamFontFamily,
                                fontSize = 20.sp,
                                color = Color.Black,
                                textAlign = TextAlign.Center,
                                modifier = Modifier.fillMaxWidth()
                            )
                        }
                }
                Button(onClick = {
                    navHost.navigate("Auth") {
                        popUpTo("Auth") { inclusive = true }
                    }
                },
                    modifier = Modifier
                        .background(
                            brush = gradientButton1, shape = RoundedCornerShape(20.dp)
                        )
                        .width(200.dp),
                    colors = ButtonDefaults.buttonColors(
                        containerColor = Color.Transparent
                    )) {
                    Text( text = "Выйти",
                        textAlign = TextAlign.Center,
                        fontFamily = kdamFontFamily,
                        fontSize = 24.sp,
                        color = Color(0xFFFDFFFC))
                }
                Spacer(modifier = Modifier.height(50.dp))
                Box(
                    modifier = Modifier.background(color = Color.White, shape = RoundedCornerShape(5.dp))
                        .fillMaxWidth()
                ){
                    Text(
                        text = " Избранное:",
                        fontSize = 25.sp,
                        fontFamily = ibmplexmono,
                        color = Color(0xFFFF9F1C),
                        textAlign = TextAlign.Left
                    )
                }
                LazyRow(
                    modifier = Modifier.background(color = Color.White)
                ) {
                    items(
                        game,
                        key = { Game -> Game.id }
                    ) { Game ->
                        FavList(Game, fav, user, navHost)
                    }
                }
            }
    }
}

@Composable
fun FavList(
    game: Game,
    fav: List<Favorite>,
    user: List<Users>,
    navHost: NavController
) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .height(260.dp)
            .padding(10.dp, 0.dp, 10.dp, 0.dp)
            .background(color = Color(0xFFFDFFFC), shape = RoundedCornerShape(20.dp))
    ) {
        val GameId = game.id
        val favGame = fav.find { it.id_game == GameId }
        Box(
            modifier = Modifier.fillMaxSize()
                .background(color = Color.White),
            contentAlignment = Alignment.Center,
        ) {
            val imageState = rememberAsyncImagePainter(
                model = ImageRequest.Builder(LocalContext.current).data(game.picture)
                    .size(Size.ORIGINAL).build()
            ).state

                if (favGame?.id_game == game.id) {
                    Column(
                        horizontalAlignment = Alignment.CenterHorizontally,
                        verticalArrangement = Arrangement.Center
                    ) {
                        Row {
                            Text(
                                game.name_game,
                                fontSize = 20.sp,
                                fontFamily = kdamFontFamily,
                                color = Color(0xFF7F807E),
                                textAlign = TextAlign.Center
                            )
                            val userId = Constant.supabase.auth.currentUserOrNull()?.id
                            val favv = game.favourites
                            val userIdString = userId.toString()
                            val userr = user.find { it.user == userIdString }
                            val viewModel = Favourites()
                            var isOrange by remember { mutableStateOf(true) }


                            val size = 50.dp
                            val buttonColor = if (isOrange) Color(0xFFFF9F1C) else Color.Gray

                            Spacer(modifier = Modifier.width(30.dp))

                            Canvas(
                                modifier = Modifier
                                    .size(30.dp)
                                    .clickable(onClick = {
                                        isOrange = !isOrange
                                        if (isOrange) {
                                            if (userr != null) {
                                                CoroutineScope(Dispatchers.Main).launch {
                                                    viewModel.addToFavorites(
                                                        game.id,
                                                        userr.id,
                                                        navHost,
                                                        favv,
                                                        "PersonalView"
                                                    )
                                                }
                                            }
                                        } else {
                                            if (userr != null) {
                                                CoroutineScope(Dispatchers.Main).launch {
                                                    viewModel.removeFromFavorites(
                                                        game.id,
                                                        userr.id,
                                                        navHost,
                                                        favv,
                                                        "PersonalView"
                                                    )
                                                }
                                            }
                                        }
                                    })
                            ) {
                                drawStar(
                                    center = center,
                                    radius = size.toPx() / 2,
                                    color = buttonColor
                                )
                            }
                        }
                        if (imageState is AsyncImagePainter.State.Success) {
                            Image(
                                painter = imageState.painter,
                                contentDescription = "Описание изображения",
                                modifier = Modifier
                                    .width(280.dp)
                                    .clip(RoundedCornerShape(20.dp))
                            )
                        }
                        Button(
                            onClick = { navHost.navigate("AboutGame/${game.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)
                            )
                        }
                    }
                }
            }
        }
    }
