package id.iiyh.inatrading.feature.cart.presentation

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
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.automirrored.outlined.ArrowForward
import androidx.compose.material.icons.automirrored.outlined.Login
import androidx.compose.material.icons.outlined.Add
import androidx.compose.material.icons.outlined.Delete
import androidx.compose.material.icons.outlined.Remove
import androidx.compose.material.icons.outlined.Storefront
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
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.alpha
import androidx.compose.ui.draw.clip
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 coil.compose.AsyncImage
import id.iiyh.inatrading.R
import id.iiyh.inatrading.core.ui.components.InaLogo
import id.iiyh.inatrading.core.ui.components.LogoSize
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.ManropeFontFamily
import id.iiyh.inatrading.core.ui.theme.OnAccentBlueContainer
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.cart.data.model.CartGroup
import id.iiyh.inatrading.feature.cart.data.model.CartItem
import java.text.NumberFormat
import java.util.Locale

@Composable
fun CartScreen(
    onBack: () -> Unit,
    onLoginRequired: () -> Unit,
    viewModel: CartViewModel,
) {
    val uiState by viewModel.uiState.collectAsState()
    val snackbarHostState = remember { SnackbarHostState() }

    LaunchedEffect(uiState.isLoggedIn) {
        if (uiState.isLoggedIn) {
            viewModel.loadCart()
        } else {
            viewModel.clearError()
        }
    }

    LaunchedEffect(uiState.errorMessage, uiState.cartGroups.isNotEmpty()) {
        val message = uiState.errorMessage ?: return@LaunchedEffect
        if (uiState.cartGroups.isNotEmpty()) {
            snackbarHostState.showSnackbar(message)
            viewModel.clearError()
        }
    }

    Scaffold(
        topBar = { CartTopBar(onBack = onBack) },
        snackbarHost = { SnackbarHost(snackbarHostState) },
        bottomBar = {
            if (uiState.isLoggedIn && uiState.cartGroups.isNotEmpty()) {
                CartFooter(
                    totalPrice = uiState.totalPrice,
                )
            }
        },
        containerColor = Background,
    ) { innerPadding ->
        Box(
            modifier = Modifier
                .fillMaxSize()
                .padding(innerPadding),
        ) {
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(220.dp)
                    .background(SurfaceContainerHighest.copy(alpha = 0.6f)),
            )

            when {
                !uiState.isLoggedIn -> {
                    CartGuestState(
                        onLoginRequired = onLoginRequired,
                        modifier = Modifier.fillMaxSize(),
                    )
                }

                uiState.isLoadingCart -> {
                    Box(
                        modifier = Modifier.fillMaxSize(),
                        contentAlignment = Alignment.Center,
                    ) {
                        CircularProgressIndicator(color = BrandRed)
                    }
                }

                uiState.errorMessage != null && uiState.cartGroups.isEmpty() -> {
                    CartMessageState(
                        title = stringResource(R.string.cart_error_title),
                        body = uiState.errorMessage ?: "",
                        actionLabel = stringResource(R.string.cart_retry),
                        onAction = viewModel::loadCart,
                        modifier = Modifier.fillMaxSize(),
                    )
                }

                uiState.cartGroups.isEmpty() -> {
                    CartMessageState(
                        title = stringResource(R.string.cart_empty_title),
                        body = stringResource(R.string.cart_empty_body),
                        actionLabel = stringResource(R.string.cart_browse_products),
                        onAction = onBack,
                        modifier = Modifier.fillMaxSize(),
                    )
                }

                else -> {
                    CartContent(
                        updatingItemIds = uiState.updatingItemIds,
                        groups = uiState.cartGroups,
                        onDecreaseQuantity = { item ->
                            viewModel.changeQuantity(
                                cartItemId = item.id.orEmpty(),
                                currentQuantity = item.quantity ?: 0,
                                quantityDelta = -1,
                            )
                        },
                        onIncreaseQuantity = { item ->
                            viewModel.changeQuantity(
                                cartItemId = item.id.orEmpty(),
                                currentQuantity = item.quantity ?: 0,
                                quantityDelta = 1,
                            )
                        },
                        modifier = Modifier.fillMaxSize(),
                    )
                }
            }
        }
    }
}

@Composable
private fun CartTopBar(
    onBack: () -> Unit,
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .background(Color.White.copy(alpha = 0.86f))
            .padding(horizontal = 20.dp, vertical = 14.dp),
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.SpaceBetween,
    ) {
        Row(
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.spacedBy(12.dp),
        ) {
            IconButton(onClick = onBack) {
                Icon(
                    imageVector = Icons.AutoMirrored.Outlined.ArrowBack,
                    contentDescription = stringResource(R.string.favorite_back),
                    tint = BrandRed,
                )
            }
            InaLogo(size = LogoSize.Small)
        }

        Spacer(modifier = Modifier.size(40.dp))
    }
}

@Composable
private fun CartContent(
    updatingItemIds: Set<String>,
    groups: List<CartGroup>,
    onDecreaseQuantity: (CartItem) -> Unit,
    onIncreaseQuantity: (CartItem) -> Unit,
    modifier: Modifier = Modifier,
) {
    LazyColumn(
        modifier = modifier,
        contentPadding = PaddingValues(
            start = 24.dp,
            end = 24.dp,
            top = 28.dp,
            bottom = 180.dp,
        ),
        verticalArrangement = Arrangement.spacedBy(20.dp),
    ) {
        item {
            Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
                Text(
                    text = stringResource(R.string.cart_eyebrow),
                    color = AccentPurple,
                    style = MaterialTheme.typography.labelMedium,
                    fontWeight = FontWeight.ExtraBold,
                    letterSpacing = 2.sp,
                )
                Text(
                    text = stringResource(R.string.cart_title),
                    fontFamily = ManropeFontFamily,
                    fontWeight = FontWeight.ExtraBold,
                    fontSize = 34.sp,
                    lineHeight = 38.sp,
                    color = OnSurface,
                )
            }
        }

        items(groups, key = { it.id ?: it.seller?.id.orEmpty() }) { group ->
            SellerCartSection(
                group = group,
                updatingItemIds = updatingItemIds,
                onDecreaseQuantity = onDecreaseQuantity,
                onIncreaseQuantity = onIncreaseQuantity,
            )
        }

        item {
            Surface(
                color = AccentBlue.copy(alpha = 0.06f),
                shape = RoundedCornerShape(20.dp),
                tonalElevation = 0.dp,
            ) {
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(18.dp),
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.spacedBy(14.dp),
                ) {
                    Box(
                        modifier = Modifier
                            .size(40.dp)
                            .clip(CircleShape)
                            .background(AccentBlueContainer),
                        contentAlignment = Alignment.Center,
                    ) {
                        Icon(
                            imageVector = Icons.Outlined.Storefront,
                            contentDescription = null,
                            tint = OnAccentBlueContainer,
                        )
                    }
                    Column(modifier = Modifier.weight(1f)) {
                        Text(
                            text = stringResource(R.string.cart_checkout_note_title),
                            fontWeight = FontWeight.Bold,
                            color = OnSurface,
                        )
                        Text(
                            text = stringResource(R.string.cart_checkout_note_body),
                            color = OnSurfaceVariant,
                            style = MaterialTheme.typography.bodySmall,
                        )
                    }
                }
            }
        }
    }
}

@Composable
private fun SellerCartSection(
    group: CartGroup,
    updatingItemIds: Set<String>,
    onDecreaseQuantity: (CartItem) -> Unit,
    onIncreaseQuantity: (CartItem) -> Unit,
) {
    Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
        Row(
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.spacedBy(12.dp),
        ) {
            Box(
                modifier = Modifier
                    .size(32.dp)
                    .clip(CircleShape)
                    .background(AccentBlueContainer),
                contentAlignment = Alignment.Center,
            ) {
                Icon(
                    imageVector = Icons.Outlined.Storefront,
                    contentDescription = null,
                    tint = AccentBlue,
                    modifier = Modifier.size(18.dp),
                )
            }
            Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
                Text(
                    text = group.seller?.name.orEmpty().ifBlank {
                        stringResource(R.string.cart_seller_fallback)
                    },
                    fontFamily = ManropeFontFamily,
                    fontWeight = FontWeight.Bold,
                    fontSize = 16.sp,
                    color = OnSurface,
                )
                Text(
                    text = stringResource(R.string.cart_seller_subtitle),
                    color = OnSurfaceVariant,
                    style = MaterialTheme.typography.bodySmall,
                )
            }
        }

        Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
            group.cartItems.forEach { item ->
                CartItemCard(
                    item = item,
                    isUpdating = item.id != null && item.id in updatingItemIds,
                    onDecreaseQuantity = { onDecreaseQuantity(item) },
                    onIncreaseQuantity = { onIncreaseQuantity(item) },
                )
            }
        }
    }
}

@Composable
private fun CartItemCard(
    item: CartItem,
    isUpdating: Boolean,
    onDecreaseQuantity: () -> Unit,
    onIncreaseQuantity: () -> Unit,
) {
    Surface(
        color = SurfaceContainerLowest,
        shape = RoundedCornerShape(24.dp),
        shadowElevation = 2.dp,
    ) {
        BoxWithConstraints(
            modifier = Modifier
                .fillMaxWidth()
                .padding(20.dp),
        ) {
            val compactLayout = maxWidth < 320.dp
            val imageSize = if (compactLayout) 82.dp else 110.dp
            val titleFontSize = if (compactLayout) 16.sp else 18.sp
            val priceFontSize = if (compactLayout) 18.sp else 22.sp

            Row(
                horizontalArrangement = Arrangement.spacedBy(16.dp),
            ) {
                AsyncImage(
                    model = item.productModel?.image,
                    contentDescription = item.productModel?.name,
                    contentScale = ContentScale.Crop,
                    modifier = Modifier
                        .size(imageSize)
                        .clip(RoundedCornerShape(16.dp))
                        .background(SurfaceContainerLow),
                )
                Column(
                    modifier = Modifier.weight(1f),
                    verticalArrangement = Arrangement.spacedBy(if (compactLayout) 10.dp else 14.dp),
                ) {
                    Row(
                        horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.Top,
                        modifier = Modifier.fillMaxWidth(),
                    ) {
                        Text(
                            text = item.productModel?.name.orEmpty().ifBlank {
                                stringResource(R.string.cart_item_name_fallback)
                            },
                            fontFamily = ManropeFontFamily,
                            fontWeight = FontWeight.Bold,
                            fontSize = titleFontSize,
                            lineHeight = if (compactLayout) 20.sp else 22.sp,
                            color = OnSurface,
                            maxLines = 2,
                            overflow = TextOverflow.Ellipsis,
                            modifier = Modifier.weight(1f),
                        )
                        IconButton(
                            onClick = {},
                            enabled = false,
                            modifier = Modifier
                                .alpha(0.45f)
                                .size(if (compactLayout) 32.dp else 40.dp),
                        ) {
                            Icon(
                                imageVector = Icons.Outlined.Delete,
                                contentDescription = stringResource(R.string.cart_delete),
                                tint = OnSurfaceVariant,
                            )
                        }
                    }

                    Text(
                        text = item.productModel?.price.toCurrency(),
                        fontFamily = ManropeFontFamily,
                        fontWeight = FontWeight.ExtraBold,
                        fontSize = priceFontSize,
                        color = BrandRed,
                    )

                    item.productMeasurement?.name?.takeIf { it.isNotBlank() }?.let { measurement ->
                        Text(
                            text = measurement,
                            color = AccentPurple,
                            style = MaterialTheme.typography.labelMedium,
                            fontWeight = FontWeight.SemiBold,
                            modifier = Modifier
                                .clip(RoundedCornerShape(999.dp))
                                .background(AccentPurpleContainer)
                                .padding(horizontal = 10.dp, vertical = 5.dp),
                        )
                    }

                    if (compactLayout) {
                        Column(
                            modifier = Modifier.fillMaxWidth(),
                            verticalArrangement = Arrangement.spacedBy(8.dp),
                            horizontalAlignment = Alignment.End,
                        ) {
                            StockChip()
                            QuantityControl(
                                quantity = item.quantity ?: 0,
                                isUpdating = isUpdating,
                                canDecrease = (item.quantity ?: 0) > 1,
                                onDecrease = onDecreaseQuantity,
                                onIncrease = onIncreaseQuantity,
                            )
                        }
                    } else {
                        Row(
                            modifier = Modifier.fillMaxWidth(),
                            horizontalArrangement = Arrangement.SpaceBetween,
                            verticalAlignment = Alignment.CenterVertically,
                        ) {
                            StockChip()
                            QuantityControl(
                                quantity = item.quantity ?: 0,
                                isUpdating = isUpdating,
                                canDecrease = (item.quantity ?: 0) > 1,
                                onDecrease = onDecreaseQuantity,
                                onIncrease = onIncreaseQuantity,
                            )
                        }
                    }
                }
            }
        }
    }
}

@Composable
private fun StockChip() {
    Text(
        text = stringResource(R.string.cart_stock_available),
        color = AccentPurple,
        style = MaterialTheme.typography.labelMedium,
        fontWeight = FontWeight.Bold,
        modifier = Modifier
            .clip(RoundedCornerShape(999.dp))
            .background(AccentPurpleContainer.copy(alpha = 0.75f))
            .padding(horizontal = 12.dp, vertical = 8.dp),
    )
}

@Composable
private fun QuantityControl(
    quantity: Int,
    isUpdating: Boolean,
    canDecrease: Boolean,
    onDecrease: () -> Unit,
    onIncrease: () -> Unit,
) {
    Row(
        modifier = Modifier
            .clip(RoundedCornerShape(14.dp))
            .background(SurfaceContainerLow)
            .padding(4.dp),
        verticalAlignment = Alignment.CenterVertically,
    ) {
        QuantityButton(
            icon = Icons.Outlined.Remove,
            contentDescription = stringResource(R.string.cart_decrease_quantity),
            enabled = canDecrease && !isUpdating,
            onClick = onDecrease,
        )
        if (isUpdating) {
            CircularProgressIndicator(
                color = BrandRed,
                strokeWidth = 2.dp,
                modifier = Modifier
                    .padding(horizontal = 10.dp)
                    .size(18.dp),
            )
        } else {
            Text(
                text = quantity.toString(),
                fontFamily = ManropeFontFamily,
                fontWeight = FontWeight.Bold,
                color = OnSurface,
                modifier = Modifier.padding(horizontal = 10.dp),
            )
        }
        QuantityButton(
            icon = Icons.Outlined.Add,
            contentDescription = stringResource(R.string.cart_increase_quantity),
            enabled = !isUpdating,
            onClick = onIncrease,
        )
    }
}

@Composable
private fun QuantityButton(
    icon: androidx.compose.ui.graphics.vector.ImageVector,
    contentDescription: String,
    enabled: Boolean,
    onClick: () -> Unit,
) {
    IconButton(
        onClick = onClick,
        enabled = enabled,
        modifier = Modifier
            .size(28.dp)
            .alpha(if (enabled) 1f else 0.45f),
    ) {
        Icon(
            imageVector = icon,
            contentDescription = contentDescription,
            tint = OnSurface,
            modifier = Modifier.size(16.dp),
        )
    }
}

@Composable
private fun CartFooter(
    totalPrice: Double,
) {
    Surface(
        color = SurfaceContainerLowest.copy(alpha = 0.9f),
        shadowElevation = 10.dp,
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(
                    start = 24.dp,
                    end = 24.dp,
                    top = 18.dp,
                    bottom = 18.dp,
                ),
            verticalArrangement = Arrangement.spacedBy(16.dp),
        ) {
            HorizontalDivider(color = OutlineVariant.copy(alpha = 0.45f))
            Row(
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.SpaceBetween,
                modifier = Modifier.fillMaxWidth(),
            ) {
                Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
                    Text(
                        text = stringResource(R.string.cart_total_label),
                        color = OnSurfaceVariant,
                        style = MaterialTheme.typography.bodySmall,
                    )
                    Text(
                        text = totalPrice.toCurrency(),
                        fontFamily = ManropeFontFamily,
                        fontWeight = FontWeight.ExtraBold,
                        fontSize = 28.sp,
                        color = OnSurface,
                    )
                }
                Button(
                    onClick = {},
                    colors = ButtonDefaults.buttonColors(
                        containerColor = BrandRed,
                        contentColor = Color.White,
                    ),
                    shape = RoundedCornerShape(18.dp),
                ) {
                    Text(
                        text = stringResource(R.string.cart_checkout),
                        fontFamily = ManropeFontFamily,
                        fontWeight = FontWeight.Bold,
                    )
                    Spacer(modifier = Modifier.size(8.dp))
                    Icon(
                        imageVector = Icons.AutoMirrored.Outlined.ArrowForward,
                        contentDescription = null,
                    )
                }
            }
        }
    }
}

@Composable
private fun CartGuestState(
    onLoginRequired: () -> Unit,
    modifier: Modifier = Modifier,
) {
    Box(
        modifier = modifier.padding(24.dp),
        contentAlignment = Alignment.Center,
    ) {
        Column(
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.spacedBy(16.dp),
        ) {
            Text(
                text = stringResource(R.string.cart_guest_title),
                fontFamily = ManropeFontFamily,
                fontWeight = FontWeight.ExtraBold,
                fontSize = 26.sp,
                color = OnSurface,
            )
            Text(
                text = stringResource(R.string.cart_guest_body),
                color = OnSurfaceVariant,
                style = MaterialTheme.typography.bodyMedium,
            )
            Button(
                onClick = onLoginRequired,
                colors = ButtonDefaults.buttonColors(
                    containerColor = BrandRed,
                    contentColor = Color.White,
                ),
                shape = RoundedCornerShape(16.dp),
            ) {
                Icon(
                    imageVector = Icons.AutoMirrored.Outlined.Login,
                    contentDescription = null,
                )
                Spacer(modifier = Modifier.size(8.dp))
                Text(
                    text = stringResource(R.string.profile_guest_cta),
                    fontWeight = FontWeight.Bold,
                )
            }
        }
    }
}

@Composable
private fun CartMessageState(
    title: String,
    body: String,
    actionLabel: String,
    onAction: () -> Unit,
    modifier: Modifier = Modifier,
) {
    Box(
        modifier = modifier.padding(24.dp),
        contentAlignment = Alignment.Center,
    ) {
        Column(
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.spacedBy(16.dp),
        ) {
            Text(
                text = title,
                fontFamily = ManropeFontFamily,
                fontWeight = FontWeight.ExtraBold,
                fontSize = 28.sp,
                color = OnSurface,
            )
            Text(
                text = body,
                color = OnSurfaceVariant,
                style = MaterialTheme.typography.bodyMedium,
            )
            TextButton(onClick = onAction) {
                Text(
                    text = actionLabel,
                    color = BrandRed,
                    fontWeight = FontWeight.Bold,
                )
            }
        }
    }
}

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