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

import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
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.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.CircleShape
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.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.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.SurfaceContainerLow
import id.iiyh.inatrading.core.ui.theme.SurfaceContainerLowest

@Composable
fun AddShippingAddressScreen(
    onBack: () -> Unit,
    onSaveSuccess: () -> Unit,
    viewModel: AddShippingAddressViewModel = 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()
            onSaveSuccess()
        }
    }

    Scaffold(
        topBar = { InaInnerTopAppBar(onBack = onBack) },
        snackbarHost = { SnackbarHost(snackbarHostState) },
        containerColor = Background,
    ) { innerPadding ->
        LazyColumn(
            modifier = Modifier
                .fillMaxSize()
                .padding(innerPadding)
                .background(Background),
            contentPadding = PaddingValues(start = 20.dp, end = 20.dp, top = 16.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.add_shipping_address_eyebrow),
                        style = MaterialTheme.typography.labelSmall,
                        letterSpacing = 1.6.sp,
                        color = AccentPurple,
                    )
                    Text(
                        text = stringResource(R.string.add_shipping_address_title),
                        fontFamily = ManropeFontFamily,
                        fontWeight = FontWeight.ExtraBold,
                        fontSize = 34.sp,
                        lineHeight = 38.sp,
                        color = OnSurface,
                    )
                    Text(
                        text = stringResource(R.string.add_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(18.dp),
                ) {
                    Text(
                        text = stringResource(R.string.add_shipping_address_label_title),
                        fontFamily = ManropeFontFamily,
                        fontWeight = FontWeight.Bold,
                        fontSize = 15.sp,
                        color = OnSurface,
                    )

                    Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
                        AddressLabelChip(
                            text = stringResource(R.string.add_shipping_address_label_home),
                            selected = uiState.label.equals("rumah", ignoreCase = true) || uiState.label.equals("home", ignoreCase = true),
                            onClick = { viewModel.onLabelSelected("rumah") },
                        )
                        AddressLabelChip(
                            text = stringResource(R.string.add_shipping_address_label_office),
                            selected = uiState.label.equals("kantor", ignoreCase = true) || uiState.label.equals("office", ignoreCase = true),
                            onClick = { viewModel.onLabelSelected("kantor") },
                        )
                        AddressLabelChip(
                            text = stringResource(R.string.add_shipping_address_label_warehouse),
                            selected = uiState.label.equals("gudang", ignoreCase = true) || uiState.label.equals("warehouse", ignoreCase = true),
                            onClick = { viewModel.onLabelSelected("gudang") },
                        )
                        AddressLabelChip(
                            text = stringResource(R.string.add_shipping_address_label_other),
                            selected = uiState.label == AddShippingAddressViewModel.CUSTOM_LABEL_KEY,
                            icon = Icons.Outlined.Add,
                            onClick = viewModel::onCustomLabelSelected,
                        )
                    }

                    if (uiState.label == AddShippingAddressViewModel.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),
                        )
                    }

                    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),
                    )

                    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),
                            placeholder = stringResource(R.string.add_shipping_address_province_placeholder),
                        )
                        InaTextField(
                            value = uiState.city,
                            onValueChange = viewModel::onCityChange,
                            label = stringResource(R.string.add_shipping_address_city_label),
                            placeholder = stringResource(R.string.add_shipping_address_city_placeholder),
                        )
                    } 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),
                        placeholder = stringResource(R.string.add_shipping_address_postal_placeholder),
                    )

                    Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
                        Text(
                            text = stringResource(R.string.add_shipping_address_full_label),
                            fontFamily = ManropeFontFamily,
                            fontWeight = FontWeight.Bold,
                            fontSize = 15.sp,
                            color = OnSurface,
                        )
                        androidx.compose.material3.OutlinedTextField(
                            value = uiState.address,
                            onValueChange = viewModel::onAddressChange,
                            modifier = Modifier.fillMaxWidth(),
                            minLines = 4,
                            shape = RoundedCornerShape(16.dp),
                            textStyle = MaterialTheme.typography.bodyLarge.copy(color = OnSurface),
                            placeholder = {
                                Text(
                                    text = stringResource(R.string.add_shipping_address_full_placeholder),
                                    color = OnSurfaceVariant.copy(alpha = 0.6f),
                                )
                            },
                            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),
                                focusedPlaceholderColor = OnSurfaceVariant.copy(alpha = 0.6f),
                                unfocusedPlaceholderColor = OnSurfaceVariant.copy(alpha = 0.6f),
                            ),
                        )
                    }

                    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(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.CenterVertically,
                    ) {
                        Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
                            Text(
                                text = stringResource(R.string.add_shipping_address_primary_label),
                                fontFamily = ManropeFontFamily,
                                fontWeight = FontWeight.Bold,
                                fontSize = 15.sp,
                                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,
                        )
                    }

                    InaPrimaryButton(
                        text = stringResource(R.string.add_shipping_address_save),
                        onClick = viewModel::saveAddress,
                        isLoading = uiState.isSaving,
                        enabled = !uiState.isResolvingLocation,
                        modifier = Modifier.fillMaxWidth(),
                    )
                }
            }
        }
    }
}

@Composable
private fun AddressLabelChip(
    text: String,
    selected: Boolean,
    icon: androidx.compose.ui.graphics.vector.ImageVector? = null,
    onClick: () -> Unit,
) {
    Box(
        modifier = Modifier
            .clip(CircleShape)
            .background(if (selected) BrandRedContainer else SurfaceContainerLow)
            .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) BrandRed else OnSurfaceVariant,
                    modifier = Modifier.size(16.dp),
                )
            }
            Text(
                text = text,
                style = MaterialTheme.typography.labelLarge,
                color = if (selected) BrandRed else OnSurfaceVariant,
            )
        }
    }
}
