package id.iiyh.inatrading.feature.profile.presentation

import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.background
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.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.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Add
import androidx.compose.material.icons.outlined.LocationOn
import androidx.compose.material.icons.outlined.Person
import androidx.compose.material.icons.outlined.Star
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.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TextFieldDefaults
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.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
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.components.InaTextField
import id.iiyh.inatrading.core.ui.theme.AccentPurple
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.SurfaceContainerLowest

@Composable
fun EditShippingAddressScreen(
    onBack: () -> Unit,
    onFinished: () -> Unit,
    viewModel: EditShippingAddressViewModel = hiltViewModel(),
) {
    val uiState by viewModel.uiState.collectAsState()
    val snackbarHostState = remember { SnackbarHostState() }
    val context = LocalContext.current
    val locationPermissionLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.RequestPermission(),
    ) { granted ->
        if (granted) {
            viewModel.onLocationRequestStarted()
            requestCurrentLocation(
                context = context,
                onSuccess = viewModel::onLocationCaptured,
                onError = viewModel::onLocationError,
            )
        } else {
            viewModel.onLocationError(context.getString(R.string.address_pin_permission_required))
        }
    }

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

    LaunchedEffect(uiState.saveSuccess) {
        if (uiState.saveSuccess) {
            viewModel.consumeSaveSuccess()
            onFinished()
        }
    }

    LaunchedEffect(uiState.deleteSuccess) {
        if (uiState.deleteSuccess) {
            viewModel.consumeDeleteSuccess()
            onFinished()
        }
    }

    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 -> {
                EditAddressState(
                    title = stringResource(R.string.shipping_addresses_error_title),
                    body = uiState.errorMessage.orEmpty(),
                    actionLabel = stringResource(R.string.explore_retry),
                    onAction = viewModel::loadAddress,
                    modifier = Modifier.padding(innerPadding),
                )
            }

            else -> {
                LazyColumn(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(innerPadding)
                        .background(Background),
                    contentPadding = PaddingValues(start = 20.dp, end = 20.dp, top = 16.dp, bottom = 120.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.edit_shipping_address_eyebrow),
                                style = MaterialTheme.typography.labelSmall,
                                letterSpacing = 1.6.sp,
                                color = AccentPurple,
                            )
                            Text(
                                text = stringResource(R.string.edit_shipping_address_title),
                                fontFamily = ManropeFontFamily,
                                fontWeight = FontWeight.ExtraBold,
                                fontSize = 34.sp,
                                color = OnSurface,
                            )
                            Text(
                                text = stringResource(R.string.edit_shipping_address_body),
                                style = MaterialTheme.typography.bodyMedium,
                                color = OnSurfaceVariant,
                            )
                        }
                    }

                    item {
                        Column(
                            modifier = Modifier
                                .fillMaxWidth()
                                .clip(RoundedCornerShape(24.dp))
                                .background(SurfaceContainerLowest)
                                .padding(20.dp),
                            verticalArrangement = Arrangement.spacedBy(16.dp),
                        ) {
                            SectionHeaderRow(Icons.Outlined.Person, stringResource(R.string.edit_shipping_address_recipient_section))
                            InaTextField(
                                value = uiState.recipient,
                                onValueChange = viewModel::onRecipientChange,
                                label = stringResource(R.string.add_shipping_address_recipient_label),
                                placeholder = stringResource(R.string.add_shipping_address_recipient_placeholder),
                            )
                            InaTextField(
                                value = uiState.phone,
                                onValueChange = viewModel::onPhoneChange,
                                label = stringResource(R.string.add_shipping_address_phone_label),
                                placeholder = stringResource(R.string.add_shipping_address_phone_placeholder),
                            )
                        }
                    }

                    item {
                        Column(
                            modifier = Modifier
                                .fillMaxWidth()
                                .clip(RoundedCornerShape(24.dp))
                                .background(SurfaceContainerLowest)
                                .padding(20.dp),
                            verticalArrangement = Arrangement.spacedBy(16.dp),
                        ) {
                            SectionHeaderRow(Icons.Outlined.LocationOn, stringResource(R.string.edit_shipping_address_location_section))
                            AddressDropdownField(
                                value = if (uiState.countryKey == ADDRESS_COUNTRY_INDONESIA) {
                                    stringResource(R.string.add_shipping_address_country_indonesia)
                                } else {
                                    stringResource(R.string.add_shipping_address_country_other)
                                },
                                label = stringResource(R.string.add_shipping_address_country_label),
                                placeholder = stringResource(R.string.add_shipping_address_country_placeholder),
                                options = listOf(
                                    DropdownOption(ADDRESS_COUNTRY_INDONESIA, stringResource(R.string.add_shipping_address_country_indonesia)),
                                    DropdownOption(ADDRESS_COUNTRY_OTHER, stringResource(R.string.add_shipping_address_country_other)),
                                ),
                                onOptionSelected = { viewModel.onCountrySelected(it.id) },
                            )
                            if (uiState.countryKey == ADDRESS_COUNTRY_OTHER) {
                                InaTextField(
                                    value = uiState.customCountry,
                                    onValueChange = viewModel::onCustomCountryChange,
                                    label = stringResource(R.string.add_shipping_address_country_custom_label),
                                    placeholder = stringResource(R.string.add_shipping_address_country_custom_placeholder),
                                )
                                InaTextField(
                                    value = uiState.province,
                                    onValueChange = viewModel::onProvinceChange,
                                    label = stringResource(R.string.add_shipping_address_province_label),
                                )
                                InaTextField(
                                    value = uiState.city,
                                    onValueChange = viewModel::onCityChange,
                                    label = stringResource(R.string.add_shipping_address_city_label),
                                )
                            } else {
                                AddressDropdownField(
                                    value = uiState.province,
                                    label = stringResource(R.string.add_shipping_address_province_label),
                                    placeholder = if (uiState.isLoadingProvinces) {
                                        stringResource(R.string.address_loading_provinces)
                                    } else {
                                        stringResource(R.string.add_shipping_address_province_placeholder)
                                    },
                                    options = uiState.provinces.mapNotNull {
                                        val id = it.id ?: return@mapNotNull null
                                        val label = it.name ?: return@mapNotNull null
                                        DropdownOption(id, label)
                                    },
                                    enabled = !uiState.isLoadingProvinces && uiState.provinces.isNotEmpty(),
                                    onOptionSelected = { viewModel.onProvinceSelected(it.id) },
                                )
                                AddressDropdownField(
                                    value = uiState.city,
                                    label = stringResource(R.string.add_shipping_address_city_label),
                                    placeholder = if (uiState.selectedProvinceId == null) {
                                        stringResource(R.string.address_select_province_first)
                                    } else if (uiState.isLoadingCities) {
                                        stringResource(R.string.address_loading_cities)
                                    } else {
                                        stringResource(R.string.add_shipping_address_city_placeholder)
                                    },
                                    options = uiState.cities.mapNotNull {
                                        val id = it.id ?: return@mapNotNull null
                                        val label = it.name ?: return@mapNotNull null
                                        DropdownOption(id, label)
                                    },
                                    enabled = uiState.selectedProvinceId != null && !uiState.isLoadingCities,
                                    onOptionSelected = { viewModel.onCitySelected(it.id) },
                                )
                            }
                            InaTextField(
                                value = uiState.postalCode,
                                onValueChange = viewModel::onPostalCodeChange,
                                label = stringResource(R.string.add_shipping_address_postal_label),
                            )
                            androidx.compose.material3.OutlinedTextField(
                                value = uiState.address,
                                onValueChange = viewModel::onAddressChange,
                                modifier = Modifier.fillMaxWidth(),
                                minLines = 3,
                                shape = RoundedCornerShape(16.dp),
                                label = { Text(stringResource(R.string.add_shipping_address_full_label)) },
                                textStyle = MaterialTheme.typography.bodyLarge.copy(color = OnSurface),
                                colors = TextFieldDefaults.colors(
                                    focusedTextColor = OnSurface,
                                    unfocusedTextColor = OnSurface,
                                    focusedContainerColor = Color.White,
                                    unfocusedContainerColor = Color.White,
                                    disabledContainerColor = Color.White,
                                    focusedIndicatorColor = BrandRed.copy(alpha = 0.45f),
                                    unfocusedIndicatorColor = OnSurfaceVariant.copy(alpha = 0.28f),
                                    focusedLabelColor = BrandRed,
                                    unfocusedLabelColor = OnSurfaceVariant,
                                ),
                            )
                            Text(
                                text = stringResource(
                                    R.string.edit_shipping_address_coordinates,
                                    uiState.latitude ?: 0.0,
                                    uiState.longitude ?: 0.0,
                                ),
                                style = MaterialTheme.typography.bodySmall,
                                color = OnSurfaceVariant,
                            )
                            AddressPinTeaser(
                                latitude = uiState.latitude,
                                longitude = uiState.longitude,
                                isLoading = uiState.isResolvingLocation,
                                onClick = {
                                    if (hasLocationPermission(context)) {
                                        viewModel.onLocationRequestStarted()
                                        requestCurrentLocation(
                                            context = context,
                                            onSuccess = viewModel::onLocationCaptured,
                                            onError = viewModel::onLocationError,
                                        )
                                    } else {
                                        locationPermissionLauncher.launch(android.Manifest.permission.ACCESS_FINE_LOCATION)
                                    }
                                },
                            )
                            CurrentLocationPermissionMessage()
                            Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
                                EditAddressLabelChip(
                                    text = stringResource(R.string.add_shipping_address_label_home),
                                    selected = uiState.label.equals("rumah", true) || uiState.label.equals("home", true),
                                    onClick = { viewModel.onLabelSelected("rumah") },
                                )
                                EditAddressLabelChip(
                                    text = stringResource(R.string.add_shipping_address_label_office),
                                    selected = uiState.label.equals("kantor", true) || uiState.label.equals("office", true),
                                    onClick = { viewModel.onLabelSelected("kantor") },
                                )
                                EditAddressLabelChip(
                                    text = stringResource(R.string.add_shipping_address_label_warehouse),
                                    selected = uiState.label.equals("gudang", true) || uiState.label.equals("warehouse", true),
                                    onClick = { viewModel.onLabelSelected("gudang") },
                                )
                                EditAddressLabelChip(
                                    text = stringResource(R.string.add_shipping_address_label_other),
                                    selected = uiState.label == EditShippingAddressViewModel.CUSTOM_LABEL_KEY,
                                    icon = Icons.Outlined.Add,
                                    onClick = viewModel::onCustomLabelSelected,
                                )
                            }
                            if (uiState.label == EditShippingAddressViewModel.CUSTOM_LABEL_KEY) {
                                InaTextField(
                                    value = uiState.customLabel,
                                    onValueChange = viewModel::onCustomLabelChange,
                                    label = stringResource(R.string.add_shipping_address_custom_label_title),
                                    placeholder = stringResource(R.string.add_shipping_address_custom_label_placeholder),
                                )
                            }
                        }
                    }

                    item {
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .clip(RoundedCornerShape(20.dp))
                                .background(SurfaceContainerLowest)
                                .padding(20.dp),
                            horizontalArrangement = Arrangement.SpaceBetween,
                            verticalAlignment = Alignment.CenterVertically,
                        ) {
                            Row(horizontalArrangement = Arrangement.spacedBy(12.dp), verticalAlignment = Alignment.CenterVertically) {
                                Box(
                                    modifier = Modifier
                                        .size(44.dp)
                                        .clip(RoundedCornerShape(14.dp))
                                        .background(BrandRedContainer.copy(alpha = 0.18f)),
                                    contentAlignment = Alignment.Center,
                                ) {
                                    Icon(Icons.Outlined.Star, contentDescription = null, tint = BrandRed)
                                }
                                Column {
                                    Text(
                                        text = stringResource(R.string.add_shipping_address_primary_label),
                                        fontWeight = FontWeight.Bold,
                                        color = OnSurface,
                                    )
                                    Text(
                                        text = stringResource(R.string.add_shipping_address_primary_body),
                                        style = MaterialTheme.typography.bodySmall,
                                        color = OnSurfaceVariant,
                                    )
                                }
                            }
                            Switch(
                                checked = uiState.isPrimary,
                                onCheckedChange = viewModel::onPrimaryChange,
                            )
                        }
                    }

                    item {
                        Row(
                            modifier = Modifier.fillMaxWidth(),
                            horizontalArrangement = Arrangement.Center,
                        ) {
                            TextButton(
                                onClick = viewModel::onDeleteClick,
                                enabled = !uiState.isDeleting && !uiState.isSaving,
                            ) {
                                Text(
                                    text = stringResource(R.string.edit_shipping_address_delete),
                                    color = BrandRed,
                                    fontWeight = FontWeight.Bold,
                                )
                            }
                        }
                    }
                }

                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(bottom = 24.dp),
                    contentAlignment = Alignment.BottomCenter,
                ) {
                    InaPrimaryButton(
                        text = stringResource(R.string.edit_shipping_address_save),
                        onClick = viewModel::onSaveClick,
                        isLoading = uiState.isSaving,
                        enabled = !uiState.isResolvingLocation,
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(horizontal = 20.dp),
                    )
                }
            }
        }
    }
}

@Composable
private fun EditAddressLabelChip(
    text: String,
    selected: Boolean,
    icon: androidx.compose.ui.graphics.vector.ImageVector? = null,
    onClick: () -> Unit,
) {
    Box(
        modifier = Modifier
            .clip(RoundedCornerShape(999.dp))
            .background(if (selected) BrandRed else SurfaceContainerHighest)
            .clickable(
                interactionSource = remember { MutableInteractionSource() },
                indication = ripple(),
                onClick = onClick,
            )
            .padding(horizontal = 16.dp, vertical = 10.dp),
        contentAlignment = Alignment.Center,
    ) {
        Row(
            horizontalArrangement = Arrangement.spacedBy(6.dp),
            verticalAlignment = Alignment.CenterVertically,
        ) {
            if (icon != null) {
                Icon(
                    imageVector = icon,
                    contentDescription = null,
                    tint = if (selected) Color.White else OnSurfaceVariant,
                    modifier = Modifier.size(16.dp),
                )
            }
            Text(
                text = text,
                style = MaterialTheme.typography.labelLarge,
                color = if (selected) Color.White else OnSurfaceVariant,
            )
        }
    }
}

@Composable
private fun SectionHeaderRow(
    icon: androidx.compose.ui.graphics.vector.ImageVector,
    title: String,
) {
    Row(
        horizontalArrangement = Arrangement.spacedBy(8.dp),
        verticalAlignment = Alignment.CenterVertically,
    ) {
        Icon(icon, contentDescription = null, tint = BrandRed)
        Text(
            text = title,
            fontFamily = ManropeFontFamily,
            fontWeight = FontWeight.Bold,
            fontSize = 18.sp,
            color = OnSurface,
        )
    }
}

@Composable
private fun EditAddressState(
    title: String,
    body: String,
    actionLabel: String,
    onAction: () -> Unit,
    modifier: Modifier = Modifier,
) {
    Box(
        modifier = modifier
            .fillMaxSize()
            .background(Background)
            .padding(24.dp),
        contentAlignment = Alignment.Center,
    ) {
        Column(
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.spacedBy(14.dp),
        ) {
            Text(text = title, fontFamily = ManropeFontFamily, fontWeight = FontWeight.ExtraBold, fontSize = 24.sp)
            Text(text = body, color = OnSurfaceVariant)
            InaPrimaryButton(
                text = actionLabel,
                onClick = onAction,
                modifier = Modifier.fillMaxWidth(),
            )
        }
    }
}
