package id.iiyh.inatrading.feature.home.presentation

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.Image
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.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.BusinessCenter
import androidx.compose.material.icons.outlined.Groups
import androidx.compose.material.icons.outlined.Hub
import androidx.compose.material.icons.outlined.Image
import androidx.compose.material.icons.outlined.Language
import androidx.compose.material.icons.outlined.OpenInNew
import androidx.compose.material.icons.outlined.RocketLaunch
import androidx.compose.material.icons.outlined.Storefront
import androidx.compose.material.icons.outlined.VerifiedUser
import androidx.compose.material.icons.outlined.WebAsset
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
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.graphics.vector.ImageVector
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import id.iiyh.inatrading.R
import id.iiyh.inatrading.core.ui.theme.AccentBlue
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.ManropeFontFamily
import id.iiyh.inatrading.core.ui.theme.OnSurface
import id.iiyh.inatrading.core.ui.theme.OnSurfaceVariant
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 HomeScreen(
    onNewsClick: (NewsArticle) -> Unit = {},
    onViewAllNews: () -> Unit = {},
    viewModel: HomeViewModel = hiltViewModel(),
) {
    val uiState by viewModel.uiState.collectAsState()

    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(Background)
            .verticalScroll(rememberScrollState()),
    ) {
        WhatIsInaSection()
        CorePillarsSection()
        WhoUsesSection()
        CaseStudiesSection()
        LatestNewsSection(
            articles     = uiState.latestNews,
            isLoading    = uiState.isLoadingNews,
            onNewsClick  = onNewsClick,
            onViewAll    = onViewAllNews,
        )
        Spacer(modifier = Modifier.height(16.dp))
    }
}

// ─── Section 1: What is INA Trading ──────────────────────────────────────────

@Composable
private fun WhatIsInaSection() {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .background(SurfaceContainerLow)
            .padding(horizontal = 24.dp)
            .padding(top = 32.dp, bottom = 32.dp),
        verticalArrangement = Arrangement.spacedBy(20.dp),
    ) {
        // Title
        Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
            Text(
                text = buildAnnotatedString {
                    append(stringResource(R.string.home_what_is_prefix))
                    withStyle(SpanStyle(color = BrandRed)) { append(stringResource(R.string.home_what_is_highlight)) }
                },
                fontFamily = ManropeFontFamily,
                fontWeight = FontWeight.ExtraBold,
                fontSize = 28.sp,
                color = OnSurface,
                lineHeight = 36.sp,
            )
            Text(
                text = stringResource(R.string.home_intro),
                style = MaterialTheme.typography.bodyMedium,
                color = OnSurfaceVariant,
                lineHeight = 22.sp,
            )
        }

        // Card 1 — Hybrid B2B
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .clip(RoundedCornerShape(16.dp))
                .background(SurfaceContainerLowest)
                .padding(24.dp),
            verticalArrangement = Arrangement.spacedBy(16.dp),
        ) {
            Box(
                modifier = Modifier
                    .size(48.dp)
                    .clip(RoundedCornerShape(12.dp))
                    .background(BrandRed.copy(alpha = 0.10f)),
                contentAlignment = Alignment.Center,
            ) {
                Icon(Icons.Outlined.Hub, contentDescription = null, tint = BrandRed, modifier = Modifier.size(24.dp))
            }
            Text(
                text = stringResource(R.string.home_hybrid_title),
                fontFamily = ManropeFontFamily,
                fontWeight = FontWeight.Bold,
                fontSize = 20.sp,
                color = OnSurface,
            )
            Text(
                text = stringResource(R.string.home_hybrid_desc),
                style = MaterialTheme.typography.bodyMedium,
                color = OnSurfaceVariant,
                lineHeight = 22.sp,
            )
            Image(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(160.dp)
                    .clip(RoundedCornerShape(12.dp)),
                painter = painterResource(R.drawable.logistic),
                contentDescription = stringResource(R.string.home_logistics_dashboard),
                contentScale = ContentScale.Crop,
            )
        }

        // Card 2 — Nusantara Modernity (gradient)
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .clip(RoundedCornerShape(16.dp))
                .background(
                    Brush.linearGradient(
                        colors = listOf(AccentPurple, Color(0xFF865FCB)),
                    )
                )
                .padding(24.dp),
            verticalArrangement = Arrangement.spacedBy(12.dp),
        ) {
            Text(
                text = stringResource(R.string.home_nusantara_title),
                fontFamily = ManropeFontFamily,
                fontWeight = FontWeight.Bold,
                fontSize = 20.sp,
                color = Color.White,
            )
            Text(
                text = stringResource(R.string.home_nusantara_desc),
                style = MaterialTheme.typography.bodyMedium,
                color = Color.White.copy(alpha = 0.85f),
                lineHeight = 22.sp,
            )
            Spacer(modifier = Modifier.height(8.dp))
            Text(
                text = "15k+",
                fontFamily = ManropeFontFamily,
                fontWeight = FontWeight.Black,
                fontSize = 40.sp,
                color = Color.White,
            )
            Text(
                text = stringResource(R.string.home_verified_merchants),
                style = MaterialTheme.typography.labelSmall,
                color = Color.White.copy(alpha = 0.65f),
                letterSpacing = 2.sp,
            )
        }
    }
}

// ─── Section 2: Core Pillars ──────────────────────────────────────────────────

@Composable
private fun CorePillarsSection() {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .background(Background)
            .padding(horizontal = 24.dp)
            .padding(top = 36.dp, bottom = 36.dp),
        verticalArrangement = Arrangement.spacedBy(32.dp),
    ) {
        // Feature list
        Column(verticalArrangement = Arrangement.spacedBy(28.dp)) {
            PillarItem(
                icon = Icons.Outlined.Language,
                iconTint = BrandRed,
                iconBg = BrandRed.copy(alpha = 0.10f),
                title = stringResource(R.string.home_global_reach),
                desc = stringResource(R.string.home_global_reach_desc),
            )
            PillarItem(
                icon = Icons.Outlined.WebAsset,
                iconTint = AccentBlue,
                iconBg = AccentBlue.copy(alpha = 0.10f),
                title = stringResource(R.string.home_digital_integration),
                desc = stringResource(R.string.home_digital_integration_desc),
            )
            PillarItem(
                icon = Icons.Outlined.VerifiedUser,
                iconTint = AccentPurple,
                iconBg = AccentPurple.copy(alpha = 0.10f),
                title = stringResource(R.string.home_secure_transaction),
                desc = stringResource(R.string.home_secure_transaction_desc),
            )
        }

        // Staggered image placeholders
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.spacedBy(12.dp),
        ) {
            Image(
                modifier = Modifier
                    .weight(1f)
                    .aspectRatio(3f / 4f)
                    .offset(y = (-16).dp)
                    .clip(RoundedCornerShape(16.dp)),
                painter = painterResource(R.drawable.kerajinan),
                contentDescription = stringResource(R.string.home_craftsmanship),
                contentScale = ContentScale.Crop,
            )
            Image(
                modifier = Modifier
                    .weight(1f)
                    .aspectRatio(3f / 4f)
                    .offset(y = 16.dp)
                    .clip(RoundedCornerShape(16.dp)),
                painter = painterResource(R.drawable.tech),
                contentDescription = stringResource(R.string.home_tech_interface),
                contentScale = ContentScale.Crop,
            )
        }
    }
}

@Composable
private fun PillarItem(
    icon: ImageVector,
    iconTint: Color,
    iconBg: Color,
    title: String,
    desc: String,
) {
    Row(
        horizontalArrangement = Arrangement.spacedBy(16.dp),
        verticalAlignment = Alignment.Top,
    ) {
        Box(
            modifier = Modifier
                .size(52.dp)
                .clip(RoundedCornerShape(14.dp))
                .background(iconBg),
            contentAlignment = Alignment.Center,
        ) {
            Icon(icon, contentDescription = null, tint = iconTint, modifier = Modifier.size(26.dp))
        }
        Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
            Text(
                text = title,
                fontFamily = ManropeFontFamily,
                fontWeight = FontWeight.Bold,
                fontSize = 16.sp,
                color = OnSurface,
            )
            Text(
                text = desc,
                style = MaterialTheme.typography.bodySmall,
                color = OnSurfaceVariant,
                lineHeight = 20.sp,
            )
        }
    }
}

// ─── Section 3: Who Uses ──────────────────────────────────────────────────────

@Composable
private fun WhoUsesSection() {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .background(SurfaceContainerHighest.copy(alpha = 0.30f))
            .padding(horizontal = 24.dp)
            .padding(top = 32.dp, bottom = 32.dp),
        verticalArrangement = Arrangement.spacedBy(20.dp),
    ) {
        Text(
            text = buildAnnotatedString {
                append(stringResource(R.string.home_who_uses_prefix))
                withStyle(SpanStyle(color = BrandRed)) { append(stringResource(R.string.home_what_is_highlight)) }
            },
            fontFamily = ManropeFontFamily,
            fontWeight = FontWeight.ExtraBold,
            fontSize = 24.sp,
            color = OnSurface,
            textAlign = TextAlign.Center,
            modifier = Modifier.fillMaxWidth(),
        )

        // 2x2 grid
        val users = listOf(
            Triple(Icons.Outlined.Storefront,      BrandRed,    stringResource(R.string.home_msmes)),
            Triple(Icons.Outlined.Groups,           AccentBlue,  stringResource(R.string.home_aggregators)),
            Triple(Icons.Outlined.RocketLaunch,     AccentPurple,stringResource(R.string.home_exporters)),
            Triple(Icons.Outlined.BusinessCenter,   OnSurface,   stringResource(R.string.home_business_owners)),
        )
        Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
            users.chunked(2).forEach { pair ->
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(12.dp),
                ) {
                    pair.forEach { (icon, tint, label) ->
                        WhoUsesCard(
                            modifier = Modifier.weight(1f),
                            icon = icon,
                            iconTint = tint,
                            label = label,
                        )
                    }
                }
            }
        }
    }
}

@Composable
private fun WhoUsesCard(
    icon: ImageVector,
    iconTint: Color,
    label: String,
    modifier: Modifier = Modifier,
) {
    Column(
        modifier = modifier
            .clip(RoundedCornerShape(16.dp))
            .background(SurfaceContainerLowest)
            .padding(20.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.spacedBy(12.dp),
    ) {
        Icon(icon, contentDescription = null, tint = iconTint, modifier = Modifier.size(36.dp))
        Text(
            text = label,
            fontFamily = ManropeFontFamily,
            fontWeight = FontWeight.Bold,
            fontSize = 14.sp,
            color = OnSurface,
            textAlign = TextAlign.Center,
        )
    }
}

// ─── Section 4: Case Studies ──────────────────────────────────────────────────

@Composable
private fun CaseStudiesSection() {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .background(Background)
            .padding(horizontal = 24.dp)
            .padding(top = 36.dp, bottom = 36.dp),
        verticalArrangement = Arrangement.spacedBy(24.dp),
    ) {
        Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
            Text(
                text = stringResource(R.string.home_case_studies),
                style = MaterialTheme.typography.labelSmall,
                fontWeight = FontWeight.Bold,
                color = BrandRed,
                letterSpacing = 2.sp,
            )
            Text(
                text = stringResource(R.string.home_real_world_examples),
                fontFamily = ManropeFontFamily,
                fontWeight = FontWeight.ExtraBold,
                fontSize = 26.sp,
                color = OnSurface,
            )
        }

        CaseStudyCard(
            overlayColor = AccentBlue.copy(alpha = 0.40f),
            title = stringResource(R.string.home_case_coffee_title),
            desc = stringResource(R.string.home_case_coffee_desc),
            imageRes = R.drawable.restoran,
            imageLabel = stringResource(R.string.home_case_coffee_label),
        )
        CaseStudyCard(
            overlayColor = BrandRed.copy(alpha = 0.40f),
            title = stringResource(R.string.home_case_restaurant_title),
            desc = stringResource(R.string.home_case_restaurant_desc),
            imageRes = R.drawable.coffee,
            imageLabel = stringResource(R.string.home_case_restaurant_label),
        )
    }
}

@Composable
private fun CaseStudyCard(
    overlayColor: Color,
    title: String,
    desc: String,
    imageRes: Int,
    imageLabel: String,
) {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .clip(RoundedCornerShape(16.dp))
            .clickable(
                interactionSource = remember { MutableInteractionSource() },
                indication = ripple(),
                onClick = {},
            ),
        verticalArrangement = Arrangement.spacedBy(12.dp),
    ) {
        // Image with overlay
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .aspectRatio(16f / 9f)
                .clip(RoundedCornerShape(20.dp)),
        ) {
            Image(
                modifier = Modifier.fillMaxSize(),
                painter = painterResource(imageRes),
                contentDescription = imageLabel,
                contentScale = ContentScale.Crop,
            )
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .background(overlayColor),
            )
        }

        Text(
            text = title,
            fontFamily = ManropeFontFamily,
            fontWeight = FontWeight.Bold,
            fontSize = 20.sp,
            color = OnSurface,
        )
        Text(
            text = desc,
            style = MaterialTheme.typography.bodyMedium,
            color = OnSurfaceVariant,
            lineHeight = 22.sp,
        )
    }
}

// ─── Section 5: Latest News ───────────────────────────────────────────────────

@Composable
private fun LatestNewsSection(
    articles: List<NewsArticle>,
    isLoading: Boolean,
    onNewsClick: (NewsArticle) -> Unit,
    onViewAll: () -> Unit,
) {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .background(SurfaceContainerLow)
            .padding(horizontal = 24.dp)
            .padding(top = 32.dp, bottom = 32.dp),
        verticalArrangement = Arrangement.spacedBy(20.dp),
    ) {
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically,
        ) {
            Text(
                text = stringResource(R.string.home_latest_news),
                fontFamily = ManropeFontFamily,
                fontWeight = FontWeight.ExtraBold,
                fontSize = 22.sp,
                color = OnSurface,
            )
            Row(
                horizontalArrangement = Arrangement.spacedBy(4.dp),
                verticalAlignment = Alignment.CenterVertically,
                modifier = Modifier.clickable(
                    interactionSource = remember { MutableInteractionSource() },
                    indication = ripple(bounded = false),
                    onClick = onViewAll,
                ),
            ) {
                Text(
                    text = stringResource(R.string.home_view_all),
                    style = MaterialTheme.typography.labelMedium,
                    fontWeight = FontWeight.Bold,
                    color = BrandRed,
                )
                Icon(Icons.Outlined.OpenInNew, contentDescription = null, tint = BrandRed, modifier = Modifier.size(14.dp))
            }
        }

        when {
            isLoading -> {
                Box(
                    modifier = Modifier.fillMaxWidth().height(120.dp),
                    contentAlignment = Alignment.Center,
                ) {
                    CircularProgressIndicator(color = BrandRed, modifier = Modifier.size(32.dp))
                }
            }
            articles.isEmpty() -> {
                Text(
                    text = stringResource(R.string.home_no_news),
                    style = MaterialTheme.typography.bodyMedium,
                    color = OnSurfaceVariant,
                    modifier = Modifier.fillMaxWidth(),
                    textAlign = TextAlign.Center,
                )
            }
            else -> {
                Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
                    articles.forEach { article ->
                        NewsCard(article = article, onClick = { onNewsClick(article) })
                    }
                }
            }
        }
    }
}

@Composable
private fun NewsCard(article: NewsArticle, onClick: () -> Unit) {
    val summary = article.summary?.takeIf { it.isNotBlank() } ?: article.subtitle.orEmpty()

    Column(
        modifier = Modifier
            .fillMaxWidth()
            .clip(RoundedCornerShape(16.dp))
            .background(SurfaceContainerLowest)
            .clickable(
                interactionSource = remember { MutableInteractionSource() },
                indication = ripple(),
                onClick = onClick,
            )
            .padding(20.dp),
        verticalArrangement = Arrangement.spacedBy(8.dp),
    ) {
        if (!article.category.isNullOrBlank()) {
            Text(
                text = article.category.uppercase(),
                style = MaterialTheme.typography.labelSmall.copy(fontSize = 9.sp),
                fontWeight = FontWeight.Bold,
                color = OnSurfaceVariant,
                letterSpacing = 1.sp,
            )
        }
        Text(
            text = article.title,
            fontFamily = ManropeFontFamily,
            fontWeight = FontWeight.Bold,
            fontSize = 15.sp,
            color = OnSurface,
            lineHeight = 22.sp,
            maxLines = 2,
            overflow = TextOverflow.Ellipsis,
        )
        if (summary.isNotBlank()) {
            Text(
                text = summary,
                style = MaterialTheme.typography.bodySmall,
                color = OnSurfaceVariant,
                lineHeight = 20.sp,
                maxLines = 3,
                overflow = TextOverflow.Ellipsis,
            )
        }
    }
}

// ─── Shared: Image Placeholder ────────────────────────────────────────────────

@Composable
private fun ImagePlaceholder(
    modifier: Modifier = Modifier,
    label: String = "",
) {
    Box(
        modifier = modifier.background(SurfaceContainerHighest),
        contentAlignment = Alignment.Center,
    ) {
        Column(
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.spacedBy(6.dp),
        ) {
            Icon(
                Icons.Outlined.Image,
                contentDescription = null,
                tint = OnSurfaceVariant.copy(alpha = 0.35f),
                modifier = Modifier.size(32.dp),
            )
            if (label.isNotEmpty()) {
                Text(
                    text = label,
                    style = MaterialTheme.typography.labelSmall,
                    color = OnSurfaceVariant.copy(alpha = 0.45f),
                )
            }
        }
    }
}
