package com.example.oscellamobile.screens

import android.util.Log
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
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.material.DropdownMenu
import androidx.compose.material.DropdownMenuItem
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.ExperimentalMaterial3Api
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.graphics.drawscope.DrawScope
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
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 kotlin.math.cos
import kotlin.math.sin
import com.example.oscellamobile.R
import com.example.oscellamobile.models.Company
import coil.compose.AsyncImagePainter
import coil.request.ImageRequest
import coil.size.Size
import com.example.oscellamobile.Favourites
import com.example.oscellamobile.domain.utlis.Constant.supabase
import com.example.oscellamobile.models.Age_rating
import com.example.oscellamobile.models.Basic_labels
import com.example.oscellamobile.models.Favorite
import com.example.oscellamobile.models.Genre
import com.example.oscellamobile.models.Label
import com.example.oscellamobile.models.Users
import io.github.jan.supabase.gotrue.auth
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch


val kdamFontFamily = FontFamily(Font(R.font.kdam))
val playfairdisplay = FontFamily(Font(R.font.playfair))
val caveat = FontFamily(Font(R.font.caveat))
val ibmplexmono = FontFamily(Font(R.font.ibm))

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



val gradientBox = Brush.linearGradient(
    colors = listOf(
        Color(0xFFFDFFFC),
        Color(0xFF2EC4B6)
    ),
    start = Offset(0f, 0f)
)

@Composable
fun MainWindow(navHost: NavHostController, flag: Int) {

    var games by remember { mutableStateOf<List<Game>>(listOf()) }
    var сompany by remember { mutableStateOf<List<Company>>(listOf()) }
    var labels by remember{ mutableStateOf<List<Label>>(listOf()) }
    var basiclabels by remember{ mutableStateOf<List<Basic_labels>>(listOf()) }
    var age by remember{ mutableStateOf<List<Age_rating>>(listOf()) }
    var genres by remember{ mutableStateOf<List<Genre>>(listOf()) }
    var user by remember{mutableStateOf<List<Users>>(listOf())}
    var fav by remember { mutableStateOf<List<Favorite>>(listOf()) }

    LaunchedEffect(Unit) {
        withContext(Dispatchers.IO) {
            try {
                сompany = Constant.supabase.from("Company").select().decodeList<Company>()
                games = Constant.supabase.from("Game").select().decodeList<Game>()
                labels = Constant.supabase.from("Label").select().decodeList<Label>()
                basiclabels = Constant.supabase.from("Basic_labels").select().decodeList<Basic_labels>()
                age = Constant.supabase.from("Age_rating").select().decodeList<Age_rating>()
                genres = Constant.supabase.from("Genre").select().decodeList<Genre>()
                user = Constant.supabase.from("Users").select().decodeList<Users>()
                fav = Constant.supabase.from("Favorite").select().decodeList<Favorite>()
                games.forEach { Game ->
                    Log.d("C", Game.name_game)
                }
            } catch (e: Exception) {
                Log.e("C", "Ошибка загрузки данных", e)
            }
        }
    }

    val systemUiController = rememberSystemUiController()

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

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

    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 {
            val userId = Constant.supabase.auth.currentUserOrNull()?.id
            val userIdString = userId.toString()
            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
            ) {
                if(flag == 0) {
                    Image(
                        painter = painterResource(id = R.drawable.personall),
                        contentDescription = "Описание изображения",
                        modifier = Modifier.size(90.dp)
                            .clickable(onClick = {
                                navHost.navigate("PersonalView")
                            })
                    )
                    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()
                                )
                            }
                        }
                    }
                }
                else{
                    Button(
                        onClick = {navHost.navigate("Auth")},
                        modifier = Modifier
                            .width(100.dp)
                            .height(40.dp)
                            .background(brush = gradientButton1, shape = RoundedCornerShape(20.dp)),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = Color.Transparent
                        )
                    ) {
                        Text(
                            text = "Войти",
                            textAlign = TextAlign.Center,
                            fontFamily = playfairdisplay,
                            fontSize = 16.sp,
                            color = Color(0xFFFDFFFC)
                        )
                    }
                }
            }
        }
        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 = {},
                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 =
                if(flag == 0) {
                    { navHost.navigate("CompanyList") }
                }
                else{
                    { navHost.navigate("Auth") }
                },
                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 =
                if(flag == 0) {
                    { navHost.navigate("CloudList") }
                }
                else{
                    { navHost.navigate("Auth") }
                },
                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))
        }
        var list = ComboBoxExample(genres, сompany, games)
        if(list.isEmpty())
        {
            list = games
        }
        Spacer(Modifier.height(50.dp))
        LazyColumn {
            items(
                list,
                key = { Game -> Game.id },
            ) { Game ->
                GameItem(
                    game = Game,
                    company = сompany,
                    label = labels,
                    basic = basiclabels,
                    age = age,
                    genre = genres,
                    navHost = navHost,
                    user = user,
                    fav = fav,
                    flag = flag
                )
            }
        }
    }
}

@Composable
    fun GameItem(
        game: Game,
        company: List<Company>,
        label: List<Label>,
        basic: List<Basic_labels>,
        age: List<Age_rating>,
        genre: List<Genre>,
        navHost: NavHostController,
        user: List<Users>,
        fav: List<Favorite>,
        flag: Int
    ) {
    val imageState = rememberAsyncImagePainter(
        model = ImageRequest.Builder(LocalContext.current).data(game.picture)
            .size(Size.ORIGINAL).build()
    ).state

    Card(
        modifier = Modifier
            .padding(20.dp, 10.dp)
            .background(color = Color(0xFFFDFFFC), shape = RoundedCornerShape(15.dp)),
    ) {
        Row {
            Spacer(Modifier.width(10.dp))
            var viewModel = Favourites()
            Column {
                val companyId = game.company
                val companyy = company.find { it.id == companyId }
                if (companyy != null) {
                    Text(
                        "${companyy?.name_company}",
                        fontSize = 20.sp,
                        fontFamily = kdamFontFamily,
                        color = Color(0xFF2EC4B6)
                    )
                    val genreId = game.genre
                    val genree = genre.find { it.id == genreId }
                    if(genree != null) {
                        Text(
                            "${genree?.genre_name}",
                            fontSize = 12.sp,
                            fontFamily = kdamFontFamily,
                            color = Color(0xFFE71D36)
                        )
                    }
                    Spacer(Modifier.width(20.dp))
                    Column {
                        Text(
                            text = "Основные метки:",
                            fontSize = 14.sp,
                            fontFamily = kdamFontFamily,
                            color = Color(0xFF7F807E)
                        )
                        Column(
                        ) {
                            val GameID = game.id
                            val labelsForGame = basic.filter { it.id_game == GameID }
                            val labelIds = labelsForGame.map { it.id_label }
                            val labels = labelIds.mapNotNull { id ->
                                label.find { it.id == id }
                            }
                            for (label 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(
                                        "${label.label_name}",
                                        color = Color(0xFFFDFFFC),
                                        fontFamily = caveat,
                                        fontSize = 20.sp,
                                        textAlign = TextAlign.Center
                                    )
                                }
                            }
                        }
                    }
                }
            }
            Column {
                Row {
                    Spacer(Modifier.width(45.dp))
                    Box(
                        modifier = Modifier
                            .width(130.dp)
                            .height(30.dp)
                            .border(
                                BorderStroke(2.dp, Color(0x80B0B0B0)),
                                shape = RoundedCornerShape(15.dp)
                            )
                    )
                    {

                        Text(
                            text = if (game.favourites == null) {
                                "Избранное: 0"
                            } else {
                                "Избранное: ${game.favourites}"
                            },
                            fontSize = 16.sp,
                            fontFamily = playfairdisplay,
                            color = Color(0xFFFF9F1C),
                            modifier = Modifier.align(Alignment.Center)
                        )
                    }
                    val size = 31.dp


                    val userId = Constant.supabase.auth.currentUserOrNull()?.id
                    val favv = game.favourites
                    val userIdString = userId.toString()
                    val userr = user.find { it.user == userIdString }

                    var isOrange by remember { mutableStateOf(false) }

                    if (userr != null) {
                        isOrange = fav.any { it.id_game == game.id && it.id_user == userr.id }
                    }

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

                    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, "MainWindow")
                                        }
                                    }
                                } else {
                                    if (userr != null) {
                                        CoroutineScope(Dispatchers.Main).launch {
                                            viewModel.removeFromFavorites(game.id, userr.id, navHost, favv, "MainWindow")
                                        }
                                    }
                                }
                            })
                    ) {
                        drawStar(
                            center = center,
                            radius = size.toPx() / 2,
                            color = buttonColor
                        )
                    }
                }
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.Center,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(
                        game.name_game,
                        fontSize = 20.sp,
                        fontFamily = kdamFontFamily,
                        color = Color(0xFF7F807E),
                    )
                    Spacer(Modifier.width(10.dp))
                    val AgeId = game.age_rating
                    val agee = age.find { it.id == AgeId }
                    if (agee != null) {
                        Text(
                            agee.rating,
                            fontSize = 20.sp,
                            fontFamily = kdamFontFamily,
                            color = Color(0xFFE71D36),
                        )
                    }
                }
                    if (imageState is AsyncImagePainter.State.Success) {
                        Image(
                            painter = imageState.painter,
                            contentDescription = "Описание изображения",
                            modifier = Modifier
                                .width(280.dp)
                                .clip(RoundedCornerShape(20.dp))
                        )
                    }
                }

            }

            Column {
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(5.dp)
                        .background(brush = gradientBox, shape = RoundedCornerShape(10.dp))
                ) {
                    Text(
                        game.short_description,
                        fontSize = 9.sp,
                        textAlign = TextAlign.Center,
                        fontFamily = ibmplexmono
                    )
                }
                Spacer(modifier = Modifier.height(5.dp))
            }
            Row(
                modifier = Modifier
                    .height(60.dp),

                ) {
                Box(
                    modifier = Modifier
                        .width(130.dp)
                        .height(40.dp)
                        .padding(5.dp, 5.dp, 0.dp, 0.dp)
                        .border(
                            BorderStroke(2.dp, Color(0x80B0B0B0)),
                            shape = RoundedCornerShape(15.dp)
                        ),
                )
                {
                    Text(
                        text = if (game.views == null) {
                            "Просмотры: 0"
                        } else {
                            "Просмотры: ${game.views}"
                        },
                        fontSize = 15.sp,
                        fontFamily = playfairdisplay,
                        color = Color(0xFFE71D36),
                        modifier = Modifier.align(Alignment.Center)
                    )
                }
                Spacer(modifier = Modifier.width(70.dp))
                Button(
                    onClick = {
                        if (flag == 0) {
                            CoroutineScope(Dispatchers.Main).launch {
                                if(game.views == null) {
                                    addToView(game.id, 0, navHost)
                                }
                                else
                                {
                                    addToView(game.id, game.views, navHost)
                                }
                            }
                            navHost.navigate("AboutGame/${game.id}")
                        } else {
                            navHost.navigate("Auth")
                        }
                    },
                    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)
                    )
                }
            }
        }
    }


fun DrawScope.drawStar(center: Offset, radius: Float, color: Color) {
    val path = androidx.compose.ui.graphics.Path()
    val points = 5
    val angle = 2 * Math.PI / points
    val innerRadius = radius / 2.5f

    for (i in 0 until points * 2) {
        val r = if (i % 2 == 0) radius else innerRadius
        val x = center.x + r * cos(i * angle - Math.PI / 2)
        val y = center.y + r * sin(i * angle - Math.PI / 2)

        if (i == 0) {
            path.moveTo(x.toFloat(), y.toFloat())
        } else {
            path.lineTo(x.toFloat(), y.toFloat())
        }
    }
    path.close()
    drawPath(path, color)
}

fun FilterGenre(games: List<Game>, genre: Int): List<Game> {
    return games.filter { it.genre == genre }
}

fun FilterCompany(games: List<Game>, company: Int): List<Game> {
    return games.filter { it.company == company }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ComboBoxExample(genres: List<Genre>, companies: List<Company>, games: List<Game>): List<Game> {
    var expanded by remember { mutableStateOf(false) }
    var filteredGames by remember { mutableStateOf(games) }
    var selectedGenre by remember { mutableStateOf<Genre?>(null) }
    var selectedCompany by remember { mutableStateOf<Company?>(null) }
    var filterByGenre by remember { mutableStateOf(true) }

    Box {
        Button(
            onClick = { expanded = true },
            modifier = Modifier
                .shadow(100.dp)
                .background(brush = gradientButton, shape = RoundedCornerShape(20.dp)),
            colors = ButtonDefaults.buttonColors(
                containerColor = Color.Transparent
            )
        ) {
            Text(
                text = when {
                    filteredGames.isEmpty() -> "Нет подходящих игр"
                    selectedGenre != null -> "Жанр: ${selectedGenre!!.genre_name}"
                    selectedCompany != null -> "Компания: ${selectedCompany!!.name_company}"
                    else -> "Фильтр"
                },
                modifier = Modifier.padding(16.dp),
                color = Color.White,
                fontFamily = playfairdisplay,
                fontSize = 20.sp
            )
        }

        DropdownMenu(
            expanded = expanded,
            onDismissRequest = { expanded = false }
        ) {
            DropdownMenuItem(
                onClick = {
                    filteredGames = games
                    selectedGenre = null
                    selectedCompany = null
                    expanded = false
                }
            ) {
                Text("Сбросить фильтр")
            }

            DropdownMenuItem(
                onClick = {
                    filterByGenre = true
                    expanded = false
                }
            ) {
                Text("Фильтровать по жанру")
            }

            DropdownMenuItem(
                onClick = {
                    filterByGenre = false
                    expanded = false
                }
            ) {
                Text("Фильтровать по компании")
            }

            if (filterByGenre) {
                genres.forEach { genre ->
                    DropdownMenuItem(
                        onClick = {
                            filteredGames = FilterGenre(games, genre.id)
                            selectedGenre = genre
                            selectedCompany = null
                            expanded = false
                        }
                    ) {
                        Text(genre.genre_name)
                    }
                }
            } else {
                companies.forEach { company ->
                    DropdownMenuItem(
                        onClick = {
                            filteredGames = FilterCompany(games, company.id)
                            selectedCompany = company
                            selectedGenre = null
                            expanded = false
                        }
                    ) {
                        Text(company.name_company)
                    }
                }
            }

            if (filteredGames.isEmpty()) {
                DropdownMenuItem(onClick = {}) {
                    Text("Нет подходящих игр", color = Color.Red)
                }
            }
        }
    }
    return filteredGames
}

    suspend fun addToView(id_game: Int, view: Int?, NavHost: NavHostController) {
        val newView = view?.plus(1)

        val response = supabase.from("Game").update(
            {
                Game::views setTo newView
                set("views", newView)
            }
        ) {
            filter {
                Game::id eq id_game
            }
        }
    }