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.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.lazy.grid.rememberLazyGridState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.automirrored.outlined.ArrowForward
import androidx.compose.material.icons.outlined.FavoriteBorder
import androidx.compose.material.icons.outlined.LocationOn
import androidx.compose.material.icons.outlined.Public
import androidx.compose.material.icons.outlined.Search
import androidx.compose.material.icons.outlined.ShoppingCart
import androidx.compose.material.icons.outlined.Storefront
import androidx.compose.material.icons.outlined.Tune
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
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.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import androidx.compose.ui.draw.alpha
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.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
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.InaChip
import id.iiyh.inatrading.core.ui.components.InaChipVariant
import id.iiyh.inatrading.core.ui.components.InaPrimaryButton
import id.iiyh.inatrading.core.ui.components.InaTextField
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.ProductItem
import java.text.NumberFormat
import java.util.Locale
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.filter

@Composable
fun ProductsScreen(
    onProductClick: (ProductItem) -> Unit = {},
    onLoginRequired: () -> Unit = {},
    onSessionExpired: () -> Unit = onLoginRequired,
    viewModel: ProductsViewModel = hiltViewModel(),
) {
    val uiState by viewModel.uiState.collectAsState()
    val gridState = rememberLazyGridState()
    val snackbarHostState = remember { SnackbarHostState() }
    val favoriteAddedMessage = stringResource(R.string.products_favorite_added)
    val favoriteRemovedMessage = stringResource(R.string.products_favorite_removed)

    LaunchedEffect(gridState) {
        snapshotFlow {
            val layoutInfo = gridState.layoutInfo
            val lastVisible = layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: -1
            lastVisible to layoutInfo.totalItemsCount
        }
            .filter { (_, totalCount) -> totalCount > 0 }
            .distinctUntilChanged()
            .collect { (lastVisible, totalCount) ->
                if (lastVisible >= totalCount - 5) {
                    viewModel.loadNextPage()
                }
            }
    }

    LaunchedEffect(uiState.favoriteMessage) {
        uiState.favoriteMessage?.let {
            val message = when (it) {
                PRODUCT_FAVORITE_ADDED_MESSAGE -> favoriteAddedMessage
                PRODUCT_FAVORITE_REMOVED_MESSAGE -> favoriteRemovedMessage
                else -> it
            }
            snackbarHostState.showSnackbar(message)
            viewModel.consumeFavoriteMessage()
        }
    }

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

    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(Background),
    ) {
        LazyVerticalGrid(
            columns = GridCells.Fixed(2),
            state = gridState,
            modifier = Modifier.fillMaxSize(),
            contentPadding = PaddingValues(start = 16.dp, end = 16.dp, top = 20.dp, bottom = 112.dp),
            horizontalArrangement = Arrangement.spacedBy(12.dp),
            verticalArrangement = Arrangement.spacedBy(18.dp),
        ) {
            item(span = { androidx.compose.foundation.lazy.grid.GridItemSpan(maxLineSpan) }) {
                ProductsHero(
                    totalItem = uiState.totalItem,
                    totalLoaded = uiState.items.size,
                )
            }

            item(span = { androidx.compose.foundation.lazy.grid.GridItemSpan(maxLineSpan) }) {
                SearchAndActionRow(
                    query = uiState.searchQuery,
                    onQueryChange = viewModel::onSearchQueryChange,
                )
            }

            item(span = { androidx.compose.foundation.lazy.grid.GridItemSpan(maxLineSpan) }) {
                CategoryRow(
                    selected = uiState.selectedCategory,
                    onSelected = viewModel::onCategorySelected,
                )
            }

            when {
                uiState.isInitialLoading -> {
                    item(span = { androidx.compose.foundation.lazy.grid.GridItemSpan(maxLineSpan) }) {
                        CenterState(
                            title = stringResource(R.string.products_loading_title),
                            body = stringResource(R.string.products_loading_body),
                            loading = true,
                        )
                    }
                }
                uiState.errorMessage != null && uiState.items.isEmpty() -> {
                    item(span = { androidx.compose.foundation.lazy.grid.GridItemSpan(maxLineSpan) }) {
                        CenterState(
                            title = stringResource(R.string.products_error_title),
                            body = uiState.errorMessage!!,
                            actionLabel = stringResource(R.string.product_detail_retry),
                            onAction = viewModel::loadInitial,
                        )
                    }
                }
                uiState.filteredItems.isEmpty() -> {
                    item(span = { androidx.compose.foundation.lazy.grid.GridItemSpan(maxLineSpan) }) {
                        CenterState(
                            title = stringResource(R.string.products_empty_title),
                            body = stringResource(R.string.products_empty_body),
                        )
                    }
                }
                else -> {
                    items(uiState.filteredItems, key = { it.id }) { product ->
                        ProductCard(
                            product = product,
                            isFavorite = product.id in uiState.favoriteIds,
                            onFavoriteClick = {
                                if (uiState.isLoggedIn) {
                                    viewModel.toggleFavorite(product.id)
                                } else {
                                    onLoginRequired()
                                }
                            },
                            onClick = { onProductClick(product) },
                        )
                    }

                    if (uiState.isAppending) {
                        item(span = { androidx.compose.foundation.lazy.grid.GridItemSpan(maxLineSpan) }) {
                            Row(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(vertical = 8.dp),
                                horizontalArrangement = Arrangement.Center,
                            ) {
                                CircularProgressIndicator(
                                    color = BrandRed,
                                    modifier = Modifier.size(28.dp),
                                    strokeWidth = 2.5.dp,
                                )
                            }
                        }
                    }
                }
            }
        }

        SnackbarHost(
            hostState = snackbarHostState,
            modifier = Modifier
                .align(Alignment.BottomCenter)
                .padding(bottom = 88.dp),
        )
    }

    if (uiState.favoriteDialogOpen) {
        FavoritePickerDialog(
            groups = uiState.favoriteGroups,
            createMode = uiState.favoriteCreateMode,
            isLoading = uiState.favoriteActionLoading,
            onDismiss = viewModel::dismissFavoriteDialog,
            onCreateMode = viewModel::showCreateFavoriteGroup,
            onCancelCreate = viewModel::hideCreateFavoriteGroup,
            onCreateGroup = viewModel::createFavoriteGroup,
            onSelectGroup = viewModel::addProductToFavorite,
        )
    }
}

@Composable
private fun ProductsHero(
    totalItem: Int,
    totalLoaded: Int,
) {
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .clip(RoundedCornerShape(28.dp))
            .background(
                Brush.linearGradient(
                    colors = listOf(
                        SurfaceContainerLowest,
                        SurfaceContainerLow,
                    )
                )
            )
            .padding(20.dp),
    ) {
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .height(220.dp)
                .clip(RoundedCornerShape(36.dp))
                .background(SurfaceContainerHighest.copy(alpha = 0.35f)),
        )

        Column(verticalArrangement = Arrangement.spacedBy(16.dp)) {
            Text(
                text = stringResource(R.string.products_limited_edition),
                style = MaterialTheme.typography.labelSmall,
                color = AccentBlue,
                fontWeight = FontWeight.Bold,
                letterSpacing = 2.sp,
            )
            Text(
                text = stringResource(R.string.products_hero_title),
                fontFamily = ManropeFontFamily,
                fontWeight = FontWeight.ExtraBold,
                fontSize = 34.sp,
                lineHeight = 40.sp,
                color = OnSurface,
            )
            Text(
                text = stringResource(R.string.products_hero_body),
                style = MaterialTheme.typography.bodyMedium,
                color = OnSurfaceVariant,
                lineHeight = 22.sp,
                modifier = Modifier.fillMaxWidth(0.85f),
            )
            Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                HeroStat(
                    label = stringResource(R.string.products_loaded),
                    value = totalLoaded.toString(),
                    containerColor = BrandRedContainer,
                    contentColor = BrandRed,
                )
                HeroStat(
                    label = stringResource(R.string.products_catalog),
                    value = if (totalItem > 0) totalItem.toString() else "0",
                    containerColor = AccentPurpleContainer,
                    contentColor = AccentPurple,
                )
            }
        }
    }
}

@Composable
private fun HeroStat(
    label: String,
    value: String,
    containerColor: Color,
    contentColor: Color,
) {
    Column(
        modifier = Modifier
            .clip(RoundedCornerShape(16.dp))
            .background(containerColor)
            .padding(horizontal = 14.dp, vertical = 10.dp),
        verticalArrangement = Arrangement.spacedBy(2.dp),
    ) {
        Text(
            text = label.uppercase(),
            style = MaterialTheme.typography.labelSmall,
            color = contentColor,
            letterSpacing = 1.sp,
        )
        Text(
            text = value,
            fontFamily = ManropeFontFamily,
            fontWeight = FontWeight.ExtraBold,
            fontSize = 18.sp,
            color = contentColor,
        )
    }
}

@Composable
private fun SearchAndActionRow(
    query: String,
    onQueryChange: (String) -> Unit,
) {
    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.spacedBy(12.dp),
        verticalAlignment = Alignment.CenterVertically,
    ) {
        Box(modifier = Modifier.weight(1f)) {
            InaTextField(
                value = query,
                onValueChange = onQueryChange,
                placeholder = stringResource(R.string.products_search_placeholder),
                keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text),
                modifier = Modifier.fillMaxWidth(),
                leadingIcon = {
                    Icon(
                        imageVector = Icons.Outlined.Search,
                        contentDescription = null,
                        tint = OnSurfaceVariant,
                        modifier = Modifier.size(20.dp),
                    )
                },
            )
        }
        IconActionButton(
            icon = Icons.Outlined.Tune,
            contentDescription = stringResource(R.string.products_filter),
        )
    }
}

@Composable
private fun CategoryRow(
    selected: ProductCategory,
    onSelected: (ProductCategory) -> Unit,
) {
    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.spacedBy(10.dp),
    ) {
        ProductCategory.entries.forEach { category ->
            InaChip(
                label = category.label,
                variant = when (category) {
                    ProductCategory.All -> InaChipVariant.Promo
                    ProductCategory.Local -> InaChipVariant.Category
                    ProductCategory.International -> InaChipVariant.Featured
                },
                selected = selected == category,
                onClick = { onSelected(category) },
            )
        }
    }
}

@Composable
private fun ProductCard(
    product: ProductItem,
    isFavorite: Boolean,
    onFavoriteClick: () -> Unit,
    onClick: () -> Unit,
) {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .clickable(
                interactionSource = remember { MutableInteractionSource() },
                indication = ripple(),
                onClick = onClick,
            ),
        verticalArrangement = Arrangement.spacedBy(10.dp),
    ) {
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .aspectRatio(4f / 5f)
                .clip(RoundedCornerShape(18.dp))
                .background(SurfaceContainerLow),
        ) {
            if (product.image != null) {
                AsyncImage(
                    model = product.image,
                    contentDescription = product.name,
                    contentScale = ContentScale.Crop,
                    modifier = Modifier.fillMaxSize(),
                )
            } else {
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .background(
                            Brush.linearGradient(
                                colors = listOf(
                                    SurfaceContainerHighest,
                                    SurfaceContainerLow,
                                )
                            )
                        ),
                    contentAlignment = Alignment.Center,
                ) {
                    Column(horizontalAlignment = Alignment.CenterHorizontally) {
                        Icon(
                            imageVector = Icons.Outlined.Storefront,
                            contentDescription = null,
                            tint = OnSurfaceVariant.copy(alpha = 0.75f),
                            modifier = Modifier.size(30.dp),
                        )
                        Spacer(modifier = Modifier.height(6.dp))
                        Text(
                            text = product.market ?: stringResource(R.string.app_name),
                            style = MaterialTheme.typography.labelSmall,
                            color = OnSurfaceVariant.copy(alpha = 0.75f),
                        )
                    }
                }
            }

            FavoriteButton(
                isFavorite = isFavorite,
                onClick = onFavoriteClick,
                modifier = Modifier
                    .align(Alignment.TopEnd)
                    .padding(10.dp),
            )

            MarketBadge(
                market = product.market,
                modifier = Modifier
                    .align(Alignment.BottomStart)
                    .padding(10.dp),
            )
        }

        Column(
            modifier = Modifier.padding(horizontal = 2.dp),
            verticalArrangement = Arrangement.spacedBy(6.dp),
        ) {
            Text(
                text = product.name,
                fontFamily = ManropeFontFamily,
                fontWeight = FontWeight.Bold,
                fontSize = 15.sp,
                lineHeight = 20.sp,
                color = OnSurface,
                maxLines = 2,
                overflow = TextOverflow.Ellipsis,
            )
            ProductMetaRow(product = product)
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.Bottom,
            ) {
                Column(
                    modifier = Modifier.weight(1f),
                    verticalArrangement = Arrangement.spacedBy(2.dp),
                ) {
                    Text(
                        text = stringResource(R.string.products_price),
                        style = MaterialTheme.typography.labelSmall,
                        color = OnSurfaceVariant,
                    )
                    Text(
                        text = product.displayPrice(),
                        fontFamily = ManropeFontFamily,
                        fontWeight = FontWeight.ExtraBold,
                        fontSize = 15.sp,
                        lineHeight = 18.sp,
                        color = BrandRed,
                        maxLines = 2,
                        overflow = TextOverflow.Ellipsis,
                    )
                }
                Spacer(modifier = Modifier.width(8.dp))
                Box(
                    modifier = Modifier
                        .size(38.dp)
                        .clip(RoundedCornerShape(12.dp))
                        .background(SurfaceContainerHighest)
                        .alpha(if (product.canAddToCartFromList()) 1f else 0.45f)
                        .clickable(
                            enabled = product.canAddToCartFromList(),
                            interactionSource = remember { MutableInteractionSource() },
                            indication = ripple(),
                            onClick = onClick,
                        ),
                    contentAlignment = Alignment.Center,
                ) {
                    Icon(
                        imageVector = Icons.Outlined.ShoppingCart,
                        contentDescription = null,
                        tint = OnSurfaceVariant,
                        modifier = Modifier.size(20.dp),
                    )
                }
            }
        }
    }
}

@Composable
private fun ProductMetaRow(product: ProductItem) {
    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.spacedBy(8.dp),
        verticalAlignment = Alignment.CenterVertically,
    ) {
        Row(
            modifier = Modifier.weight(1f),
            horizontalArrangement = Arrangement.spacedBy(4.dp),
            verticalAlignment = Alignment.CenterVertically,
        ) {
            Icon(
                imageVector = if (product.market.equals("International", ignoreCase = true)) {
                    Icons.Outlined.Public
                } else {
                    Icons.Outlined.LocationOn
                },
                contentDescription = null,
                tint = OnSurfaceVariant,
                modifier = Modifier.size(14.dp),
            )
            Text(
                text = product.market ?: stringResource(R.string.products_marketplace),
                style = MaterialTheme.typography.bodySmall,
                color = OnSurfaceVariant,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis,
            )
        }
        Text(
            text = if (product.totalStock > 0) {
                stringResource(R.string.products_stock, product.totalStock)
            } else {
                stringResource(R.string.products_out_of_stock)
            },
            style = MaterialTheme.typography.labelSmall,
            color = if (product.totalStock > 0) AccentBlue else BrandRed,
            fontWeight = FontWeight.SemiBold,
        )
    }
}

@Composable
private fun FavoriteButton(
    isFavorite: Boolean,
    onClick: () -> Unit,
    modifier: Modifier = Modifier,
) {
    Box(
        modifier = modifier
            .size(36.dp)
            .clip(CircleShape)
            .background(Color.White.copy(alpha = 0.88f))
            .clickable(
                interactionSource = remember { MutableInteractionSource() },
                indication = ripple(bounded = true),
                onClick = onClick,
            ),
        contentAlignment = Alignment.Center,
    ) {
        Icon(
            imageVector = if (isFavorite) Icons.Filled.Favorite else Icons.Outlined.FavoriteBorder,
            contentDescription = null,
            tint = if (isFavorite) BrandRed else OnSurfaceVariant,
            modifier = Modifier.size(18.dp),
        )
    }
}

@Composable
private fun MarketBadge(
    market: String?,
    modifier: Modifier = Modifier,
) {
    val text = market ?: stringResource(R.string.products_general)
    val (container, content) = if (market.equals("International", ignoreCase = true)) {
        AccentPurpleContainer to AccentPurple
    } else {
        AccentBlueContainer to AccentBlue
    }

    Box(
        modifier = modifier
            .clip(RoundedCornerShape(999.dp))
            .background(container.copy(alpha = 0.95f))
            .padding(horizontal = 10.dp, vertical = 6.dp),
    ) {
        Text(
            text = text,
            style = MaterialTheme.typography.labelSmall,
            color = content,
            fontWeight = FontWeight.Bold,
        )
    }
}

@Composable
private fun IconActionButton(
    icon: androidx.compose.ui.graphics.vector.ImageVector,
    contentDescription: String,
) {
    Box(
        modifier = Modifier
            .size(52.dp)
            .clip(RoundedCornerShape(14.dp))
            .background(SurfaceContainerLowest)
            .clickable(
                interactionSource = remember { MutableInteractionSource() },
                indication = ripple(),
                onClick = {},
            ),
        contentAlignment = Alignment.Center,
    ) {
        Icon(
            imageVector = icon,
            contentDescription = contentDescription,
            tint = OnSurfaceVariant,
            modifier = Modifier.size(22.dp),
        )
    }
}

@Composable
private fun CenterState(
    title: String,
    body: String,
    loading: Boolean = false,
    actionLabel: String? = null,
    onAction: (() -> Unit)? = null,
) {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 32.dp)
            .clip(RoundedCornerShape(24.dp))
            .background(SurfaceContainerLowest)
            .padding(24.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.spacedBy(14.dp),
    ) {
        if (loading) {
            CircularProgressIndicator(
                color = BrandRed,
                modifier = Modifier.size(32.dp),
                strokeWidth = 2.5.dp,
            )
        } else {
            Text(
                text = stringResource(R.string.products_catalog_label),
                fontFamily = ManropeFontFamily,
                fontWeight = FontWeight.ExtraBold,
                fontSize = 20.sp,
                color = BrandRed,
                fontStyle = FontStyle.Italic,
            )
        }
        Text(
            text = title,
            fontFamily = ManropeFontFamily,
            fontWeight = FontWeight.ExtraBold,
            fontSize = 24.sp,
            color = OnSurface,
        )
        Text(
            text = body,
            style = MaterialTheme.typography.bodyMedium,
            color = OnSurfaceVariant,
            lineHeight = 22.sp,
        )
        if (actionLabel != null && onAction != null) {
            InaPrimaryButton(
                text = actionLabel,
                onClick = onAction,
                modifier = Modifier.padding(top = 6.dp),
            )
        }
    }
}

@Composable
private fun FavoritePickerDialog(
    groups: List<id.iiyh.inatrading.feature.favorite.domain.FavoriteGroupSummary>,
    createMode: Boolean,
    isLoading: Boolean,
    onDismiss: () -> Unit,
    onCreateMode: () -> Unit,
    onCancelCreate: () -> Unit,
    onCreateGroup: (String) -> Unit,
    onSelectGroup: (String) -> Unit,
) {
    var groupName by remember { mutableStateOf("") }

    AlertDialog(
        onDismissRequest = {
            if (!isLoading) onDismiss()
        },
        title = {
            Text(
                text = if (createMode) {
                    stringResource(R.string.favorite_create_collection)
                } else {
                    stringResource(R.string.products_select_favorite_group)
                },
                fontFamily = ManropeFontFamily,
                fontWeight = FontWeight.Bold,
            )
        },
        text = {
            Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
                if (isLoading) {
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.Center,
                    ) {
                        CircularProgressIndicator(
                            color = BrandRed,
                            modifier = Modifier.size(28.dp),
                            strokeWidth = 2.5.dp,
                        )
                    }
                } else if (createMode) {
                    InaTextField(
                        value = groupName,
                        onValueChange = { groupName = it },
                        placeholder = stringResource(R.string.favorite_name_placeholder),
                    )
                } else {
                    Text(
                        text = stringResource(R.string.products_choose_favorite_group),
                        style = MaterialTheme.typography.bodyMedium,
                        color = OnSurfaceVariant,
                    )
                    groups.forEach { group ->
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .clip(RoundedCornerShape(14.dp))
                                .background(SurfaceContainerLow)
                                .clickable(
                                    interactionSource = remember { MutableInteractionSource() },
                                    indication = ripple(),
                                    onClick = { onSelectGroup(group.id) },
                                )
                                .padding(horizontal = 14.dp, vertical = 12.dp),
                            horizontalArrangement = Arrangement.SpaceBetween,
                            verticalAlignment = Alignment.CenterVertically,
                        ) {
                            Column(
                                modifier = Modifier.weight(1f),
                                verticalArrangement = Arrangement.spacedBy(2.dp),
                            ) {
                                Text(
                                    text = group.name,
                                    fontWeight = FontWeight.SemiBold,
                                    color = OnSurface,
                                )
                                Text(
                                    text = stringResource(R.string.products_favorite_group_count, group.itemCount),
                                    style = MaterialTheme.typography.bodySmall,
                                    color = OnSurfaceVariant,
                                )
                            }
                            Icon(
                                imageVector = Icons.AutoMirrored.Outlined.ArrowForward,
                                contentDescription = null,
                                tint = BrandRed,
                                modifier = Modifier.size(18.dp),
                            )
                        }
                    }
                }
            }
        },
        confirmButton = {
            when {
                createMode -> {
                    TextButton(
                        enabled = groupName.trim().isNotEmpty() && !isLoading,
                        onClick = {
                            onCreateGroup(groupName.trim())
                            groupName = ""
                        },
                    ) {
                        Text(stringResource(R.string.favorite_create_action))
                    }
                }
                else -> {
                    TextButton(
                        enabled = !isLoading,
                        onClick = onCreateMode,
                    ) {
                        Text(stringResource(R.string.favorite_create_collection))
                    }
                }
            }
        },
        dismissButton = {
            TextButton(
                enabled = !isLoading,
                onClick = {
                    if (createMode && groups.isNotEmpty()) {
                        onCancelCreate()
                    } else {
                        onDismiss()
                    }
                },
            ) {
                Text(stringResource(R.string.dialog_cancel))
            }
        },
    )
}

@Composable
private fun ProductItem.displayPrice(): String {
    val min = minPrice
    val max = maxPrice
    if (min <= 0.0 && max <= 0.0) return stringResource(R.string.products_contact_price)
    return if (min > 0.0 && max > 0.0 && min != max) {
        "${min.toCurrency()} - ${max.toCurrency()}"
    } else {
        maxOf(min, max).toCurrency()
    }
}

private fun ProductItem.canAddToCartFromList(): Boolean {
    return maxOf(minPrice, maxPrice) > 0.0
}

private fun Double.toCurrency(): String {
    val formatter = NumberFormat.getCurrencyInstance(Locale("in", "ID")).apply {
        maximumFractionDigits = 0
    }
    return formatter.format(this).replace("Rp", "Rp ")
}
