package id.iiyh.inatrading.feature.product.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.PaddingValues
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.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.itemsIndexed
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.ArrowBack
import androidx.compose.material.icons.outlined.Battery6Bar
import androidx.compose.material.icons.outlined.CheckCircle
import androidx.compose.material.icons.outlined.Inventory2
import androidx.compose.material.icons.outlined.PhotoCamera
import androidx.compose.material.icons.outlined.Public
import androidx.compose.material.icons.outlined.ShoppingCart
import androidx.compose.material.icons.outlined.Verified
import androidx.compose.material.icons.outlined.Warning
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.material3.ripple
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
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.vector.ImageVector
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.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.text.HtmlCompat
import androidx.hilt.navigation.compose.hiltViewModel
import coil.compose.AsyncImage
import id.iiyh.inatrading.R
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.SurfaceContainerHighest
import id.iiyh.inatrading.core.ui.theme.SurfaceContainerLow
import id.iiyh.inatrading.core.ui.theme.SurfaceContainerLowest
import id.iiyh.inatrading.feature.product.data.model.ComplianceInformation
import id.iiyh.inatrading.feature.product.data.model.ProductDetail
import id.iiyh.inatrading.feature.product.data.model.ProductImage
import id.iiyh.inatrading.feature.product.data.model.ProductInformation
import id.iiyh.inatrading.feature.product.data.model.ProductModel
import java.text.NumberFormat
import java.util.Locale

@Composable
fun ProductDetailScreen(
    onBack: () -> Unit,
    onLoginRequired: () -> Unit = {},
    onSessionExpired: () -> Unit = onLoginRequired,
    onCartAdded: () -> Unit = {},
    cartItemCount: Int = 0,
    onCartClick: () -> Unit = {},
    viewModel: ProductDetailViewModel = hiltViewModel(),
) {
    val uiState by viewModel.uiState.collectAsState()
    val snackbarHostState = remember { SnackbarHostState() }
    val cartAddedMessage = stringResource(R.string.cart_add_success)

    LaunchedEffect(uiState.cartMessage) {
        uiState.cartMessage?.let { message ->
            snackbarHostState.showSnackbar(
                if (message == CART_ADDED_MESSAGE) cartAddedMessage else message,
            )
            if (message == CART_ADDED_MESSAGE) {
                onCartAdded()
            }
            viewModel.consumeCartMessage()
        }
    }

    LaunchedEffect(uiState.sessionExpired) {
        if (uiState.sessionExpired) {
            viewModel.consumeSessionExpired()
            onSessionExpired()
        }
    }

    Scaffold(
        topBar = {
            ProductDetailTopBar(
                onBack = onBack,
                cartItemCount = cartItemCount,
                onCartClick = onCartClick,
            )
        },
        snackbarHost = { SnackbarHost(snackbarHostState) },
        bottomBar = {
            uiState.product?.let { product ->
                ProductDetailBottomBar(
                    product = product,
                    isAddingToCart = uiState.isAddingToCart,
                    canAddToCart = uiState.canAddToCart,
                    onAddToCart = {
                        if (uiState.isLoggedIn) {
                            viewModel.addToCart()
                        } else {
                            onLoginRequired()
                        }
                    },
                )
            }
        },
        containerColor = Background,
    ) { innerPadding ->
        when {
            uiState.isLoading -> {
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(innerPadding),
                    contentAlignment = Alignment.Center,
                ) {
                    CircularProgressIndicator(color = BrandRed)
                }
            }

            uiState.errorMessage != null -> {
                ErrorState(
                    message = uiState.errorMessage!!,
                    onRetry = viewModel::loadProduct,
                    modifier = Modifier.padding(innerPadding),
                )
            }

            uiState.product != null -> {
                ProductDetailContent(
                    product = uiState.product!!,
                    modifier = Modifier.padding(innerPadding),
                )
            }
        }
    }
}

@Composable
private fun ProductDetailTopBar(
    onBack: () -> Unit,
    cartItemCount: Int,
    onCartClick: () -> Unit,
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .background(Color.White.copy(alpha = 0.88f))
            .padding(horizontal = 20.dp, vertical = 14.dp),
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.SpaceBetween,
    ) {
        Row(
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.spacedBy(12.dp),
        ) {
            TopBarIcon(
                icon = Icons.AutoMirrored.Outlined.ArrowBack,
                onClick = onBack,
            )
            Text(
                text = stringResource(R.string.product_detail_title),
                fontFamily = ManropeFontFamily,
                fontWeight = FontWeight.Bold,
                fontSize = 18.sp,
                color = BrandRed,
            )
        }

        Box {
            TopBarIcon(
                icon = Icons.Outlined.ShoppingCart,
                onClick = onCartClick,
            )
            if (cartItemCount > 0) {
                Box(
                    modifier = Modifier
                        .size(16.dp)
                        .offset(x = 8.dp, y = (-4).dp)
                        .background(BrandRed, CircleShape)
                        .align(Alignment.TopEnd),
                    contentAlignment = Alignment.Center,
                ) {
                    Text(
                        text = if (cartItemCount > 9) "9+" else cartItemCount.toString(),
                        style = MaterialTheme.typography.labelSmall.copy(fontSize = 9.sp),
                        color = Color.White,
                    )
                }
            }
        }
    }
}

@Composable
private fun ProductDetailContent(
    product: ProductDetail,
    modifier: Modifier = Modifier,
) {
    val model = product.primaryModel()
    val gallery = product.galleryImages()
    var selectedImageIndex by rememberSaveable(product.id) { mutableIntStateOf(0) }

    LaunchedEffect(gallery.size) {
        if (selectedImageIndex >= gallery.size) selectedImageIndex = 0
    }

    LazyColumn(
        modifier = modifier
            .fillMaxSize()
            .background(Background),
        contentPadding = PaddingValues(start = 24.dp, end = 24.dp, top = 20.dp, bottom = 112.dp),
        verticalArrangement = Arrangement.spacedBy(20.dp),
    ) {
        item {
            ProductGallerySection(
                product = product,
                gallery = gallery,
                selectedImageIndex = selectedImageIndex,
                onImageSelected = { selectedImageIndex = it },
            )
        }

        item {
            ProductSummarySection(product = product, model = model)
        }

        if (product.productFeatures.isNotEmpty()) {
            item {
                FeatureCardList(features = product.productFeatures)
            }
        }

        item {
            OverviewStatsSection(product = product, model = model)
        }

        product.complianceInformation?.takeIf { it.hasVisibleData() }?.let { compliance ->
            item {
                ComplianceWarningSection(compliance = compliance)
            }
        }

        item {
            DetailedSpecificationsSection(product = product, model = model)
        }

        if (product.productKeyWords.isNotEmpty()) {
            item {
                KeywordSection(product.productKeyWords)
            }
        }
    }
}

@Composable
private fun ProductGallerySection(
    product: ProductDetail,
    gallery: List<String>,
    selectedImageIndex: Int,
    onImageSelected: (Int) -> Unit,
) {
    val selectedImage = gallery.getOrNull(selectedImageIndex)

    Column(verticalArrangement = Arrangement.spacedBy(14.dp)) {
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .aspectRatio(16f / 10f)
                .clip(RoundedCornerShape(24.dp))
                .background(SurfaceContainerLow),
        ) {
            if (selectedImage != null) {
                AsyncImage(
                    model = selectedImage,
                    contentDescription = product.name,
                    contentScale = ContentScale.Crop,
                    modifier = Modifier.fillMaxSize(),
                )
            }

            Column(
                modifier = Modifier
                    .align(Alignment.TopStart)
                    .padding(18.dp),
                verticalArrangement = Arrangement.spacedBy(8.dp),
            ) {
                if (product.isNew) {
                    EditorialBadge(
                        text = stringResource(R.string.product_detail_status_new),
                        container = AccentPurpleContainer,
                        content = AccentPurple,
                    )
                }
                if (product.isEligibleToExport) {
                    EditorialBadge(
                        text = stringResource(R.string.product_detail_status_export),
                        container = AccentBlue,
                        content = Color.White,
                        icon = Icons.Outlined.Public,
                    )
                }
            }

            Box(
                modifier = Modifier
                    .align(Alignment.BottomEnd)
                    .padding(18.dp)
                    .size(116.dp)
                    .background(
                        SurfaceContainerHighest.copy(alpha = 0.18f),
                        RoundedCornerShape(26.dp),
                    )
            )
        }

        if (gallery.isNotEmpty()) {
            Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
                gallery.take(3).forEachIndexed { index, image ->
                    AsyncImage(
                        model = image,
                        contentDescription = null,
                        contentScale = ContentScale.Crop,
                        modifier = Modifier
                            .weight(1f)
                            .aspectRatio(1f)
                            .clip(RoundedCornerShape(16.dp))
                            .background(SurfaceContainerLow)
                            .clickable(
                                interactionSource = remember { MutableInteractionSource() },
                                indication = ripple(),
                                onClick = { onImageSelected(index) },
                            )
                            .then(
                                if (selectedImageIndex == index) Modifier.background(BrandRedContainer)
                                else Modifier
                            ),
                    )
                }
                if (gallery.size > 3) {
                    Box(
                        modifier = Modifier
                            .weight(1f)
                            .aspectRatio(1f)
                            .clip(RoundedCornerShape(16.dp))
                            .background(SurfaceContainerHighest)
                            .clickable(
                                interactionSource = remember { MutableInteractionSource() },
                                indication = ripple(),
                                onClick = { onImageSelected(3) },
                            ),
                        contentAlignment = Alignment.Center,
                    ) {
                        Text(
                            text = "+${gallery.size - 3}",
                            fontFamily = ManropeFontFamily,
                            fontWeight = FontWeight.Bold,
                            color = OnSurfaceVariant,
                        )
                    }
                }
            }
        }
    }
}

@Composable
private fun ProductSummarySection(
    product: ProductDetail,
    model: ProductModel?,
) {
    val eyebrow = buildList {
        product.brand()?.takeIf(String::isNotBlank)?.let(::add)
        product.categoryLabel()?.takeIf(String::isNotBlank)?.let(::add)
    }.joinToString(" • ")

    Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
        if (eyebrow.isNotBlank()) {
            Text(
                text = eyebrow,
                style = MaterialTheme.typography.labelSmall,
                fontWeight = FontWeight.Bold,
                color = AccentPurple,
                letterSpacing = 2.sp,
            )
        }

        Text(
            text = product.name,
            fontFamily = ManropeFontFamily,
            fontWeight = FontWeight.ExtraBold,
            fontSize = 36.sp,
            lineHeight = 42.sp,
            color = OnSurface,
        )

        PriceBlock(model = model)

        product.description.orEmpty().toPlainText().takeIf(String::isNotBlank)?.let { description ->
            Text(
                text = description,
                style = MaterialTheme.typography.bodyMedium,
                color = OnSurfaceVariant,
                lineHeight = 24.sp,
            )
        }
    }
}

@Composable
private fun PriceBlock(model: ProductModel?) {
    val salePrice = model?.promotionPrice
    val regularPrice = model?.price
    Row(
        verticalAlignment = Alignment.Bottom,
        horizontalArrangement = Arrangement.spacedBy(12.dp),
    ) {
        Text(
            text = (salePrice ?: regularPrice).toDisplayPrice(),
            fontFamily = ManropeFontFamily,
            fontWeight = FontWeight.ExtraBold,
            fontSize = 28.sp,
            color = BrandRed,
        )
        if (salePrice != null && regularPrice != null && regularPrice > salePrice) {
            Text(
                text = regularPrice.toDisplayPrice(),
                style = MaterialTheme.typography.titleMedium,
                color = OnSurfaceVariant.copy(alpha = 0.6f),
            )
        }
    }
}

@Composable
private fun FeatureCardList(
    features: List<String>,
) {
    val icons = listOf(
        Icons.Outlined.CheckCircle,
        Icons.Outlined.Battery6Bar,
        Icons.Outlined.PhotoCamera,
    )
    val colors = listOf(BrandRed, AccentBlue, AccentPurple)
    val containers = listOf(BrandRedContainer, AccentBlueContainer, AccentPurpleContainer)

    Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
        features.take(3).forEachIndexed { index, feature ->
            FeatureCard(
                icon = icons[index % icons.size],
                iconTint = colors[index % colors.size],
                iconContainer = containers[index % containers.size],
                title = feature,
            )
        }
    }
}

@Composable
private fun FeatureCard(
    icon: ImageVector,
    iconTint: Color,
    iconContainer: Color,
    title: String,
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .clip(RoundedCornerShape(18.dp))
            .background(SurfaceContainerLow)
            .padding(16.dp),
        horizontalArrangement = Arrangement.spacedBy(14.dp),
        verticalAlignment = Alignment.CenterVertically,
    ) {
        Box(
            modifier = Modifier
                .size(48.dp)
                .clip(RoundedCornerShape(14.dp))
                .background(iconContainer),
            contentAlignment = Alignment.Center,
        ) {
            Icon(icon, contentDescription = null, tint = iconTint)
        }
        Text(
            text = title,
            fontFamily = ManropeFontFamily,
            fontWeight = FontWeight.Bold,
            color = OnSurface,
        )
    }
}

@Composable
private fun OverviewStatsSection(
    product: ProductDetail,
    model: ProductModel?,
) {
    val stock = model?.warehouses?.sumOf { it.stock }?.takeIf { it > 0 }
    val warranty = product.warrantyInformation?.formattedText()

    if (stock == null && warranty == null) return

    Row(horizontalArrangement = Arrangement.spacedBy(14.dp)) {
        warranty?.let {
            StatCard(
                modifier = Modifier.weight(1f),
                icon = Icons.Outlined.Verified,
                iconTint = BrandRed,
                label = stringResource(R.string.product_detail_warranty),
                value = it,
            )
        }
        stock?.let {
            StatCard(
                modifier = Modifier.weight(1f),
                icon = Icons.Outlined.Inventory2,
                iconTint = AccentBlue,
                label = stringResource(R.string.product_detail_stock),
                value = stringResource(R.string.product_detail_stock_available, it),
            )
        }
    }
}

@Composable
private fun StatCard(
    label: String,
    value: String,
    icon: ImageVector,
    iconTint: Color,
    modifier: Modifier = Modifier,
) {
    Column(
        modifier = modifier
            .clip(RoundedCornerShape(18.dp))
            .background(SurfaceContainerLowest)
            .padding(18.dp),
        verticalArrangement = Arrangement.spacedBy(8.dp),
    ) {
        Icon(icon, contentDescription = null, tint = iconTint)
        Text(
            text = label.uppercase(),
            style = MaterialTheme.typography.labelSmall,
            color = OnSurfaceVariant,
            letterSpacing = 1.sp,
        )
        Text(
            text = value,
            fontFamily = ManropeFontFamily,
            fontWeight = FontWeight.Bold,
            color = OnSurface,
        )
    }
}

@Composable
private fun ComplianceWarningSection(
    compliance: ComplianceInformation,
) {
    val lines = buildList {
        compliance.safetyWarning?.takeIf(String::isNotBlank)?.let(::add)
        compliance.countryOfOrigin?.takeIf(String::isNotBlank)?.let {
            add(stringResource(R.string.product_detail_origin_value, it))
        }
    }
    if (lines.isEmpty()) return

    Row(
        modifier = Modifier
            .fillMaxWidth()
            .clip(RoundedCornerShape(18.dp))
            .background(BrandRedContainer.copy(alpha = 0.22f))
            .padding(16.dp),
        horizontalArrangement = Arrangement.spacedBy(12.dp),
        verticalAlignment = Alignment.Top,
    ) {
        Icon(
            imageVector = Icons.Outlined.Warning,
            contentDescription = null,
            tint = BrandRed,
            modifier = Modifier.padding(top = 2.dp),
        )
        Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
            Text(
                text = stringResource(R.string.product_detail_safety_warning),
                style = MaterialTheme.typography.labelSmall,
                fontWeight = FontWeight.Bold,
                color = BrandRed,
                letterSpacing = 1.sp,
            )
            lines.forEach {
                Text(text = it, style = MaterialTheme.typography.bodyMedium, color = OnSurfaceVariant)
            }
        }
    }
}

@Composable
private fun DetailedSpecificationsSection(
    product: ProductDetail,
    model: ProductModel?,
) {
    val specifications = buildSpecifications(product, model)
    if (specifications.isEmpty()) return

    Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
        Text(
            text = stringResource(R.string.product_detail_detailed_specifications),
            fontFamily = ManropeFontFamily,
            fontWeight = FontWeight.Bold,
            fontSize = 28.sp,
            color = OnSurface,
        )

        specifications.forEach { (label, value) ->
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(vertical = 6.dp),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.Top,
            ) {
                Text(
                    text = label,
                    style = MaterialTheme.typography.bodyMedium,
                    color = OnSurfaceVariant,
                    modifier = Modifier.weight(1f),
                )
                Spacer(modifier = Modifier.width(16.dp))
                Text(
                    text = value,
                    style = MaterialTheme.typography.bodyMedium,
                    fontWeight = FontWeight.Bold,
                    color = OnSurface,
                    modifier = Modifier.weight(1f),
                    textAlign = TextAlign.End,
                )
            }
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(1.dp)
                    .background(SurfaceContainerHighest)
            )
        }
    }
}

@Composable
private fun KeywordSection(
    keywords: List<String>,
) {
    Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
        Text(
            text = stringResource(R.string.product_detail_keywords),
            fontFamily = ManropeFontFamily,
            fontWeight = FontWeight.Bold,
            fontSize = 18.sp,
            color = OnSurface,
        )
        LazyRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
            itemsIndexed(keywords) { _, keyword ->
                Box(
                    modifier = Modifier
                        .clip(RoundedCornerShape(999.dp))
                        .background(AccentPurpleContainer.copy(alpha = 0.3f))
                        .padding(horizontal = 14.dp, vertical = 8.dp),
                ) {
                    Text(
                        text = keyword,
                        style = MaterialTheme.typography.labelMedium,
                        color = AccentPurple,
                        fontWeight = FontWeight.Bold,
                    )
                }
            }
        }
    }
}

@Composable
private fun ProductDetailBottomBar(
    product: ProductDetail,
    isAddingToCart: Boolean,
    canAddToCart: Boolean,
    onAddToCart: () -> Unit,
) {
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .background(Color.White.copy(alpha = 0.95f))
            .padding(horizontal = 16.dp, vertical = 12.dp),
    ) {
        Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
            SecondaryBottomAction(
                text = stringResource(R.string.product_detail_add_to_cart),
                icon = Icons.Outlined.ShoppingCart,
                enabled = canAddToCart && !isAddingToCart,
                loading = isAddingToCart,
                onClick = onAddToCart,
                modifier = Modifier.weight(1f),
            )
            PrimaryBottomAction(
                text = stringResource(R.string.product_detail_buy_now),
                modifier = Modifier.weight(1.45f),
            )
        }
    }
}

@Composable
private fun SecondaryBottomAction(
    text: String,
    icon: ImageVector,
    enabled: Boolean,
    loading: Boolean,
    onClick: () -> Unit,
    modifier: Modifier = Modifier,
) {
    Row(
        modifier = modifier
            .height(56.dp)
            .clip(RoundedCornerShape(18.dp))
            .background(Color.White)
            .clickable(
                enabled = enabled && !loading,
                interactionSource = remember { MutableInteractionSource() },
                indication = ripple(),
                onClick = onClick,
            ),
        horizontalArrangement = Arrangement.Center,
        verticalAlignment = Alignment.CenterVertically,
    ) {
        if (loading) {
            CircularProgressIndicator(
                modifier = Modifier.size(18.dp),
                color = BrandRed,
                strokeWidth = 2.dp,
            )
        } else {
            Icon(icon, contentDescription = null, tint = OnSurface)
            Spacer(modifier = Modifier.width(8.dp))
            Text(
                text = text,
                color = OnSurface,
                fontWeight = FontWeight.Bold,
            )
        }
    }
}

@Composable
private fun PrimaryBottomAction(
    text: String,
    modifier: Modifier = Modifier,
) {
    Box(
        modifier = modifier
            .height(56.dp)
            .clip(RoundedCornerShape(18.dp))
            .background(Brush.linearGradient(listOf(BrandRed, Color(0xFFDB322F))))
            .clickable(
                interactionSource = remember { MutableInteractionSource() },
                indication = ripple(color = Color.White.copy(alpha = 0.18f)),
                onClick = {},
            ),
        contentAlignment = Alignment.Center,
    ) {
        Text(
            text = text,
            color = Color.White,
            fontWeight = FontWeight.Bold,
            fontFamily = ManropeFontFamily,
        )
    }
}

@Composable
private fun TopBarIcon(
    icon: ImageVector,
    onClick: () -> Unit,
) {
    Box(
        modifier = Modifier
            .size(40.dp)
            .clip(RoundedCornerShape(12.dp))
            .clickable(
                interactionSource = remember { MutableInteractionSource() },
                indication = ripple(),
                onClick = onClick,
            ),
        contentAlignment = Alignment.Center,
    ) {
        Icon(
            imageVector = icon,
            contentDescription = null,
            tint = OnSurfaceVariant,
        )
    }
}

@Composable
private fun EditorialBadge(
    text: String,
    container: Color,
    content: Color,
    icon: ImageVector? = null,
) {
    Row(
        modifier = Modifier
            .clip(RoundedCornerShape(999.dp))
            .background(container)
            .padding(horizontal = 12.dp, vertical = 8.dp),
        horizontalArrangement = Arrangement.spacedBy(6.dp),
        verticalAlignment = Alignment.CenterVertically,
    ) {
        if (icon != null) {
            Icon(icon, contentDescription = null, tint = content, modifier = Modifier.size(14.dp))
        }
        Text(
            text = text,
            style = MaterialTheme.typography.labelSmall,
            color = content,
            fontWeight = FontWeight.Bold,
            letterSpacing = 1.sp,
        )
    }
}

@Composable
private fun ErrorState(
    message: String,
    onRetry: () -> Unit,
    modifier: Modifier = Modifier,
) {
    Column(
        modifier = modifier
            .fillMaxSize()
            .padding(24.dp),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally,
    ) {
        Text(
            text = stringResource(R.string.product_detail_load_error),
            fontFamily = ManropeFontFamily,
            fontWeight = FontWeight.ExtraBold,
            fontSize = 24.sp,
            color = OnSurface,
        )
        Spacer(modifier = Modifier.height(8.dp))
        Text(
            text = message,
            style = MaterialTheme.typography.bodyMedium,
            color = OnSurfaceVariant,
            textAlign = TextAlign.Center,
        )
        Spacer(modifier = Modifier.height(20.dp))
        androidx.compose.material3.Button(onClick = onRetry) {
            Text(stringResource(R.string.product_detail_retry))
        }
    }
}

private fun ProductDetail.primaryModel(): ProductModel? = productModels.firstOrNull()

private fun ProductDetail.brand(): String? =
    productInformations.firstOrNull { it.paramName.equals("Brand", ignoreCase = true) }?.paramValue

private fun ProductDetail.categoryLabel(): String? =
    categoryInformations.firstOrNull()?.paramValue
        ?: subCategory?.name

private fun ProductDetail.galleryImages(): List<String> {
    val ordered = productImages
        .sortedBy(ProductImage::sequence)
        .mapNotNull { it.image }
    val fallback = listOfNotNull(image, primaryModel()?.image)
    return (ordered + fallback).distinct()
}

private fun ComplianceInformation.hasVisibleData(): Boolean =
    !safetyWarning.isNullOrBlank() || !countryOfOrigin.isNullOrBlank()

private fun id.iiyh.inatrading.feature.product.data.model.WarrantyInformation.formattedText(): String? {
    val durationText = duration?.takeIf { it > 0 }?.let {
        buildString {
            append(it)
            durationType?.takeIf(String::isNotBlank)?.let { type ->
                append(" ")
                append(type)
            }
        }
    }
    return listOfNotNull(type?.takeIf(String::isNotBlank), durationText).joinToString(" ").ifBlank { null }
}

@Composable
private fun buildSpecifications(
    product: ProductDetail,
    model: ProductModel?,
): List<Pair<String, String>> {
    val items = mutableListOf<Pair<String, String>>()

    product.brand()?.takeIf(String::isNotBlank)?.let {
        items += stringResource(R.string.product_detail_brand) to it
    }
    product.productInformations.firstOrNull { it.paramName.equals("Battery", ignoreCase = true) }?.paramValue
        ?.takeIf(String::isNotBlank)?.let {
            items += stringResource(R.string.product_detail_battery_capacity) to it
        }
    product.categoryLabel()?.takeIf(String::isNotBlank)?.let {
        items += stringResource(R.string.product_detail_category) to it
    }
    product.complianceInformation?.countryOfOrigin?.takeIf(String::isNotBlank)?.let {
        items += stringResource(R.string.product_detail_origin) to it
    }
    model?.sku?.takeIf(String::isNotBlank)?.let {
        items += stringResource(R.string.product_detail_sku) to it
    }
    model?.name?.takeIf(String::isNotBlank)?.let {
        items += stringResource(R.string.product_detail_model_name) to it
    }
    model?.weight?.let { weight ->
        model.weightType?.takeIf(String::isNotBlank)?.let { type ->
            items += stringResource(R.string.product_detail_weight) to "${trimTrailingZero(weight)} $type"
        }
    }
    model?.let { currentModel ->
        val parts = listOfNotNull(currentModel.length, currentModel.width, currentModel.height).map(::trimTrailingZero)
        if (parts.size == 3 && !currentModel.dimensionType.isNullOrBlank()) {
            items += stringResource(R.string.product_detail_dimensions) to
                "${parts[0]} x ${parts[1]} x ${parts[2]} ${currentModel.dimensionType.lowercase()}"
        }
    }
    product.warrantyInformation?.formattedText()?.let {
        items += stringResource(R.string.product_detail_warranty) to it
    }

    return items
}

private fun String.toPlainText(): String =
    HtmlCompat.fromHtml(this, HtmlCompat.FROM_HTML_MODE_LEGACY).toString().trim()

private fun trimTrailingZero(value: Double): String =
    if (value % 1.0 == 0.0) value.toInt().toString() else value.toString()

@Composable
private fun Double?.toDisplayPrice(): String {
    if (this == null || this <= 0.0) return stringResource(R.string.products_contact_price)
    return NumberFormat.getCurrencyInstance(Locale.forLanguageTag("id-ID"))
        .apply { maximumFractionDigits = 0 }
        .format(this)
        .replace("Rp", "Rp ")
}
