package com.example.myani.ui.media

import android.annotation.SuppressLint
import android.content.Context
import androidx.compose.animation.animateContentSize
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.animation.core.updateTransition
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
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.LazyListState
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowLeft
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.filled.Share
import androidx.compose.material.icons.filled.Star
import androidx.compose.material.icons.filled.ThumbUp
import androidx.compose.material3.AssistChip
import androidx.compose.material3.AssistChipDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
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.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavController
import androidx.navigation.NavHostController
import coil.ImageLoader
import coil.compose.AsyncImage
import coil.request.CachePolicy
import coil.request.ImageRequest
import com.apollographql.apollo.ApolloClient
import com.example.myani.data.response.CharacterEdge
import com.example.myani.data.response.ExternalLink
import com.example.myani.data.response.MediaDetails
import com.example.myani.data.response.MediaRecommendationEdge
import com.example.myani.data.response.Recommendation
import com.example.myani.data.response.RelatedMedia
import com.example.myani.data.response.RelatedMediaEdge
import com.example.myani.data.response.Tag
import com.example.myani.data.response.VoiceActorNode
import com.example.myani.helper.LoadingScreen
import com.example.myani.helper.colorFromString
import com.example.myani.helper.copyToClipboard
import com.example.myani.helper.detectPressAndNavigate
import com.example.myani.helper.htmlToSpanned
import com.example.myani.helper.navigateToAnimeDetails
import com.example.myani.helper.timeConverter
import com.example.myani.helper.toggleAnimeFavorite
import com.example.myani.ui.animeitems.AnimatedStatusDot
import com.example.myani.ui.animeitems.DarkLabelOverlay
import com.example.myani.utils.ContextUtils.openActionView
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch


@Composable
fun MediaDetailsScreen(
    viewModel: AnimeDetailsViewModel,
    animeId: Int,
    navController: NavHostController,
    imageLoader: ImageLoader,
    apolloClient: ApolloClient
) {
    val fetchAnimeDetails = remember(animeId) {
        { viewModel.fetchAnimeDetails(animeId) }
    }

    LaunchedEffect(fetchAnimeDetails) {
        fetchAnimeDetails()
    }

    val uiState by viewModel.uiState.collectAsStateWithLifecycle()

    MediaDetailsContent(
        uiState = uiState,
        navController = navController,
        imageLoader = imageLoader,
        apolloClient = apolloClient
    )
}

@Composable
private fun MediaDetailsContent(
    uiState: AnimeDetailsUiState,
    navController: NavHostController,
    imageLoader: ImageLoader,
    apolloClient: ApolloClient
) {
    val lazyListState = rememberLazyListState()

    when {
        uiState.isLoading -> LoadingScreen()
        uiState.mediaDetails != null -> MediaDetailsLayout(
            media = uiState.mediaDetails,
            navController = navController,
            lazyListState = lazyListState,
            imageLoader = imageLoader,
            apolloClient = apolloClient
        )
        else -> ErrorScreen()
    }
}


@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
@Composable
private fun MediaDetailsLayout(
    media: MediaDetails,
    navController: NavHostController,
    lazyListState: LazyListState,
    imageLoader: ImageLoader,
    apolloClient: ApolloClient
) {

    val fullSizeModifier = Modifier.fillMaxSize()
    val backgroundColor = MaterialTheme.colorScheme.background
    val isAtTop by remember { derivedStateOf {
        lazyListState.firstVisibleItemIndex == 0 && lazyListState.firstVisibleItemScrollOffset < 380
    }}

    Scaffold(topBar = {
            TopBar(
                headerInfo = media,
                onBackPress = { navController.popBackStack() },
                apolloClient = apolloClient,
                backgroundColor = if (isAtTop) Color.Transparent else MaterialTheme.colorScheme.background,
                isAtTop = isAtTop
            )
        }
    )
    {
        LazyColumn(
            state = lazyListState,
            modifier = fullSizeModifier
                .background(backgroundColor)
        ) {

            item { HeaderSection(media, imageLoader) }
            item { EpisodeInfo(media) }
            item { GenreChips(media.genres) }
            item { Description(media.description) }
            item { OverviewSection(media) }
            item { TagsSection(media.tags) }
            item { CharactersSection(media, navController) }
            item { RelationsSection(media.relatedMedia, navController, imageLoader) }
            item { RecommendationsSection(media.recommendations, navController, imageLoader)}
            item { StreamingLinksSection(media.externalLinks) }
        }
    }
}

@Composable
private fun ErrorScreen() {
    Box(
        modifier = Modifier.fillMaxSize(),
        contentAlignment = Alignment.Center
    ) {
        Text("Error loading anime details", color = MaterialTheme.colorScheme.error)
    }
}


@Composable
private fun HeaderSection(
    media: MediaDetails,
    imageLoader: ImageLoader
) {

    val headerInfo = remember(media) {
        (media.bannerImage ?: media.coverImage.extraLarge)?.let {
            HeaderInfo(
                title = media.title.userPreferred ?: media.title.romaji ?: "",
                yearFormat = "${media.startDate.year} • ${media.format}",
                bannerImage = it,
                coverImage = media.coverImage.large ?: "",
                siteUrl = media.siteUrl ?: "",
                isFavorite = media.isFavourite,
                id = media.id,
                mediaType = media.type
            )
        }
    }

    val context = LocalContext.current

    val imageRequest = ImageRequest.Builder(context)
        .data(media.bannerImage ?: headerInfo?.coverImage)
        .memoryCachePolicy(CachePolicy.ENABLED)
        .diskCachePolicy(CachePolicy.ENABLED)
        .crossfade(true)
        .build()

    HeaderContent(headerInfo, imageLoader, imageRequest)
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TopBar(
    headerInfo: MediaDetails,
    onBackPress: () -> Unit,
    apolloClient: ApolloClient,
    backgroundColor: Color,
    isAtTop: Boolean
) {

    val context = LocalContext.current
    var isFavorite by remember { mutableStateOf(headerInfo.isFavourite) }

    TopAppBar(
        title = {
            Box(modifier = Modifier.height(24.dp)) {
                val transition = updateTransition(targetState = isAtTop, label = "titleTransition")
                val yOffset by transition.animateFloat(
                    label = "yOffset",
                    transitionSpec = { tween(300) }
                ) { atTop ->
                    if (atTop) -40f else 0f
                }
                val alpha by transition.animateFloat(
                    label = "alpha",
                    transitionSpec = { tween(300) }
                ) { atTop ->
                    if (atTop) 0f else 1f
                }

                Text(
                    text = headerInfo.title.userPreferred ?: "",
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis,
                    style = MaterialTheme.typography.titleMedium,
                    modifier = Modifier.offset(y = yOffset.dp),
                    color = MaterialTheme.colorScheme.onBackground.copy(alpha = alpha)
                )
            }
        },
        navigationIcon = {
            IconButton(onClick = onBackPress) {
                Icon(
                    imageVector = Icons.AutoMirrored.Filled.ArrowBack,
                    contentDescription = "Back",
                    modifier = Modifier.size(20.dp)
                )
            }
        },
        actions = {
            IconButton(onClick = {
                if (isFavorite != null) {
                    CoroutineScope(Dispatchers.IO).launch {
                        if (toggleAnimeFavorite(apolloClient, headerInfo.id, headerInfo.type)) isFavorite = !isFavorite!!
                    }
                }
            }) {
                Icon(
                    imageVector = Icons.Filled.Favorite,
                    contentDescription = "Favorite",
                    tint = if (isFavorite == true) Color.Red else Color.White,
                    modifier = Modifier.size(20.dp)
                )
            }

            IconButton(onClick = {
                copyToClipboard(
                    context,
                    headerInfo.siteUrl ?: "There was a problem getting the URL"
                )
            }) {
                Icon(Icons.Filled.Share, contentDescription = "Share", tint = Color.White, modifier = Modifier.size(20.dp))
            }
        },
        colors = TopAppBarDefaults.topAppBarColors(
            containerColor = backgroundColor,
            titleContentColor = if (isAtTop) Color.Transparent else MaterialTheme.colorScheme.onBackground
        ),
    )
}


@Composable
private fun HeaderContent(
    headerInfo: HeaderInfo?,
    imageLoader: ImageLoader,
    imageRequest: ImageRequest
) {

    Box(
        modifier = Modifier
            .height(225.dp)
            .fillMaxWidth()
    ) {
        AsyncImage(
            model = imageRequest,
            contentDescription = "Anime Cover",
            modifier = Modifier.fillMaxSize(),
            contentScale = ContentScale.Crop,
            imageLoader = imageLoader
        )
        Box(
            modifier = Modifier
                .fillMaxSize()
                .background(
                    Brush.verticalGradient(
                        colors = listOf(Color.Transparent, MaterialTheme.colorScheme.background),
                        startY = 100f
                    )
                )
        )
        Row(
            modifier = Modifier
                .align(Alignment.BottomStart)
                .padding(16.dp)
        ) {
            Column(
                modifier = Modifier.padding(horizontal = 16.dp)
            ) {
                Text(
                    text = headerInfo?.title ?: "",
                    style = MaterialTheme.typography.headlineSmall,
                    color = MaterialTheme.colorScheme.onBackground,
                    fontWeight = FontWeight.Bold,
                    maxLines = 3,
                    overflow = TextOverflow.Ellipsis
                )
                Text(
                    text = headerInfo?.yearFormat ?: "",
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onSurface
                )
            }
        }
    }
}


@Immutable
data class HeaderInfo(
    val title: String,
    val yearFormat: String,
    val bannerImage: String,
    val siteUrl: String,
    val isFavorite: Boolean?,
    val id: Int,
    val mediaType: String,
    val coverImage: String
)


@Composable
private fun EpisodeInfo(anime: MediaDetails) {
    val isAiring =
        anime.nextAiringEpisode?.episode != 0 && anime.nextAiringEpisode?.episode != null && anime.status == "RELEASING"
    val episodeInfo = if (isAiring) {
        "Episodes: ${(anime.nextAiringEpisode?.episode ?: 1) - 1}/${anime.episodes ?: "??"}"
    } else {
        "Episodes: ${anime.episodes ?: "??"}"
    }

    val startDate = anime.startDate.let { "Start Date: ${it.day}/${it.month}/${it.year}" }

    val nextEpisodeInfo = remember(anime.nextAiringEpisode) {
        if (isAiring) {
            val (timeUntil, type) = timeConverter(anime.nextAiringEpisode!!.timeUntilAiring.toLong())
            when (type) {
                "day" -> "Next Episode: $timeUntil days"
                "hour" -> "Next Episode: $timeUntil hours"
                else -> "Next Episode: $timeUntil minutes"
            }
        } else {
            null
        }
    }

    if (isAiring) {
        Column(modifier = Modifier.padding(16.dp)) {
            Row(modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
                Text(
                    text = episodeInfo,
                    style = MaterialTheme.typography.titleMedium,
                    color = MaterialTheme.colorScheme.tertiary
                )
                Spacer(modifier = Modifier.weight(1f))
                Text(
                    text = startDate,
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.tertiaryContainer
                )

            }

            nextEpisodeInfo?.let {
                Text(
                    text = it,
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.tertiary
                )
            }
        }
    } else {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(
                text = episodeInfo,
                style = MaterialTheme.typography.titleMedium,
                color = MaterialTheme.colorScheme.tertiary
            )
            Spacer(modifier = Modifier.weight(1f))
            Text(
                text = startDate,
                style = MaterialTheme.typography.bodyMedium,
                color = MaterialTheme.colorScheme.tertiaryContainer
            )
        }
    }
}


@Composable
private fun GenreChips(genres: List<String>) {
    val rememberedGenres = remember { genres }

    LazyRow(
        horizontalArrangement = Arrangement.spacedBy(8.dp),
        contentPadding = PaddingValues(horizontal = 16.dp)
    ) {
        items(rememberedGenres.size, key = { it }) { index ->
            AssistChip(
                onClick = { },
                label = { Text(
                    text = rememberedGenres[index],
                    color = MaterialTheme.colorScheme.tertiary
                )},
                colors = AssistChipDefaults.assistChipColors(
                    containerColor = MaterialTheme.colorScheme.background,
                    labelColor = MaterialTheme.colorScheme.tertiary
                )
            )
        }
    }
}


@OptIn(ExperimentalFoundationApi::class)
@SuppressLint("ServiceCast")
@Composable
private fun Description(description: String?) {
    var expanded by rememberSaveable { mutableStateOf(false) }
    val context = LocalContext.current

    val htmlText = description?.trimIndent()

    Column(
        modifier = Modifier
            .padding(16.dp)
            .animateContentSize()
            .combinedClickable(
                onClick = { expanded = !expanded },
                onLongClick = {
                    if (description != null) {
                        copyToClipboard(context, description)
                    }
                }
            )
    ) {
        Text(
            text = "Description",
            style = MaterialTheme.typography.titleMedium,
            color = MaterialTheme.colorScheme.tertiary,
            fontWeight = FontWeight.Bold
        )
        Spacer(modifier = Modifier.height(8.dp))
        Text(
            text = htmlText?.let { htmlToSpanned(it) }?.toString() ?: "No description available.",
            style = MaterialTheme.typography.bodyMedium,
            color = MaterialTheme.colorScheme.tertiaryContainer,
            maxLines = if (expanded) Int.MAX_VALUE else 5,
            overflow = TextOverflow.Ellipsis
        )
    }
}


@Composable
private fun CharactersSection(
    anime: MediaDetails,
    navController: NavHostController
) {

    if (anime.characters.edges?.isNotEmpty() == true) {
        Column(modifier = Modifier.padding(top = 4.dp, bottom = 16.dp)) {
            Text(
                text = "Characters",
                style = MaterialTheme.typography.titleMedium,
                color = MaterialTheme.colorScheme.tertiary ,
                fontWeight = FontWeight.Bold,
                modifier = Modifier.padding(horizontal = 16.dp)
            )
            Spacer(modifier = Modifier.height(12.dp))
            LazyRow(
                horizontalArrangement = Arrangement.spacedBy(12.dp),
                contentPadding = PaddingValues(start = 16.dp, end = 16.dp)
            ) {
                items(anime.characters.edges, key = { it.node?.id ?: 0 }) { character ->
                    CharacterCard(character = character, navController = navController)
                }
            }
        }
    }
}

@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun CharacterCard(
    character: CharacterEdge,
    navController: NavHostController
) {

    val voiceActors = remember { character.voiceActors ?: emptyList() }
    val pagerState = rememberPagerState(pageCount = { voiceActors.size })

    val coroutineScope = rememberCoroutineScope()

    Card(
        modifier = Modifier
            .width(150.dp)
            .clickable {
                character.node?.id?.let { characterId ->
                    navController.navigate("character/$characterId")
                }
            },
        shape = RoundedCornerShape(8.dp),
        elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
    ) {
        Column {
            Box(
                modifier = Modifier
                    .height(200.dp)
                    .fillMaxWidth()
            ) {
                AsyncImage(
                    model = ImageRequest.Builder(LocalContext.current)
                        .data(character.node?.image?.large)
                        .crossfade(true)
                        .build(),
                    contentDescription = "Character Image",
                    modifier = Modifier.fillMaxSize(),
                    contentScale = ContentScale.Crop
                )
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .background(
                            MaterialTheme.colorScheme.surface.copy(alpha = 0.65f)
                        )
                )
                Column(
                    modifier = Modifier
                        .align(Alignment.BottomStart)
                        .padding(8.dp)
                ) {
                    Text(
                        text = character.node?.name?.userPreferred ?: "Unknown",
                        style = MaterialTheme.typography.titleMedium,
                        color = MaterialTheme.colorScheme.onSurface,
                        fontWeight = FontWeight.Bold,
                        maxLines = 2,
                        overflow = TextOverflow.Ellipsis
                    )
                    Spacer(modifier = Modifier.height(4.dp))
                    Text(
                        text = character.role.toString(),
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
            }
            if (voiceActors.isNotEmpty()) {
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(60.dp)
                ) {
                    HorizontalPager(
                        state = pagerState,
                        modifier = Modifier.fillMaxSize()
                    ) { page ->
                        VoiceActorItem(voiceActor = voiceActors[page])
                    }

                    // Left navigation arrow
                    if (pagerState.currentPage > 0) {
                        IconButton(
                            onClick = {
                                coroutineScope.launch {
                                    pagerState.animateScrollToPage(pagerState.currentPage - 1)
                                }
                            },
                            modifier = Modifier.align(Alignment.BottomStart)
                        ) {
                            Icon(
                                imageVector = Icons.AutoMirrored.Filled.KeyboardArrowLeft,
                                contentDescription = "Previous Voice Actor",
                                tint = Color.White,
                                modifier = Modifier.size(16.dp)
                            )
                        }
                    }

                    // Right navigation arrow
                    if (pagerState.currentPage < voiceActors.size - 1) {
                        IconButton(
                            onClick = {
                                coroutineScope.launch {
                                    pagerState.animateScrollToPage(pagerState.currentPage + 1)
                                }
                            },
                            modifier = Modifier.align(Alignment.BottomEnd)
                        ) {
                            Icon(
                                imageVector = Icons.AutoMirrored.Filled.KeyboardArrowRight,
                                contentDescription = "Next Voice Actor",
                                tint = Color.White,
                                modifier = Modifier.size(16.dp)
                            )
                        }
                    }
                }
            }
        }
    }
}

@Composable
private fun VoiceActorItem(voiceActor: VoiceActorNode) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(8.dp)
            .clickable { /*TODO: Handle click*/ },
        verticalAlignment = Alignment.CenterVertically,
    ) {
        AsyncImage(
            model = ImageRequest.Builder(LocalContext.current)
                .data(voiceActor.image?.medium)
                .crossfade(true)
                .build(),
            contentDescription = "Voice Actor Image",
            modifier = Modifier
                .size(48.dp)
                .clip(RoundedCornerShape(4.dp)),
            contentScale = ContentScale.Crop
        )
        Spacer(modifier = Modifier.width(8.dp))
        Column {
            Text(
                text = voiceActor.name?.userPreferred ?: "Unknown",
                style = MaterialTheme.typography.bodyMedium,
                color = MaterialTheme.colorScheme.onSurface,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis
            )
            Text(
                text = voiceActor.languageV2 ?: "Unknown Language",
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )
        }
    }
}


@Composable
private fun OverviewSection(anime: MediaDetails) {

    val preparedData = remember(anime) {
        PreparedAnimeData(
            romaji = anime.title.romaji ?: "N/A",
            english = anime.title.english ?: "N/A",
            format = anime.format,
            duration = "${anime.duration ?: "?"} min per ep",
            status = anime.status ?: "N/A",
            averageScore = "${anime.averageScore}%",
            popularity = anime.popularity.toString(),
            favorites = anime.favorites.toString(),
            season = "${anime.season} ${anime.seasonYear}",
            startDate = anime.startDate.let { "${it.day}/${it.month}/${it.year}" },
            studioList = anime.studios?.nodes?.filterNotNull()
                ?.filter { it.isAnimationStudio }?.joinToString(", ") { it.name } ?: ""
        )
    }

    Column(modifier = Modifier.padding(16.dp)) {
        Text(
            text = "Overview",
            style = MaterialTheme.typography.titleMedium,
            color = MaterialTheme.colorScheme.tertiary,
            fontWeight = FontWeight.Bold
        )
        Spacer(modifier = Modifier.height(8.dp))

        with(preparedData) {
            OverviewItem("Romaji", romaji)
            OverviewItem("English", english)
            OverviewItem("Format", format)
            OverviewItem("Duration", duration)
            OverviewItem("Status", status, showStatusDot = true, status = anime.status)
            OverviewItem("Average Score", averageScore)
            OverviewItem("Popularity", popularity)
            OverviewItem("Favorites", favorites)
            OverviewItem("Season", season)
            OverviewItem("Start Date", startDate)
            OverviewItem("Studios", studioList)
        }
    }
}

@Immutable
data class PreparedAnimeData(
    val romaji: String,
    val english: String,
    val format: String,
    val duration: String,
    val status: String,
    val averageScore: String,
    val popularity: String,
    val favorites: String,
    val season: String,
    val startDate: String,
    val studioList: String
)



@Composable
private fun OverviewItem(label: String, value: String, showStatusDot: Boolean = false, status: String? = null) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 4.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        Text(text = label, color =MaterialTheme.colorScheme.tertiaryContainer, modifier = Modifier.weight(1f))
        Row(
            verticalAlignment = Alignment.CenterVertically,
            modifier = Modifier.weight(1f)
        ) {
            Text(text = value, color = MaterialTheme.colorScheme.tertiary)
            if (showStatusDot && status == "RELEASING") {
                Spacer(modifier = Modifier.width(4.dp))
                AnimatedStatusDot()
            }
        }
    }
}


@Composable
private fun TagsSection(tagList: List<Tag>?) {

    val tags = remember(tagList) {
        tagList?.sortedByDescending { it.rank } ?: emptyList()
    }

    if (tags.isNotEmpty()) {
        Column {
            Text(
                text = "Tags",
                style = MaterialTheme.typography.titleMedium,
                color = MaterialTheme.colorScheme.tertiary,
                fontWeight = FontWeight.Bold,
                modifier = Modifier.padding(horizontal = 16.dp)
            )
            Spacer(modifier = Modifier.height(4.dp))
            LazyRow(contentPadding = PaddingValues(start = 16.dp, end = 16.dp)) {
                items(tags.size, key = { it }) { index ->
                    AssistChip(
                        onClick = { },
                        label = { Text("${tags[index].name} : ${tags[index].rank}%" , color = MaterialTheme.colorScheme.tertiary) },
                        colors = AssistChipDefaults.assistChipColors(
                            containerColor = MaterialTheme.colorScheme.background,
                            labelColor = MaterialTheme.colorScheme.tertiary
                        )
                    )
                    Spacer(modifier = Modifier.width(8.dp))
                }
            }
        }
    }
}

@Composable
private fun RelationsSection(
    relatedMedia: RelatedMedia?,
    navController: NavHostController,
    imageLoader: ImageLoader
) {

    val context = LocalContext.current

    if (relatedMedia != null) {
        if (relatedMedia.edge.isNotEmpty()) {
            Column {
                Text(
                    text = "Relations",
                    style = MaterialTheme.typography.titleMedium,
                    color = MaterialTheme.colorScheme.tertiary,
                    fontWeight = FontWeight.Bold,
                    modifier = Modifier.padding(horizontal = 16.dp)
                )
                Spacer(modifier = Modifier.height(8.dp))
                LazyRow(
                    horizontalArrangement = Arrangement.spacedBy(8.dp),
                    contentPadding = PaddingValues(start = 16.dp, end = 16.dp)
                ) {
                    items(relatedMedia.edge) { node ->
                        AnimeCardRelations(node, navController, imageLoader, context)
                    }
                }
            }
        }
    }
}

@Composable
private fun AnimeCardRelations(
    media: RelatedMediaEdge,
    navController: NavController,
    imageLoader: ImageLoader,
    context: Context,
) {
    val isPressed = remember { mutableStateOf(false) }

    val scale by animateFloatAsState(
        targetValue = if (isPressed.value) 0.98f else 1f,
        animationSpec = tween(durationMillis = 150),
        label = ""
    )
    val elevation by animateDpAsState(
        targetValue = if (isPressed.value) 3.dp else 5.dp,
        animationSpec = tween(durationMillis = 150),
        label = ""
    )

    val cardModifier = Modifier
        .size(width = 140.dp, height = 220.dp)
        .graphicsLayer {
            scaleX = scale
            scaleY = scale
            shadowElevation = elevation.toPx()
        }

    val imageRequest = ImageRequest.Builder(context)
        .data(media.node.coverImage.large)
        .crossfade(true)
        .build()

    Card(
        modifier = cardModifier.detectPressAndNavigate(
            onPress = { isPressed.value = true },
            onRelease = { isPressed.value = false }
        ) {
            navigateToAnimeDetails(media.node.id, navController)
        },
        shape = RoundedCornerShape(12.dp),
        elevation = CardDefaults.cardElevation(defaultElevation = elevation)
    ) {
        Box(modifier = Modifier.fillMaxSize()) {
            AnimeImage(imageRequest, imageLoader)
            GradientOverlay()
            AnimeInfoRelations(media)
        }
    }
}

@Composable
private fun AnimeImage(imageRequest: ImageRequest, imageLoader: ImageLoader) {
    AsyncImage(
        model = imageRequest,
        imageLoader = imageLoader,
        contentDescription = "Anime Cover Image",
        modifier = Modifier.fillMaxSize(),
        contentScale = ContentScale.Crop
    )
}

@Composable
private fun GradientOverlay() {
    val gradientBrush = Brush.verticalGradient(
        colors = listOf(Color.Transparent, Color.Black.copy(alpha = 0.7f)),
        startY = 100f
    )
    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(gradientBrush)
    )
}

@Composable
private fun AnimeInfoRelations(media: RelatedMediaEdge) {
    Box(
        modifier = Modifier
            .fillMaxSize()
            .padding(12.dp)
    ) {
        Surface(modifier = Modifier.align(Alignment.TopStart), color = Color.Transparent) {
            if (media.node.format?.isNotBlank() == true) {
                DarkLabelOverlay(text = media.node.format)
            }
        }

        Column(
            modifier = Modifier.align(Alignment.BottomStart)
        ) {
            Text(
                text = media.node.title.userPreferred ?: "",
                style = MaterialTheme.typography.bodyLarge.copy(
                    color = Color.White,
                    fontWeight = FontWeight.Bold
                ),
                maxLines = 2,
                overflow = TextOverflow.Ellipsis
            )
            Text(
                text = media.relationType.toString(),
                style = MaterialTheme.typography.bodySmall.copy(color = media.node.coverImage.color?.let { colorFromString(it)} ?: Color.White)
            )
            if (media.node.averageScore != 0) {
                Row(verticalAlignment = Alignment.CenterVertically) {
                    Icon(
                        imageVector = Icons.Filled.Star,
                        contentDescription = null,
                        tint = Color.Yellow,
                        modifier = Modifier.size(16.dp)
                    )
                    Spacer(modifier = Modifier.width(4.dp))
                    Text(
                        text = "${media.node.averageScore}%",
                        style = MaterialTheme.typography.bodyMedium.copy(color = Color.White)
                    )
                }
            }
        }
    }
}

@Composable
private fun RecommendationsSection(
    recommendations: Recommendation,
    navController: NavHostController,
    imageLoader: ImageLoader
) {
    val context = LocalContext.current


    if (recommendations.edges.isNotEmpty()) {
        Column(modifier = Modifier.padding(top = 16.dp)) {
            Text(
                text = "Recommendations",
                style = MaterialTheme.typography.titleMedium,
                color = MaterialTheme.colorScheme.tertiary,
                fontWeight = FontWeight.Bold,
                modifier = Modifier.padding(horizontal = 16.dp)
            )
            Spacer(modifier = Modifier.height(8.dp))
            LazyRow(
                horizontalArrangement = Arrangement.spacedBy(8.dp),
                contentPadding = PaddingValues(start = 16.dp, end = 16.dp)
            ) {
                items(recommendations.edges) { node ->
                    AnimeCardRecommendations(node, navController, imageLoader, context)
                }
            }
        }
    }
}

@Composable
private fun AnimeCardRecommendations(
    media: MediaRecommendationEdge,
    navController: NavController,
    imageLoader: ImageLoader,
    context: Context
) {
    val isPressed = remember { mutableStateOf(false) }

    val scale by animateFloatAsState(
        targetValue = if (isPressed.value) 0.98f else 1f,
        animationSpec = tween(durationMillis = 150),
        label = ""
    )
    val elevation by animateDpAsState(
        targetValue = if (isPressed.value) 3.dp else 5.dp,
        animationSpec = tween(durationMillis = 150),
        label = ""
    )

    val cardModifier = Modifier
        .size(width = 140.dp, height = 220.dp)
        .graphicsLayer {
            scaleX = scale
            scaleY = scale
            shadowElevation = elevation.toPx()
        }

    val imageRequest = ImageRequest.Builder(context)
        .data(media.node.coverImage.large)
        .crossfade(true)
        .build()

    Card(
        modifier = cardModifier.detectPressAndNavigate(
            onPress = { isPressed.value = true },
            onRelease = { isPressed.value = false }
        ) {
            navigateToAnimeDetails(media.node.id, navController)
        },
        shape = RoundedCornerShape(12.dp),
        elevation = CardDefaults.cardElevation(defaultElevation = elevation)
    ) {
        Box(modifier = Modifier.fillMaxSize()) {
            AnimeImage(imageRequest, imageLoader)
            GradientOverlay()
            AnimeInfoRecommendations(media)
        }
    }
}

@Composable
fun AnimeInfoRecommendations(media: MediaRecommendationEdge) {
    Box(
        modifier = Modifier
            .fillMaxSize()
            .padding(12.dp)
    ) {
        Surface(modifier = Modifier.align(Alignment.TopStart), color = Color.Transparent) {
            if (media.node.format.isNotBlank()) {
                DarkLabelOverlay(text = media.node.format)
            }
        }

        Column(
            modifier = Modifier.align(Alignment.BottomStart)
        ) {
            Text(
                text = media.node.title.userPreferred ?: "",
                style = MaterialTheme.typography.bodyLarge.copy(
                    color = Color.White,
                    fontWeight = FontWeight.Bold
                ),
                maxLines = 2,
                overflow = TextOverflow.Ellipsis,
            )
            Spacer(modifier = Modifier.height(4.dp))
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                if (media.node.averageScore != 0) {
                    Row(verticalAlignment = Alignment.CenterVertically) {
                        Icon(
                            imageVector = Icons.Filled.Star,
                            contentDescription = null,
                            tint = Color.Yellow,
                            modifier = Modifier.size(16.dp)
                        )
                        Spacer(modifier = Modifier.width(4.dp))
                        Text(
                            text = "${media.node.averageScore}%",
                            style = MaterialTheme.typography.bodyMedium.copy(color = Color.White)
                        )
                    }
                }

                Row (verticalAlignment = Alignment.CenterVertically){
                    Icon(
                        imageVector = Icons.Default.ThumbUp,
                        contentDescription = "Recommendation count",
                        tint = Color.White,
                        modifier = Modifier.size(16.dp)
                    )
                    Spacer(modifier = Modifier.width(4.dp))
                    Text(
                        text = "${media.node.rating}",
                        style = MaterialTheme.typography.bodyMedium.copy(color = Color.White)
                    )
                }
            }
        }

    }
}


@Composable
private fun StreamingLinksSection(links: List<ExternalLink>?) {

    val streamingLinks = remember { links?.filter { it.type == "STREAMING" } ?: emptyList() }
    val otherLinks = remember { links?.filter { it.type != "STREAMING" } ?: emptyList() }

    val context = LocalContext.current

    if (streamingLinks.isNotEmpty()) {
        Column(modifier = Modifier.padding(top = 16.dp)){
            Text(
                text = "Streaming Links",
                style = MaterialTheme.typography.titleMedium,
                color = MaterialTheme.colorScheme.tertiary,
                fontWeight = FontWeight.Bold,
                modifier = Modifier.padding(start = 16.dp)
            )

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

            LazyRow(
                contentPadding = PaddingValues(bottom = 24.dp, start = 16.dp, end = 16.dp),
                horizontalArrangement = Arrangement.SpaceEvenly
            ) {

                items(streamingLinks.size, key = { it }) { index ->
                    AssistChip(
                        onClick = { streamingLinks[index].url.let { context.openActionView(it) } },
                        label = {
                            Text(text = streamingLinks[index].site, color = MaterialTheme.colorScheme.tertiary)
                        },
                        leadingIcon = {
                            if (streamingLinks[index].icon.isNotEmpty()) {
                                AsyncImage(
                                    model = streamingLinks[index].icon,
                                    contentDescription = "Icons",
                                    modifier = Modifier.size(20.dp),
                                    colorFilter = ColorFilter.tint(colorFromString(streamingLinks[index].color))
                                )
                            }
                        }
                    )
                    Spacer(modifier = Modifier.width(8.dp))
                }
            }
        }
    }

    if (otherLinks.isNotEmpty()) {
        Column{
            Text(
                text = "Other Links",
                style = MaterialTheme.typography.titleMedium,
                color = MaterialTheme.colorScheme.tertiary,
                fontWeight = FontWeight.Bold,
                modifier = Modifier.padding(start = 16.dp)
            )

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

            LazyRow(
                contentPadding = PaddingValues(bottom = 24.dp, start = 16.dp, end = 16.dp),
                horizontalArrangement = Arrangement.SpaceEvenly
            ) {

                items(otherLinks.size, key = { it }) { index ->
                    AssistChip(
                        onClick = { otherLinks[index].url.let { context.openActionView(it) } },
                        label = {
                            Text(text = otherLinks[index].site, color = MaterialTheme.colorScheme.tertiary)
                            if (otherLinks[index].language == "Japanese") Text(text = "\tJP", color = Color.Cyan)
                        },
                        leadingIcon = {
                            if(otherLinks[index].icon.isNotEmpty()) {
                                AsyncImage(
                                    model = otherLinks[index].icon,
                                    contentDescription = "Icons",
                                    modifier = Modifier.size(20.dp),
                                    colorFilter = when (otherLinks[index].site) {
                                        "Twitter" -> ColorFilter.tint(MaterialTheme.colorScheme.onBackground)
                                        else -> ColorFilter.tint(colorFromString(otherLinks[index].color))
                                    })
                            }
                        }
                    )
                    Spacer(modifier = Modifier.width(8.dp))
                }
            }
        }
    }
}

Bu UI'ı daha güzel hale getir