package id.iiyh.inatrading.feature.profile.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.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.itemsIndexed
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.BusinessCenter
import androidx.compose.material.icons.outlined.Edit
import androidx.compose.material.icons.outlined.Explore
import androidx.compose.material.icons.outlined.Home
import androidx.compose.material.icons.outlined.LocationOn
import androidx.compose.material.icons.outlined.Person
import androidx.compose.material.icons.outlined.Phone
import androidx.compose.material.icons.outlined.Refresh
import androidx.compose.material.icons.outlined.Warehouse
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.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import id.iiyh.inatrading.R
import id.iiyh.inatrading.core.ui.components.InaInnerTopAppBar
import id.iiyh.inatrading.core.ui.components.InaPrimaryButton
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.profile.data.model.ShippingAddress

@Composable
fun ShippingAddressesScreen(
    onBack: () -> Unit,
    onAddAddressClick: () -> Unit,
    onEditAddressClick: (ShippingAddress) -> Unit,
    viewModel: ShippingAddressesViewModel = hiltViewModel(),
) {
    val uiState by viewModel.uiState.collectAsState()
    val snackbarHostState = remember { SnackbarHostState() }

    LaunchedEffect(uiState.infoMessage) {
        uiState.infoMessage?.let {
            snackbarHostState.showSnackbar(it)
            viewModel.consumeInfoMessage()
        }
    }

    Scaffold(
        topBar = { InaInnerTopAppBar(onBack = onBack) },
        snackbarHost = { SnackbarHost(snackbarHostState) },
        containerColor = Background,
    ) { innerPadding ->
        when {
            uiState.isLoading -> {
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(innerPadding),
                    contentAlignment = Alignment.Center,
                ) {
                    CircularProgressIndicator(color = BrandRed)
                }
            }

            uiState.errorMessage != null -> {
                AddressState(
                    title = stringResource(R.string.shipping_addresses_error_title),
                    body = uiState.errorMessage.orEmpty(),
                    actionLabel = stringResource(R.string.explore_retry),
                    onAction = viewModel::loadAddresses,
                    modifier = Modifier.padding(innerPadding),
                )
            }

            uiState.addresses.isEmpty() -> {
                AddressState(
                    title = stringResource(R.string.shipping_addresses_empty_title),
                    body = stringResource(R.string.shipping_addresses_empty_body),
                    actionLabel = stringResource(R.string.shipping_addresses_add_cta),
                    onAction = onAddAddressClick,
                    modifier = Modifier.padding(innerPadding),
                )
            }

            else -> {
                ShippingAddressesContent(
                    addresses = uiState.addresses,
                    onAddAddressClick = onAddAddressClick,
                    onEditAddressClick = onEditAddressClick,
                    modifier = Modifier.padding(innerPadding),
                )
            }
        }
    }
}

@Composable
private fun ShippingAddressesContent(
    addresses: List<ShippingAddress>,
    onAddAddressClick: () -> Unit,
    onEditAddressClick: (ShippingAddress) -> Unit,
    modifier: Modifier = Modifier,
) {
    LazyColumn(
        modifier = modifier
            .fillMaxSize()
            .background(Background),
        contentPadding = PaddingValues(start = 24.dp, end = 24.dp, top = 20.dp, bottom = 32.dp),
        verticalArrangement = Arrangement.spacedBy(18.dp),
    ) {
        item {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .clip(RoundedCornerShape(32.dp))
                    .background(SurfaceContainerHighest.copy(alpha = 0.35f))
                    .padding(horizontal = 24.dp, vertical = 28.dp),
                verticalArrangement = Arrangement.spacedBy(10.dp),
            ) {
                Text(
                    text = stringResource(R.string.shipping_addresses_eyebrow),
                    style = MaterialTheme.typography.labelSmall,
                    letterSpacing = 2.sp,
                    color = AccentPurple,
                )
                Text(
                    text = stringResource(R.string.shipping_addresses_title),
                    fontFamily = ManropeFontFamily,
                    fontWeight = FontWeight.ExtraBold,
                    fontSize = 34.sp,
                    lineHeight = 38.sp,
                    color = OnSurface,
                )
            }
        }

        itemsIndexed(addresses, key = { _, item -> item.id.orEmpty() }) { index, address ->
            ShippingAddressCard(
                address = address,
                title = resolveAddressLabel(address, index),
                icon = if (index == 0 || address.isPrimary) Icons.Outlined.Home else Icons.Outlined.BusinessCenter,
                accent = if (address.isPrimary) BrandRed else AccentBlue,
                accentContainer = if (address.isPrimary) BrandRedContainer.copy(alpha = 0.14f) else AccentBlueContainer.copy(alpha = 0.22f),
                onEditClick = { onEditAddressClick(address) },
            )
        }

        item {
            DeliveryZoneCard()
        }

        item {
            InaPrimaryButton(
                text = stringResource(R.string.shipping_addresses_add_cta),
                onClick = onAddAddressClick,
                modifier = Modifier.fillMaxWidth(),
            )
        }
    }
}

@Composable
private fun ShippingAddressCard(
    address: ShippingAddress,
    title: String,
    icon: ImageVector,
    accent: Color,
    accentContainer: Color,
    onEditClick: () -> Unit,
) {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .clip(RoundedCornerShape(24.dp))
            .background(SurfaceContainerLowest)
            .padding(20.dp),
        verticalArrangement = Arrangement.spacedBy(14.dp),
    ) {
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.Top,
        ) {
            Row(
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.spacedBy(12.dp),
            ) {
                Box(
                    modifier = Modifier
                        .size(40.dp)
                        .clip(RoundedCornerShape(12.dp))
                        .background(accentContainer),
                    contentAlignment = Alignment.Center,
                ) {
                    Icon(
                        imageVector = icon,
                        contentDescription = null,
                        tint = accent,
                    )
                }
                Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
                    Text(
                        text = title,
                        fontFamily = ManropeFontFamily,
                        fontWeight = FontWeight.Bold,
                        fontSize = 19.sp,
                        color = OnSurface,
                    )
                    if (address.isPrimary) {
                        Box(
                            modifier = Modifier
                                .clip(CircleShape)
                                .background(AccentPurpleContainer)
                                .padding(horizontal = 10.dp, vertical = 4.dp),
                        ) {
                            Text(
                                text = stringResource(R.string.shipping_addresses_primary),
                                style = MaterialTheme.typography.labelSmall,
                                color = Color.White,
                            )
                        }
                    }
                }
            }

            Box(
                modifier = Modifier
                    .size(32.dp)
                    .clip(CircleShape)
                    .clickable(
                        interactionSource = remember { MutableInteractionSource() },
                        indication = ripple(),
                        onClick = onEditClick,
                    ),
                contentAlignment = Alignment.Center,
            ) {
                Icon(
                    imageVector = Icons.Outlined.Edit,
                    contentDescription = null,
                    tint = OnSurfaceVariant.copy(alpha = 0.75f),
                    modifier = Modifier.size(20.dp),
                )
            }
        }

        AddressMetaRow(
            icon = Icons.Outlined.Person,
            primaryText = address.recipient?.takeIf { it.isNotBlank() }
                ?: stringResource(R.string.shipping_addresses_recipient_fallback),
        )
        AddressMetaRow(
            icon = Icons.Outlined.Phone,
            primaryText = address.mobile?.takeIf { it.isNotBlank() }
                ?: stringResource(R.string.shipping_addresses_phone_fallback),
        )
        AddressMetaRow(
            icon = Icons.Outlined.LocationOn,
            primaryText = buildAddressLine(address),
            isMultiLine = true,
        )
    }
}

@Composable
private fun AddressMetaRow(
    icon: ImageVector,
    primaryText: String,
    isMultiLine: Boolean = false,
) {
    Row(
        horizontalArrangement = Arrangement.spacedBy(10.dp),
        verticalAlignment = if (isMultiLine) Alignment.Top else Alignment.CenterVertically,
    ) {
        Icon(
            imageVector = icon,
            contentDescription = null,
            tint = OnSurfaceVariant,
            modifier = Modifier
                .padding(top = if (isMultiLine) 2.dp else 0.dp)
                .size(18.dp),
        )
        Text(
            text = primaryText,
            style = MaterialTheme.typography.bodyMedium,
            color = OnSurfaceVariant,
            maxLines = if (isMultiLine) Int.MAX_VALUE else 1,
            overflow = if (isMultiLine) TextOverflow.Clip else TextOverflow.Ellipsis,
        )
    }
}

@Composable
private fun DeliveryZoneCard() {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .clip(RoundedCornerShape(24.dp))
            .background(SurfaceContainerLowest)
            .padding(bottom = 20.dp),
    ) {
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .height(132.dp)
                .background(
                    brush = Brush.linearGradient(
                        colors = listOf(
                            SurfaceContainerHighest,
                            SurfaceContainerLow,
                            SurfaceContainerLowest,
                        )
                    )
                ),
        ) {
            Box(
                modifier = Modifier
                    .align(Alignment.Center)
                    .size(56.dp)
                    .clip(CircleShape)
                    .background(Color.White.copy(alpha = 0.88f)),
                contentAlignment = Alignment.Center,
            ) {
                Icon(
                    imageVector = Icons.Outlined.Explore,
                    contentDescription = null,
                    tint = BrandRed,
                    modifier = Modifier.size(28.dp),
                )
            }
            Row(
                modifier = Modifier
                    .align(Alignment.BottomStart)
                    .padding(start = 20.dp, bottom = 14.dp),
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.spacedBy(6.dp),
            ) {
                Icon(
                    imageVector = Icons.Outlined.Warehouse,
                    contentDescription = null,
                    tint = BrandRed,
                    modifier = Modifier.size(16.dp),
                )
                Text(
                    text = stringResource(R.string.shipping_addresses_zone_label),
                    style = MaterialTheme.typography.labelSmall,
                    letterSpacing = 1.4.sp,
                    color = OnSurfaceVariant,
                )
            }
        }

        Text(
            text = stringResource(R.string.shipping_addresses_zone_quote),
            style = MaterialTheme.typography.bodySmall,
            color = OnSurfaceVariant,
            modifier = Modifier.padding(horizontal = 20.dp, vertical = 16.dp),
        )
    }
}

@Composable
private fun AddressState(
    title: String,
    body: String,
    actionLabel: String,
    onAction: () -> Unit,
    modifier: Modifier = Modifier,
) {
    Box(
        modifier = modifier
            .fillMaxSize()
            .background(Background)
            .padding(24.dp),
        contentAlignment = Alignment.Center,
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .clip(RoundedCornerShape(28.dp))
                .background(SurfaceContainerLowest)
                .padding(24.dp),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.spacedBy(14.dp),
        ) {
            Text(
                text = title,
                fontFamily = ManropeFontFamily,
                fontWeight = FontWeight.ExtraBold,
                fontSize = 26.sp,
                color = OnSurface,
            )
            Text(
                text = body,
                style = MaterialTheme.typography.bodyMedium,
                color = OnSurfaceVariant,
            )
            Row(
                modifier = Modifier
                    .clip(RoundedCornerShape(18.dp))
                    .background(BrandRed)
                    .clickable(
                        interactionSource = remember { MutableInteractionSource() },
                        indication = ripple(),
                        onClick = onAction,
                    )
                    .padding(horizontal = 18.dp, vertical = 12.dp),
                horizontalArrangement = Arrangement.spacedBy(8.dp),
                verticalAlignment = Alignment.CenterVertically,
            ) {
                Icon(
                    imageVector = Icons.Outlined.Refresh,
                    contentDescription = null,
                    tint = Color.White,
                    modifier = Modifier.size(18.dp),
                )
                Text(
                    text = actionLabel,
                    color = Color.White,
                    fontWeight = FontWeight.Bold,
                )
            }
        }
    }
}

@Composable
private fun resolveAddressLabel(address: ShippingAddress, index: Int): String {
    val label = address.label?.trim().orEmpty()
    if (label.isNotBlank()) return label.replaceFirstChar { it.uppercase() }
    if (address.isPrimary) return stringResource(R.string.shipping_addresses_home_label)
    if (index == 1) return stringResource(R.string.shipping_addresses_office_label)
    return stringResource(R.string.shipping_addresses_default_label, index + 1)
}

private fun buildAddressLine(address: ShippingAddress): String {
    return listOfNotNull(
        address.address?.takeIf { it.isNotBlank() },
        address.city?.takeIf { it.isNotBlank() },
        address.province?.takeIf { it.isNotBlank() },
        address.country?.takeIf { it.isNotBlank() },
        address.postalCode?.takeIf { it.isNotBlank() },
    ).joinToString(", ")
}
