package id.iiyh.inatrading.feature.news.presentation

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
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.aspectRatio
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.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.outlined.ArrowForward
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.ripple
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
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.layout.ContentScale
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import coil.compose.AsyncImage
import id.iiyh.inatrading.R
import id.iiyh.inatrading.core.ui.components.InaInnerTopAppBar
import id.iiyh.inatrading.core.ui.theme.AccentBlue
import id.iiyh.inatrading.core.ui.theme.AccentBlueContainer
import id.iiyh.inatrading.core.ui.theme.AccentPurple
import id.iiyh.inatrading.core.ui.theme.AccentPurpleContainer
import id.iiyh.inatrading.core.ui.theme.Background
import id.iiyh.inatrading.core.ui.theme.BrandRed
import id.iiyh.inatrading.core.ui.theme.BrandRedContainer
import id.iiyh.inatrading.core.ui.theme.ManropeFontFamily
import id.iiyh.inatrading.core.ui.theme.OnSurface
import id.iiyh.inatrading.core.ui.theme.OnSurfaceVariant
import id.iiyh.inatrading.core.ui.theme.OutlineVariant
import id.iiyh.inatrading.core.ui.theme.SurfaceContainerHighest
import id.iiyh.inatrading.core.ui.theme.SurfaceContainerLow
import id.iiyh.inatrading.core.ui.theme.SurfaceContainerLowest
import id.iiyh.inatrading.feature.news.data.model.NewsArticle

@Composable
fun NewsListScreen(
    onBack: () -> Unit,
    onArticleClick: (NewsArticle) -> Unit,
    viewModel: NewsListViewModel = hiltViewModel(),
) {
    val uiState by viewModel.uiState.collectAsState()

    Scaffold(
        topBar = { InaInnerTopAppBar(onBack = onBack) },
        containerColor = Background,
    ) { innerPadding ->
        LazyColumn(
            modifier = Modifier
                .fillMaxSize()
                .background(Background)
                .padding(innerPadding),
        ) {
            item {
                NewsListHero()
            }

            when {
                uiState.isLoading -> {
                    item {
                        Box(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(vertical = 64.dp),
                            contentAlignment = Alignment.Center,
                        ) {
                            CircularProgressIndicator(color = BrandRed)
                        }
                    }
                }
                uiState.errorMessage != null -> {
                    item {
                        NewsListMessageCard(
                            title = stringResource(R.string.news_list_error_title),
                            body = uiState.errorMessage!!,
                            accent = AccentBlue,
                        )
                    }
                }
                uiState.articles.isEmpty() -> {
                    item {
                        NewsListMessageCard(
                            title = stringResource(R.string.news_list_empty_title),
                            body = stringResource(R.string.news_list_empty_body),
                            accent = AccentPurple,
                        )
                    }
                }
                else -> {
                    val articles = uiState.articles

                    item {
                        SectionTitle()
                    }

                    item {
                        FeaturedArticleCard(
                            article = articles.first(),
                            onClick = { onArticleClick(articles.first()) },
                        )
                    }

                    val secondary = articles.drop(1).take(2)
                    if (secondary.isNotEmpty()) {
                        item {
                            Row(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(horizontal = 24.dp),
                                horizontalArrangement = Arrangement.spacedBy(16.dp),
                            ) {
                                secondary.forEach { article ->
                                    CompactArticleCard(
                                        article = article,
                                        modifier = Modifier.weight(1f),
                                        onClick = { onArticleClick(article) },
                                    )
                                }
                                if (secondary.size == 1) {
                                    Spacer(modifier = Modifier.weight(1f))
                                }
                            }
                        }
                    }

                    val highlighted = articles.drop(3).firstOrNull()
                    if (highlighted != null) {
                        item {
                            WideArticleCard(
                                article = highlighted,
                                onClick = { onArticleClick(highlighted) },
                            )
                        }
                    }

                    val remaining = articles.drop(4)
                    items(remaining.size) { index ->
                        val article = remaining[index]
                        EditorialArticleCard(
                            article = article,
                            onClick = { onArticleClick(article) },
                        )
                    }
                }
            }
        }
    }
}

@Composable
private fun NewsListHero() {
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 24.dp)
            .padding(top = 24.dp, bottom = 8.dp),
    ) {
        Box(
            modifier = Modifier
                .align(Alignment.TopEnd)
                .width(220.dp)
                .height(200.dp)
                .clip(
                    RoundedCornerShape(
                        topStart = 0.dp,
                        topEnd = 0.dp,
                        bottomStart = 64.dp,
                        bottomEnd = 0.dp,
                    )
                )
                .background(SurfaceContainerHighest.copy(alpha = 0.55f)),
        )

        Column(
            modifier = Modifier.fillMaxWidth(),
            verticalArrangement = Arrangement.spacedBy(16.dp),
        ) {
            Text(
                text = stringResource(R.string.news_list_room),
                style = MaterialTheme.typography.labelSmall,
                color = BrandRed,
                letterSpacing = 1.5.sp,
                fontWeight = FontWeight.SemiBold,
            )

            Text(
                text = stringResource(R.string.news_list_title),
                fontFamily = ManropeFontFamily,
                fontWeight = FontWeight.ExtraBold,
                fontSize = 38.sp,
                color = OnSurface,
                lineHeight = 46.sp,
            )

            Text(
                text = stringResource(R.string.news_list_intro),
                style = MaterialTheme.typography.bodyMedium,
                color = OnSurfaceVariant,
                lineHeight = 24.sp,
            )

            Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
                AccentPill(
                    label = stringResource(R.string.news_list_pill_editorial),
                    container = BrandRedContainer,
                    content = BrandRed,
                )
                AccentPill(
                    label = stringResource(R.string.news_list_pill_trade_signals),
                    container = AccentBlueContainer,
                    content = AccentBlue,
                )
                AccentPill(
                    label = stringResource(R.string.news_list_pill_merchant_stories),
                    container = AccentPurpleContainer,
                    content = AccentPurple,
                )
            }
        }
    }
}

@Composable
private fun SectionTitle() {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 24.dp)
            .padding(bottom = 18.dp),
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.SpaceBetween,
    ) {
        Text(
            text = stringResource(R.string.news_list_latest_updates),
            fontFamily = ManropeFontFamily,
            fontWeight = FontWeight.ExtraBold,
            fontSize = 28.sp,
            color = OnSurface,
        )
        Box(
            modifier = Modifier
                .width(64.dp)
                .height(2.dp)
                .background(OutlineVariant),
        )
    }
}

@Composable
private fun FeaturedArticleCard(
    article: NewsArticle,
    onClick: () -> Unit,
) {
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 24.dp)
            .padding(bottom = 18.dp)
            .clip(RoundedCornerShape(28.dp))
            .background(SurfaceContainerLowest)
            .clickable(
                interactionSource = remember { MutableInteractionSource() },
                indication = ripple(),
                onClick = onClick,
            ),
    ) {
        Column {
            NewsImage(
                article = article,
                modifier = Modifier
                    .fillMaxWidth()
                    .aspectRatio(16f / 10f),
            )
            Column(
                modifier = Modifier.padding(24.dp),
                verticalArrangement = Arrangement.spacedBy(12.dp),
            ) {
                CategoryBadge(article = article)
                Text(
                    text = article.title,
                    fontFamily = ManropeFontFamily,
                    fontWeight = FontWeight.ExtraBold,
                    fontSize = 24.sp,
                    lineHeight = 32.sp,
                    color = OnSurface,
                )
                val summary = article.displaySummary.ifBlank {
                    stringResource(R.string.news_list_featured_fallback)
                }
                Text(
                    text = summary,
                    style = MaterialTheme.typography.bodyMedium,
                    color = OnSurfaceVariant,
                    lineHeight = 24.sp,
                    maxLines = 3,
                    overflow = TextOverflow.Ellipsis,
                )
                DetailLink()
            }
        }
    }
}

@Composable
private fun CompactArticleCard(
    article: NewsArticle,
    modifier: Modifier = Modifier,
    onClick: () -> Unit,
) {
    Column(
        modifier = modifier
            .clip(RoundedCornerShape(20.dp))
            .background(SurfaceContainerLowest)
            .clickable(
                interactionSource = remember { MutableInteractionSource() },
                indication = ripple(),
                onClick = onClick,
            )
            .padding(16.dp),
        verticalArrangement = Arrangement.spacedBy(14.dp),
    ) {
        NewsImage(
            article = article,
            modifier = Modifier
                .fillMaxWidth()
                .aspectRatio(4f / 3f)
                .clip(RoundedCornerShape(16.dp)),
        )
        CategoryBadge(article = article)
        Text(
            text = article.title,
            fontFamily = ManropeFontFamily,
            fontWeight = FontWeight.Bold,
            fontSize = 18.sp,
            lineHeight = 24.sp,
            color = OnSurface,
            maxLines = 3,
            overflow = TextOverflow.Ellipsis,
        )
        Text(
            text = article.displaySummary.ifBlank { stringResource(R.string.news_list_compact_fallback) },
            style = MaterialTheme.typography.bodySmall,
            color = OnSurfaceVariant,
            lineHeight = 20.sp,
            maxLines = 3,
            overflow = TextOverflow.Ellipsis,
        )
    }
}

@Composable
private fun WideArticleCard(
    article: NewsArticle,
    onClick: () -> Unit,
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 24.dp)
            .padding(bottom = 18.dp)
            .clip(RoundedCornerShape(24.dp))
            .background(SurfaceContainerLowest)
            .clickable(
                interactionSource = remember { MutableInteractionSource() },
                indication = ripple(),
                onClick = onClick,
            ),
    ) {
        NewsImage(
            article = article,
            modifier = Modifier
                .weight(1.05f)
                .aspectRatio(1f),
        )
        Column(
            modifier = Modifier
                .weight(1f)
                .padding(22.dp),
            verticalArrangement = Arrangement.spacedBy(10.dp),
        ) {
            CategoryBadge(article = article)
            Text(
                text = article.title,
                fontFamily = ManropeFontFamily,
                fontWeight = FontWeight.ExtraBold,
                fontSize = 22.sp,
                lineHeight = 30.sp,
                color = OnSurface,
                maxLines = 4,
                overflow = TextOverflow.Ellipsis,
            )
            Text(
                text = article.displaySummary.ifBlank { stringResource(R.string.news_list_wide_fallback) },
                style = MaterialTheme.typography.bodyMedium,
                color = OnSurfaceVariant,
                lineHeight = 22.sp,
                maxLines = 4,
                overflow = TextOverflow.Ellipsis,
            )
            DetailLink(label = stringResource(R.string.news_list_explore_update))
        }
    }
}

@Composable
private fun EditorialArticleCard(
    article: NewsArticle,
    onClick: () -> Unit,
) {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 24.dp)
            .padding(bottom = 18.dp)
            .clip(RoundedCornerShape(24.dp))
            .background(SurfaceContainerLow)
            .clickable(
                interactionSource = remember { MutableInteractionSource() },
                indication = ripple(),
                onClick = onClick,
            )
            .padding(18.dp),
        verticalArrangement = Arrangement.spacedBy(14.dp),
    ) {
        NewsImage(
            article = article,
            modifier = Modifier
                .fillMaxWidth()
                .aspectRatio(16f / 9f)
                .clip(RoundedCornerShape(18.dp)),
        )
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically,
        ) {
            CategoryBadge(article = article)
            if (!article.reporter.isNullOrBlank()) {
                Text(
                    text = article.reporter.uppercase(),
                    style = MaterialTheme.typography.labelSmall,
                    color = OnSurfaceVariant,
                    letterSpacing = 1.2.sp,
                )
            }
        }
        Text(
            text = article.title,
            fontFamily = ManropeFontFamily,
            fontWeight = FontWeight.Bold,
            fontSize = 20.sp,
            lineHeight = 28.sp,
            color = OnSurface,
        )
        Text(
            text = article.displaySummary.ifBlank { stringResource(R.string.news_list_editorial_fallback) },
            style = MaterialTheme.typography.bodyMedium,
            color = OnSurfaceVariant,
            lineHeight = 22.sp,
            maxLines = 3,
            overflow = TextOverflow.Ellipsis,
        )
        DetailLink()
    }
}

@Composable
private fun NewsListMessageCard(
    title: String,
    body: String,
    accent: Color,
) {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 24.dp)
            .padding(bottom = 18.dp)
            .clip(RoundedCornerShape(24.dp))
            .background(SurfaceContainerLowest)
            .padding(24.dp),
        verticalArrangement = Arrangement.spacedBy(12.dp),
    ) {
        Box(
            modifier = Modifier
                .size(48.dp)
                .clip(CircleShape)
                .background(accent.copy(alpha = 0.14f)),
        )
        Text(
            text = title,
            fontFamily = ManropeFontFamily,
            fontWeight = FontWeight.ExtraBold,
            fontSize = 22.sp,
            color = OnSurface,
        )
        Text(
            text = body,
            style = MaterialTheme.typography.bodyMedium,
            color = OnSurfaceVariant,
            lineHeight = 22.sp,
        )
    }
}

@Composable
private fun AccentPill(
    label: String,
    container: Color,
    content: Color,
) {
    Box(
        modifier = Modifier
            .clip(RoundedCornerShape(999.dp))
            .background(container)
            .padding(horizontal = 14.dp, vertical = 8.dp),
    ) {
        Text(
            text = label,
            style = MaterialTheme.typography.labelMedium,
            fontWeight = FontWeight.SemiBold,
            color = content,
        )
    }
}

@Composable
private fun CategoryBadge(article: NewsArticle) {
    val label = article.category?.takeIf { it.isNotBlank() } ?: stringResource(R.string.news_list_latest_update)
    val container = when (label.lowercase()) {
        "ekonomi" -> BrandRedContainer
        "merchant success" -> AccentBlueContainer
        "trade policy" -> AccentPurpleContainer
        else -> SurfaceContainerHighest
    }
    val content = when (label.lowercase()) {
        "ekonomi" -> BrandRed
        "merchant success" -> AccentBlue
        "trade policy" -> AccentPurple
        else -> OnSurfaceVariant
    }

    Box(
        modifier = Modifier
            .clip(RoundedCornerShape(10.dp))
            .background(container)
            .padding(horizontal = 10.dp, vertical = 6.dp),
    ) {
        Text(
            text = label,
            style = MaterialTheme.typography.labelSmall,
            fontWeight = FontWeight.Bold,
            color = content,
            letterSpacing = 0.8.sp,
        )
    }
}

@Composable
private fun DetailLink(label: String? = null) {
    val resolvedLabel = label ?: stringResource(R.string.news_list_view_details)
    Row(
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.spacedBy(6.dp),
    ) {
        Text(
            text = resolvedLabel,
            style = MaterialTheme.typography.labelLarge,
            fontWeight = FontWeight.Bold,
            color = BrandRed,
        )
        Icon(
            imageVector = Icons.AutoMirrored.Outlined.ArrowForward,
            contentDescription = null,
            tint = BrandRed,
            modifier = Modifier.size(18.dp),
        )
    }
}

@Composable
private fun NewsImage(
    article: NewsArticle,
    modifier: Modifier = Modifier,
) {
    val imageUrl = article.image1 ?: article.image2 ?: article.image3

    if (imageUrl != null) {
        AsyncImage(
            model = imageUrl,
            contentDescription = article.title,
            contentScale = ContentScale.Crop,
            modifier = modifier,
        )
    } else {
        Box(
            modifier = modifier
                .background(
                    Brush.linearGradient(
                        colors = listOf(
                            SurfaceContainerHighest,
                            SurfaceContainerLow,
                        )
                    )
                ),
        ) {
            Text(
                text = article.category?.uppercase() ?: "INA",
                style = MaterialTheme.typography.labelLarge,
                color = OnSurfaceVariant.copy(alpha = 0.7f),
                modifier = Modifier
                    .align(Alignment.Center)
                    .padding(12.dp),
            )
        }
    }
}
