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 com.example.oscellamobile.models.Company
import coil.compose.AsyncImagePainter
import coil.request.ImageRequest
import coil.size.Size
import com.example.oscellamobile.models.Users
import io.github.jan.supabase.gotrue.auth

@Composable
fun AboutCompany(navHost: NavHostController, id: Int) {
    var company by remember { mutableStateOf<List<Company>>(listOf()) }
    var games by remember { mutableStateOf<List<Game>>(listOf()) }
    var user by remember { mutableStateOf<List<Users>>(listOf()) }

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

    val filteredCompany = company.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 // Центрируем элементы внутри LazyColumn
                ) {
                    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(
                filteredCompany,
                key = { company -> company.id }
            ) { company ->
                CompanyItem(company, navHost, games)
            }
        }
    }
}

@Composable
fun CompanyItem(
    company: Company,
    navHost: NavHostController,
    games: List<Game>
) {
    val imageState = rememberAsyncImagePainter(
        model = ImageRequest.Builder(LocalContext.current).data(company.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(
                    company.name_company,
                    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))
                if (company.description != 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(
                            company.description!!,
                            textAlign = TextAlign.Center,
                            fontFamily = ibmplexmono,
                            fontSize = 12.sp,
                            color = Color.Black
                        )
                    }
                }
                val CompanyID = company.id
                val gamecompany = games.filter { it.company == CompanyID }
                if (!gamecompany.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(gamecompany) { 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)
                                            )
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}