package id.iiyh.inatrading.feature.explore.presentation

import android.content.Intent
import android.net.Uri
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
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.outlined.Call
import androidx.compose.material.icons.outlined.LocationOn
import androidx.compose.material.icons.outlined.Map
import androidx.compose.material.icons.outlined.QrCode2
import androidx.compose.material.icons.outlined.Schedule
import androidx.compose.material.icons.outlined.ShoppingBag
import androidx.compose.material.icons.outlined.Verified
import androidx.compose.material3.Button
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.ripple
import androidx.compose.runtime.Composable
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.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
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 coil.compose.AsyncImage
import id.iiyh.inatrading.R
import id.iiyh.inatrading.core.ui.theme.AccentBlue
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.BrandRedLight
import id.iiyh.inatrading.core.ui.theme.ManropeFontFamily
import id.iiyh.inatrading.core.ui.theme.OnAccentPurpleContainer
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.explore.data.model.LocationItem

@Composable
fun ExploreDetailScreen(
    location: LocationItem,
    onBack: () -> Unit,
) {
    val context = LocalContext.current
    val gallery = listOfNotNull(
        location.image1,
        location.image2,
        location.image3,
        location.image4,
        location.image5,
    ).ifEmpty { listOf("") }

    Scaffold(
        topBar = {
            ExploreDetailTopBar(
                title = location.name,
                onBack = onBack,
            )
        },
        floatingActionButton = {
            FloatingActionButton(
                onClick = {},
                containerColor = BrandRed,
                contentColor = Color.White,
                shape = RoundedCornerShape(20.dp),
            ) {
                Icon(
                    imageVector = Icons.Outlined.ShoppingBag,
                    contentDescription = stringResource(R.string.explore_detail_fab),
                )
            }
        },
        containerColor = Background,
    ) { innerPadding ->
        androidx.compose.foundation.lazy.LazyColumn(
            modifier = Modifier
                .fillMaxSize()
                .padding(innerPadding)
                .background(Background),
            contentPadding = PaddingValues(start = 24.dp, end = 24.dp, top = 12.dp, bottom = 120.dp),
            verticalArrangement = Arrangement.spacedBy(24.dp),
        ) {
            item {
                HeroGallerySection(
                    imageUrl = location.image1,
                    showVerified = location.status.equals("APPROVED", ignoreCase = true),
                )
            }

            item {
                TitleIdentitySection(location = location)
            }

            item {
                StorySection(location = location)
            }

            item {
                VisitSection(
                    location = location,
                    onOpenMaps = {
                        openLocationInMaps(context = context, location = location)
                    },
                )
            }

            item {
                SignaturePrintsSection(
                    title = location.type ?: stringResource(R.string.explore_type_fallback),
                    gallery = gallery,
                )
            }
        }
    }
}

@Composable
private fun ExploreDetailTopBar(
    title: String,
    onBack: () -> Unit,
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .background(Color.White.copy(alpha = 0.88f))
            .padding(horizontal = 20.dp, vertical = 14.dp),
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.SpaceBetween,
    ) {
        DetailIconButton(
            icon = Icons.AutoMirrored.Outlined.ArrowBack,
            contentDescription = stringResource(R.string.favorite_back),
            onClick = onBack,
        )
        Text(
            text = title,
            modifier = Modifier.weight(1f).padding(horizontal = 12.dp),
            style = MaterialTheme.typography.titleLarge,
            fontFamily = ManropeFontFamily,
            fontWeight = FontWeight.ExtraBold,
            color = BrandRed,
            maxLines = 1,
            overflow = TextOverflow.Ellipsis,
        )
        DetailIconButton(
            icon = Icons.Outlined.Verified,
            contentDescription = stringResource(R.string.explore_detail_verified),
            onClick = {},
        )
    }
}

@Composable
private fun HeroGallerySection(
    imageUrl: String?,
    showVerified: Boolean,
) {
    Box {
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .aspectRatio(4f / 5f)
                .clip(RoundedCornerShape(28.dp))
                .background(SurfaceContainerLow),
        ) {
            if (!imageUrl.isNullOrBlank()) {
                AsyncImage(
                    model = imageUrl,
                    contentDescription = null,
                    contentScale = ContentScale.Crop,
                    modifier = Modifier.fillMaxSize(),
                )
            } else {
                Box(
                    modifier = Modifier.fillMaxSize(),
                    contentAlignment = Alignment.Center,
                ) {
                    Icon(
                        imageVector = Icons.Outlined.LocationOn,
                        contentDescription = null,
                        tint = BrandRed,
                        modifier = Modifier.size(48.dp),
                    )
                }
            }
        }

        if (showVerified) {
            Surface(
                modifier = Modifier
                    .align(Alignment.BottomEnd)
                    .padding(end = 20.dp, bottom = 20.dp),
                color = AccentPurple,
                shape = RoundedCornerShape(24.dp),
                shadowElevation = 6.dp,
            ) {
                Box(
                    modifier = Modifier
                        .size(88.dp)
                        .padding(8.dp),
                    contentAlignment = Alignment.Center,
                ) {
                    Icon(
                        imageVector = Icons.Outlined.Verified,
                        contentDescription = null,
                        tint = Color.White,
                        modifier = Modifier.size(40.dp),
                    )
                }
            }
        }
    }
}

@Composable
private fun TitleIdentitySection(location: LocationItem) {
    Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
        Row(
            horizontalArrangement = Arrangement.spacedBy(8.dp),
            verticalAlignment = Alignment.CenterVertically,
        ) {
            Surface(
                color = AccentPurpleContainer,
                shape = RoundedCornerShape(999.dp),
            ) {
                Text(
                    text = stringResource(R.string.explore_featured_eyebrow),
                    modifier = Modifier.padding(horizontal = 12.dp, vertical = 7.dp),
                    style = MaterialTheme.typography.labelMedium,
                    color = OnAccentPurpleContainer,
                    fontWeight = FontWeight.Bold,
                )
            }
            Text(
                text = location.type.orEmpty().ifBlank { stringResource(R.string.explore_type_fallback) },
                style = MaterialTheme.typography.labelMedium,
                color = OnSurfaceVariant,
                fontWeight = FontWeight.Bold,
            )
        }

        Text(
            text = location.name,
            style = MaterialTheme.typography.displaySmall,
            color = OnSurface,
            fontWeight = FontWeight.ExtraBold,
        )

        Row(
            horizontalArrangement = Arrangement.spacedBy(6.dp),
            verticalAlignment = Alignment.CenterVertically,
        ) {
            Icon(
                imageVector = Icons.Outlined.LocationOn,
                contentDescription = null,
                tint = BrandRed,
                modifier = Modifier.size(18.dp),
            )
            Text(
                text = location.address?.takeIf { it.isNotBlank() } ?: buildLocationLabel(location),
                style = MaterialTheme.typography.bodyMedium,
                color = OnSurfaceVariant,
                maxLines = 2,
                overflow = TextOverflow.Ellipsis,
            )
        }
    }
}

@Composable
private fun StorySection(location: LocationItem) {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .clip(RoundedCornerShape(28.dp))
            .background(SurfaceContainerHighest.copy(alpha = 0.7f))
            .padding(vertical = 28.dp, horizontal = 20.dp),
        verticalArrangement = Arrangement.spacedBy(20.dp),
    ) {
        Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
            Text(
                text = stringResource(R.string.explore_detail_story_title),
                style = MaterialTheme.typography.headlineSmall,
                color = OnSurface,
                fontWeight = FontWeight.Bold,
            )
            Text(
                text = location.description.orEmpty().ifBlank {
                    stringResource(R.string.explore_description_fallback)
                },
                style = MaterialTheme.typography.bodyLarge,
                color = OnSurfaceVariant,
            )
        }

        Button(
            onClick = {},
            shape = RoundedCornerShape(18.dp),
        ) {
            Text(text = stringResource(R.string.explore_detail_explore_collection))
        }

        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.spacedBy(12.dp),
        ) {
            DetailInfoCard(
                modifier = Modifier.weight(1f),
                icon = Icons.Outlined.Call,
                title = stringResource(R.string.explore_detail_contact),
                value = location.contact ?: stringResource(R.string.explore_detail_value_unavailable),
                iconTint = AccentBlue,
            )
            DetailInfoCard(
                modifier = Modifier.weight(1f),
                icon = Icons.Outlined.Schedule,
                title = stringResource(R.string.explore_detail_status),
                value = location.status ?: stringResource(R.string.explore_detail_open_daily),
                iconTint = AccentPurple,
            )
        }

        DetailMerchantCard(location = location)
    }
}

@Composable
private fun DetailInfoCard(
    modifier: Modifier = Modifier,
    icon: ImageVector,
    title: String,
    value: String,
    iconTint: Color,
) {
    Surface(
        modifier = modifier,
        shape = RoundedCornerShape(22.dp),
        color = SurfaceContainerLowest,
    ) {
        Column(
            modifier = Modifier.padding(18.dp),
            verticalArrangement = Arrangement.spacedBy(10.dp),
        ) {
            Icon(
                imageVector = icon,
                contentDescription = null,
                tint = iconTint,
            )
            Text(
                text = title,
                style = MaterialTheme.typography.labelSmall,
                color = OnSurfaceVariant,
                fontWeight = FontWeight.Bold,
            )
            Text(
                text = value,
                style = MaterialTheme.typography.titleMedium,
                color = OnSurface,
                maxLines = 2,
                overflow = TextOverflow.Ellipsis,
            )
        }
    }
}

@Composable
private fun DetailMerchantCard(location: LocationItem) {
    Surface(
        shape = RoundedCornerShape(22.dp),
        color = SurfaceContainerLowest,
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(18.dp),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically,
        ) {
            Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
                Text(
                    text = stringResource(R.string.explore_detail_merchant_id),
                    style = MaterialTheme.typography.labelSmall,
                    color = OnSurfaceVariant,
                    fontWeight = FontWeight.Bold,
                )
                Text(
                    text = buildMerchantCode(location),
                    style = MaterialTheme.typography.titleMedium,
                    color = OnSurface,
                )
            }

            Box(
                modifier = Modifier
                    .size(48.dp)
                    .clip(RoundedCornerShape(14.dp))
                    .background(SurfaceContainerLow),
                contentAlignment = Alignment.Center,
            ) {
                Icon(
                    imageVector = Icons.Outlined.QrCode2,
                    contentDescription = null,
                    tint = OnSurface,
                )
            }
        }
    }
}

@Composable
private fun VisitSection(
    location: LocationItem,
    onOpenMaps: () -> Unit,
) {
    Surface(
        shape = RoundedCornerShape(28.dp),
        color = SurfaceContainerLowest,
    ) {
        Column(
            modifier = Modifier.padding(20.dp),
            verticalArrangement = Arrangement.spacedBy(18.dp),
        ) {
            Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
                Text(
                    text = stringResource(R.string.explore_detail_visit_title),
                    style = MaterialTheme.typography.headlineSmall,
                    color = OnSurface,
                    fontWeight = FontWeight.ExtraBold,
                )
                Text(
                    text = location.address?.takeIf { it.isNotBlank() } ?: buildLocationLabel(location),
                    style = MaterialTheme.typography.bodyMedium,
                    color = OnSurfaceVariant,
                )
            }

            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .aspectRatio(21f / 9f)
                    .clip(RoundedCornerShape(22.dp))
                    .background(SurfaceContainerHighest),
            ) {
                if (!location.image1.isNullOrBlank()) {
                    AsyncImage(
                        model = location.image1,
                        contentDescription = null,
                        contentScale = ContentScale.Crop,
                        modifier = Modifier.fillMaxSize(),
                        alpha = 0.45f,
                    )
                }
                Box(
                    modifier = Modifier
                        .align(Alignment.Center)
                        .size(56.dp)
                        .clip(RoundedCornerShape(999.dp))
                        .background(BrandRed),
                    contentAlignment = Alignment.Center,
                ) {
                    Icon(
                        imageVector = Icons.Outlined.LocationOn,
                        contentDescription = null,
                        tint = Color.White,
                    )
                }
            }

            Button(
                onClick = onOpenMaps,
                modifier = Modifier.fillMaxWidth(),
                shape = RoundedCornerShape(18.dp),
            ) {
                Icon(
                    imageVector = Icons.Outlined.Map,
                    contentDescription = null,
                )
                Spacer(modifier = Modifier.width(8.dp))
                Text(text = stringResource(R.string.explore_detail_open_maps))
            }
        }
    }
}

@Composable
private fun SignaturePrintsSection(
    title: String,
    gallery: List<String>,
) {
    Column(verticalArrangement = Arrangement.spacedBy(16.dp)) {
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically,
        ) {
            Text(
                text = stringResource(R.string.explore_detail_signature_title),
                style = MaterialTheme.typography.headlineSmall,
                color = OnSurface,
                fontWeight = FontWeight.ExtraBold,
            )
            Text(
                text = stringResource(R.string.profile_view_all),
                style = MaterialTheme.typography.labelMedium,
                color = BrandRed,
                fontWeight = FontWeight.Bold,
            )
        }

        Row(
            modifier = Modifier
                .fillMaxWidth()
                .horizontalScroll(rememberScrollState()),
            horizontalArrangement = Arrangement.spacedBy(16.dp),
        ) {
            gallery.forEachIndexed { index, imageUrl ->
                Column(
                    modifier = Modifier.width(220.dp),
                    verticalArrangement = Arrangement.spacedBy(10.dp),
                ) {
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .aspectRatio(1f)
                            .clip(RoundedCornerShape(24.dp))
                            .background(SurfaceContainerLow),
                    ) {
                        if (imageUrl.isNotBlank()) {
                            AsyncImage(
                                model = imageUrl,
                                contentDescription = null,
                                contentScale = ContentScale.Crop,
                                modifier = Modifier.fillMaxSize(),
                            )
                        }
                    }
                    Text(
                        text = title,
                        style = MaterialTheme.typography.labelSmall,
                        color = OnSurfaceVariant,
                        fontWeight = FontWeight.Bold,
                    )
                    Text(
                        text = stringResource(R.string.explore_detail_gallery_item, index + 1),
                        style = MaterialTheme.typography.titleMedium,
                        color = OnSurface,
                    )
                }
            }
        }
    }
}

@Composable
private fun DetailIconButton(
    icon: ImageVector,
    contentDescription: String,
    onClick: () -> Unit,
) {
    Box(
        modifier = Modifier
            .size(40.dp)
            .clip(RoundedCornerShape(999.dp))
            .clickable(
                interactionSource = remember { MutableInteractionSource() },
                indication = ripple(),
                onClick = onClick,
            ),
        contentAlignment = Alignment.Center,
    ) {
        Icon(
            imageVector = icon,
            contentDescription = contentDescription,
            tint = BrandRed,
        )
    }
}

private fun openLocationInMaps(
    context: android.content.Context,
    location: LocationItem,
) {
    val label = Uri.encode(location.name)
    val address = Uri.encode(location.address ?: buildLocationLabel(location))
    val uri = if (location.latitude != null && location.longitude != null) {
        Uri.parse("geo:${location.latitude},${location.longitude}?q=${location.latitude},${location.longitude}($label)")
    } else {
        Uri.parse("geo:0,0?q=$address")
    }
    val intent = Intent(Intent.ACTION_VIEW, uri)
    runCatching { context.startActivity(intent) }
}

private fun buildLocationLabel(location: LocationItem): String {
    return listOfNotNull(
        location.city?.takeIf { it.isNotBlank() },
        location.province?.takeIf { it.isNotBlank() },
        location.country?.takeIf { it.isNotBlank() },
    ).joinToString(", ").ifBlank { "Indonesia" }
}

private fun buildMerchantCode(location: LocationItem): String {
    val prefix = location.name
        .split(" ")
        .filter { it.isNotBlank() }
        .take(2)
        .joinToString("") { it.take(1).uppercase() }
        .ifBlank { "LOC" }
    val area = (location.city ?: location.province ?: location.country)
        .orEmpty()
        .replace(Regex("[^A-Za-z]"), "")
        .take(3)
        .uppercase()
        .ifBlank { "IDN" }
    val suffix = location.id.takeLast(4).uppercase()
    return "$prefix-$area-$suffix"
}
