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

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
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.aspectRatio
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.layout.width
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.GridItemSpan
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.rememberLazyGridState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.LocationOn
import androidx.compose.material.icons.outlined.Search
import androidx.compose.material.icons.outlined.Tune
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.snapshotFlow
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.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.hilt.navigation.compose.hiltViewModel
import coil.compose.AsyncImage
import id.iiyh.inatrading.R
import id.iiyh.inatrading.core.ui.components.InaTextField
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.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
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.filter

@Composable
fun ExploreScreen(
    onLocationClick: (LocationItem) -> Unit = {},
    viewModel: ExploreViewModel = hiltViewModel(),
) {
    val uiState by viewModel.uiState.collectAsState()
    val gridState = rememberLazyGridState()

    LaunchedEffect(gridState) {
        snapshotFlow {
            val layoutInfo = gridState.layoutInfo
            val lastVisible = layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: -1
            lastVisible to layoutInfo.totalItemsCount
        }
            .filter { (_, totalCount) -> totalCount > 0 }
            .distinctUntilChanged()
            .collect { (lastVisible, totalCount) ->
                if (lastVisible >= totalCount - 5) {
                    viewModel.loadNextPage()
                }
            }
    }

    val featuredItems = uiState.filteredItems.take(5)
    val recommendedItems = uiState.filteredItems.drop(featuredItems.size)

    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(Background),
    ) {
        LazyVerticalGrid(
            columns = GridCells.Fixed(2),
            state = gridState,
            modifier = Modifier.fillMaxSize(),
            contentPadding = PaddingValues(start = 16.dp, end = 16.dp, top = 20.dp, bottom = 112.dp),
            horizontalArrangement = Arrangement.spacedBy(12.dp),
            verticalArrangement = Arrangement.spacedBy(16.dp),
        ) {
            item(span = { GridItemSpan(maxLineSpan) }) {
                ExploreHero(
                    totalItem = uiState.totalItem,
                    totalLoaded = uiState.items.size,
                )
            }

            item(span = { GridItemSpan(maxLineSpan) }) {
                ExploreSearchRow(
                    query = uiState.searchQuery,
                    onQueryChange = viewModel::onSearchQueryChange,
                )
            }

            when {
                uiState.isInitialLoading -> {
                    item(span = { GridItemSpan(maxLineSpan) }) {
                        ExploreCenterState(
                            title = stringResource(R.string.explore_loading_title),
                            body = stringResource(R.string.explore_loading_body),
                            loading = true,
                        )
                    }
                }
                uiState.errorMessage != null && uiState.items.isEmpty() -> {
                    item(span = { GridItemSpan(maxLineSpan) }) {
                        ExploreCenterState(
                            title = stringResource(R.string.explore_error_title),
                            body = uiState.errorMessage.orEmpty(),
                            actionLabel = stringResource(R.string.explore_retry),
                            onAction = viewModel::loadInitial,
                        )
                    }
                }
                uiState.filteredItems.isEmpty() -> {
                    item(span = { GridItemSpan(maxLineSpan) }) {
                        ExploreCenterState(
                            title = stringResource(R.string.explore_empty_title),
                            body = stringResource(R.string.explore_empty_body),
                        )
                    }
                }
                else -> {
                    if (featuredItems.isNotEmpty()) {
                        item(span = { GridItemSpan(maxLineSpan) }) {
                            SectionHeader(
                                eyebrow = stringResource(R.string.explore_featured_eyebrow),
                                title = stringResource(R.string.explore_featured_title),
                            )
                        }

                        item(span = { GridItemSpan(maxLineSpan) }) {
                            FeaturedHeroCard(
                                location = featuredItems.first(),
                                onClick = { onLocationClick(featuredItems.first()) },
                            )
                        }

                        if (featuredItems.size > 1) {
                            item(span = { GridItemSpan(maxLineSpan) }) {
                                FeaturedWideCard(
                                    location = featuredItems[1],
                                    onClick = { onLocationClick(featuredItems[1]) },
                                )
                            }
                        }

                        featuredItems.drop(2).forEach { location ->
                            item {
                                FeaturedCompactCard(
                                    location = location,
                                    onClick = { onLocationClick(location) },
                                )
                            }
                        }
                    }

                    if (recommendedItems.isNotEmpty()) {
                        item(span = { GridItemSpan(maxLineSpan) }) {
                            SectionHeader(
                                title = stringResource(R.string.explore_recommended_title),
                                body = stringResource(R.string.explore_recommended_body),
                            )
                        }

                        recommendedItems.forEach { location ->
                            item(key = location.id) {
                                RecommendedCard(
                                    location = location,
                                    onClick = { onLocationClick(location) },
                                )
                            }
                        }
                    }

                    if (uiState.isAppending) {
                        item(span = { GridItemSpan(maxLineSpan) }) {
                            Row(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(vertical = 8.dp),
                                horizontalArrangement = Arrangement.Center,
                            ) {
                                CircularProgressIndicator(
                                    modifier = Modifier.size(28.dp),
                                    color = BrandRed,
                                    strokeWidth = 2.5.dp,
                                )
                            }
                        }
                    }
                }
            }
        }
    }
}

@Composable
private fun ExploreHero(
    totalItem: Int,
    totalLoaded: Int,
) {
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .clip(RoundedCornerShape(28.dp))
            .background(
                brush = Brush.linearGradient(
                    listOf(
                        SurfaceContainerHighest,
                        Background,
                    )
                )
            )
            .padding(24.dp),
    ) {
        Box(
            modifier = Modifier
                .align(Alignment.TopEnd)
                .width(140.dp)
                .height(88.dp)
                .clip(RoundedCornerShape(24.dp))
                .background(BrandRed.copy(alpha = 0.08f)),
        )

        Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
            Text(
                text = stringResource(R.string.explore_hero_eyebrow),
                style = MaterialTheme.typography.labelMedium,
                color = AccentPurple,
                fontWeight = FontWeight.Bold,
            )
            Text(
                text = buildString {
                    append(stringResource(R.string.explore_hero_title_prefix))
                    append(" ")
                    append(stringResource(R.string.explore_hero_title_emphasis))
                },
                style = MaterialTheme.typography.displaySmall,
                color = OnSurface,
            )
            Text(
                text = stringResource(R.string.explore_hero_body),
                style = MaterialTheme.typography.bodyMedium,
                color = OnSurfaceVariant,
            )
            Surface(
                color = AccentPurpleContainer,
                shape = RoundedCornerShape(999.dp),
            ) {
                Text(
                    text = stringResource(R.string.explore_hero_counter, totalLoaded, totalItem),
                    modifier = Modifier.padding(horizontal = 14.dp, vertical = 8.dp),
                    style = MaterialTheme.typography.labelMedium,
                    color = OnAccentPurpleContainer,
                    fontWeight = FontWeight.Bold,
                )
            }
        }
    }
}

@Composable
private fun ExploreSearchRow(
    query: String,
    onQueryChange: (String) -> Unit,
) {
    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.spacedBy(12.dp),
        verticalAlignment = Alignment.CenterVertically,
    ) {
        InaTextField(
            value = query,
            onValueChange = onQueryChange,
            modifier = Modifier.weight(1f),
            placeholder = stringResource(R.string.explore_search_placeholder),
            leadingIcon = {
                Icon(
                    imageVector = Icons.Outlined.Search,
                    contentDescription = null,
                    tint = OnSurfaceVariant,
                )
            },
        )

        Surface(
            modifier = Modifier.size(52.dp),
            shape = RoundedCornerShape(18.dp),
            color = SurfaceContainerLow,
        ) {
            Box(contentAlignment = Alignment.Center) {
                Icon(
                    imageVector = Icons.Outlined.Tune,
                    contentDescription = stringResource(R.string.explore_filter),
                    tint = OnSurface,
                )
            }
        }
    }
}

@Composable
private fun SectionHeader(
    title: String,
    eyebrow: String? = null,
    body: String? = null,
) {
    Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
        eyebrow?.let {
            Text(
                text = it,
                style = MaterialTheme.typography.labelMedium,
                color = AccentBlue,
                fontWeight = FontWeight.Bold,
            )
        }
        Text(
            text = title,
            style = MaterialTheme.typography.headlineMedium,
            color = OnSurface,
        )
        body?.let {
            Text(
                text = it,
                style = MaterialTheme.typography.bodyMedium,
                color = OnSurfaceVariant,
            )
        }
    }
}

@Composable
private fun FeaturedHeroCard(
    location: LocationItem,
    onClick: () -> Unit,
) {
    Surface(
        onClick = onClick,
        shape = RoundedCornerShape(28.dp),
        color = SurfaceContainerLowest,
        shadowElevation = 2.dp,
    ) {
        Column {
            LocationImage(
                imageUrl = location.image1,
                modifier = Modifier
                    .fillMaxWidth()
                    .height(280.dp),
            )
            Column(
                modifier = Modifier.padding(20.dp),
                verticalArrangement = Arrangement.spacedBy(8.dp),
            ) {
                LocationTagRow(location = location, featured = true)
                Text(
                    text = location.name,
                    style = MaterialTheme.typography.headlineSmall,
                    color = OnSurface,
                )
                Text(
                    text = location.description.orEmpty().ifBlank {
                        stringResource(R.string.explore_description_fallback)
                    },
                    style = MaterialTheme.typography.bodyMedium,
                    color = OnSurfaceVariant,
                    maxLines = 3,
                    overflow = TextOverflow.Ellipsis,
                )
            }
        }
    }
}

@Composable
private fun FeaturedWideCard(
    location: LocationItem,
    onClick: () -> Unit,
) {
    Surface(
        onClick = onClick,
        shape = RoundedCornerShape(24.dp),
        color = SurfaceContainerLowest,
        shadowElevation = 1.dp,
    ) {
        Row(
            modifier = Modifier.fillMaxWidth(),
            verticalAlignment = Alignment.CenterVertically,
        ) {
            LocationImage(
                imageUrl = location.image1,
                modifier = Modifier
                    .weight(0.38f)
                    .height(160.dp),
            )
            Column(
                modifier = Modifier
                    .weight(0.62f)
                    .padding(18.dp),
                verticalArrangement = Arrangement.spacedBy(8.dp),
            ) {
                LocationTagRow(location = location)
                Text(
                    text = location.name,
                    style = MaterialTheme.typography.titleLarge,
                    color = OnSurface,
                    maxLines = 2,
                    overflow = TextOverflow.Ellipsis,
                )
                LocationMeta(location = location)
            }
        }
    }
}

@Composable
private fun FeaturedCompactCard(
    location: LocationItem,
    onClick: () -> Unit,
) {
    Surface(
        onClick = onClick,
        shape = RoundedCornerShape(22.dp),
        color = SurfaceContainerLowest,
        shadowElevation = 1.dp,
    ) {
        Column {
            LocationImage(
                imageUrl = location.image1,
                modifier = Modifier
                    .fillMaxWidth()
                    .height(136.dp),
            )
            Column(
                modifier = Modifier.padding(16.dp),
                verticalArrangement = Arrangement.spacedBy(6.dp),
            ) {
                Text(
                    text = location.type.orEmpty().ifBlank {
                        stringResource(R.string.explore_type_fallback)
                    },
                    style = MaterialTheme.typography.labelSmall,
                    color = AccentBlue,
                    fontWeight = FontWeight.Bold,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis,
                )
                Text(
                    text = location.name,
                    style = MaterialTheme.typography.titleMedium,
                    color = OnSurface,
                    maxLines = 2,
                    overflow = TextOverflow.Ellipsis,
                )
            }
        }
    }
}

@Composable
private fun RecommendedCard(
    location: LocationItem,
    onClick: () -> Unit,
) {
    Column(
        modifier = Modifier.clickable(onClick = onClick),
        verticalArrangement = Arrangement.spacedBy(10.dp),
    ) {
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .aspectRatio(4f / 3f)
                .clip(RoundedCornerShape(22.dp)),
        ) {
            LocationImage(
                imageUrl = location.image1,
                modifier = Modifier.fillMaxSize(),
            )
            Surface(
                modifier = Modifier
                    .align(Alignment.BottomStart)
                    .padding(12.dp),
                shape = RoundedCornerShape(999.dp),
                color = Color.White.copy(alpha = 0.92f),
            ) {
                Text(
                    text = location.type.orEmpty().ifBlank {
                        stringResource(R.string.explore_type_fallback)
                    },
                    modifier = Modifier.padding(horizontal = 12.dp, vertical = 6.dp),
                    style = MaterialTheme.typography.labelSmall,
                    color = OnSurface,
                    fontWeight = FontWeight.Bold,
                )
            }
        }
        Text(
            text = location.name,
            style = MaterialTheme.typography.titleLarge,
            color = OnSurface,
            maxLines = 2,
            overflow = TextOverflow.Ellipsis,
        )
        LocationMeta(location = location)
    }
}

@Composable
private fun LocationImage(
    imageUrl: String?,
    modifier: Modifier = Modifier,
) {
    if (imageUrl.isNullOrBlank()) {
        Box(
            modifier = modifier.background(SurfaceContainerLow),
            contentAlignment = Alignment.Center,
        ) {
            Icon(
                imageVector = Icons.Outlined.LocationOn,
                contentDescription = null,
                tint = BrandRed.copy(alpha = 0.7f),
                modifier = Modifier.size(28.dp),
            )
        }
        return
    }

    AsyncImage(
        model = imageUrl,
        contentDescription = null,
        modifier = modifier,
        contentScale = ContentScale.Crop,
    )
}

@Composable
private fun LocationTagRow(
    location: LocationItem,
    featured: Boolean = false,
) {
    Row(
        horizontalArrangement = Arrangement.spacedBy(8.dp),
        verticalAlignment = Alignment.CenterVertically,
    ) {
        Text(
            text = buildLocationBadge(location).ifBlank {
                stringResource(R.string.explore_type_fallback)
            },
            style = MaterialTheme.typography.labelSmall,
            color = AccentBlue,
            fontWeight = FontWeight.Bold,
            maxLines = 1,
            overflow = TextOverflow.Ellipsis,
        )
        if (featured) {
            Surface(
                color = BrandRed.copy(alpha = 0.12f),
                shape = RoundedCornerShape(999.dp),
            ) {
                Text(
                    text = stringResource(R.string.explore_featured_badge),
                    modifier = Modifier.padding(horizontal = 10.dp, vertical = 5.dp),
                    style = MaterialTheme.typography.labelSmall,
                    color = BrandRed,
                    fontWeight = FontWeight.Bold,
                )
            }
        }
    }
}

@Composable
private fun LocationMeta(location: LocationItem) {
    Row(
        horizontalArrangement = Arrangement.spacedBy(6.dp),
        verticalAlignment = Alignment.CenterVertically,
    ) {
        Icon(
            imageVector = Icons.Outlined.LocationOn,
            contentDescription = null,
            tint = OnSurfaceVariant,
            modifier = Modifier.size(16.dp),
        )
        Text(
            text = buildLocationSubtitle(location),
            style = MaterialTheme.typography.bodySmall,
            color = OnSurfaceVariant,
            maxLines = 2,
            overflow = TextOverflow.Ellipsis,
        )
    }
}

@Composable
private fun ExploreCenterState(
    title: String,
    body: String,
    loading: Boolean = false,
    actionLabel: String? = null,
    onAction: (() -> Unit)? = null,
) {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 48.dp, horizontal = 20.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.spacedBy(12.dp),
    ) {
        if (loading) {
            CircularProgressIndicator(
                color = BrandRed,
                strokeWidth = 3.dp,
            )
        }
        Text(
            text = title,
            style = MaterialTheme.typography.headlineSmall,
            color = OnSurface,
        )
        Text(
            text = body,
            style = MaterialTheme.typography.bodyMedium,
            color = OnSurfaceVariant,
        )
        if (actionLabel != null && onAction != null) {
            Button(onClick = onAction) {
                Text(text = actionLabel)
            }
        }
    }
}

private fun buildLocationBadge(location: LocationItem): String {
    val type = location.type?.takeIf { it.isNotBlank() }
    val area = location.city?.takeIf { it.isNotBlank() }
        ?: location.province?.takeIf { it.isNotBlank() }
        ?: location.country?.takeIf { it.isNotBlank() }

    return listOfNotNull(type, area).joinToString(" • ")
}

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