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

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.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.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.itemsIndexed
import androidx.compose.foundation.lazy.grid.rememberLazyGridState
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.filled.CreateNewFolder
import androidx.compose.material.icons.outlined.CardGiftcard
import androidx.compose.material.icons.outlined.DeleteOutline
import androidx.compose.material.icons.outlined.Edit
import androidx.compose.material.icons.outlined.HomeWork
import androidx.compose.material.icons.outlined.MoreVert
import androidx.compose.material.icons.outlined.Refresh
import androidx.compose.material.icons.outlined.Restaurant
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
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.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
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.graphics.vector.ImageVector
import androidx.compose.ui.res.pluralStringResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
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.InaPrimaryButton
import id.iiyh.inatrading.core.ui.components.InaTextField
import id.iiyh.inatrading.core.ui.theme.AccentBlue
import id.iiyh.inatrading.core.ui.theme.AccentBlueContainer
import id.iiyh.inatrading.core.ui.theme.AccentPurple
import id.iiyh.inatrading.core.ui.theme.AccentPurpleContainer
import id.iiyh.inatrading.core.ui.theme.Background
import id.iiyh.inatrading.core.ui.theme.BrandRed
import id.iiyh.inatrading.core.ui.theme.BrandRedLight
import id.iiyh.inatrading.core.ui.theme.ManropeFontFamily
import id.iiyh.inatrading.core.ui.theme.OnSurface
import id.iiyh.inatrading.core.ui.theme.OnSurfaceVariant
import id.iiyh.inatrading.core.ui.theme.SurfaceContainerHighest
import id.iiyh.inatrading.core.ui.theme.SurfaceContainerLow
import id.iiyh.inatrading.core.ui.theme.SurfaceContainerLowest
import id.iiyh.inatrading.feature.favorite.domain.FavoriteGroupSummary
import id.iiyh.inatrading.feature.favorite.presentation.FavoritesViewModel

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun FavoritesScreen(
    onBack: () -> Unit,
    onBrowseProducts: () -> Unit,
    onGroupClick: (FavoriteGroupSummary) -> Unit,
    onSessionExpired: () -> Unit,
    viewModel: FavoritesViewModel = hiltViewModel(),
) {
    val uiState by viewModel.uiState.collectAsState()
    val snackbarHostState = remember { SnackbarHostState() }
    var createDialogOpen by remember { mutableStateOf(false) }
    var editingGroup by remember { mutableStateOf<FavoriteGroupSummary?>(null) }
    var deletingGroup by remember { mutableStateOf<FavoriteGroupSummary?>(null) }
    val gridState = rememberLazyGridState()

    LaunchedEffect(uiState.errorMessage) {
        uiState.errorMessage?.let { snackbarHostState.showSnackbar(it) }
    }

    LaunchedEffect(uiState.sessionExpired) {
        if (uiState.sessionExpired) {
            viewModel.consumeSessionExpired()
            onSessionExpired()
        }
    }

    Scaffold(
        topBar = {
            FavoritesTopBar(
                onBack = onBack,
                onCreateClick = { createDialogOpen = true },
            )
        },
        snackbarHost = { SnackbarHost(hostState = snackbarHostState) },
        floatingActionButton = {
            Box(
                modifier = Modifier
                    .size(56.dp)
                    .clip(RoundedCornerShape(18.dp))
                    .background(BrandRed)
                    .clickable(onClick = { createDialogOpen = true }),
                contentAlignment = Alignment.Center,
            ) {
                Icon(
                    imageVector = Icons.Filled.CreateNewFolder,
                    contentDescription = stringResource(R.string.favorite_create_collection),
                    tint = Color.White,
                    modifier = Modifier.size(28.dp),
                )
            }
        },
        containerColor = Background,
    ) { innerPadding ->
        LazyVerticalGrid(
            columns = GridCells.Adaptive(minSize = 160.dp),
            state = gridState,
            modifier = Modifier
                .fillMaxSize()
                .background(Background)
                .padding(innerPadding),
            contentPadding = androidx.compose.foundation.layout.PaddingValues(
                start = 24.dp,
                end = 24.dp,
                top = 20.dp,
                bottom = 104.dp,
            ),
            horizontalArrangement = Arrangement.spacedBy(16.dp),
            verticalArrangement = Arrangement.spacedBy(16.dp),
        ) {
            item(span = { androidx.compose.foundation.lazy.grid.GridItemSpan(maxLineSpan) }) {
                FavoritesHero()
            }

            if (uiState.isLoading) {
                item(span = { androidx.compose.foundation.lazy.grid.GridItemSpan(maxLineSpan) }) {
                    LoadingState()
                }
            } else if (uiState.groups.isEmpty()) {
                item(span = { androidx.compose.foundation.lazy.grid.GridItemSpan(maxLineSpan) }) {
                    EmptyState(onBrowseProducts = onBrowseProducts, onCreateClick = { createDialogOpen = true })
                }
            } else {
                itemsIndexed(uiState.groups, key = { _, item -> item.id }) { index, group ->
                    FavoriteGroupCard(
                        group = group,
                        accent = accentFor(index),
                        onClick = { onGroupClick(group) },
                        onEdit = { editingGroup = group },
                        onDelete = { deletingGroup = group },
                    )
                }

                item {
                    CreateCollectionCard(onClick = { createDialogOpen = true })
                }
            }

            if (!uiState.isLoading && uiState.groups.isNotEmpty()) {
                item(span = { androidx.compose.foundation.lazy.grid.GridItemSpan(maxLineSpan) }) {
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(top = 4.dp),
                        horizontalArrangement = Arrangement.Center,
                    ) {
                        TextButton(onClick = viewModel::loadFavorites) {
                            Icon(
                                imageVector = Icons.Outlined.Refresh,
                                contentDescription = null,
                                tint = BrandRed,
                                modifier = Modifier.size(18.dp),
                            )
                            Text(
                                text = stringResource(R.string.favorite_refresh),
                                color = BrandRed,
                                modifier = Modifier.padding(start = 8.dp),
                            )
                        }
                    }
                }
            }
        }
    }

    if (createDialogOpen) {
        FavoriteNameDialog(
            title = stringResource(R.string.favorite_create_collection),
            confirmLabel = stringResource(R.string.favorite_create_action),
            initialValue = "",
            isSubmitting = uiState.isSubmitting,
            onDismiss = { createDialogOpen = false },
            onConfirm = { name ->
                createDialogOpen = false
                viewModel.createGroup(name)
            },
        )
    }

    editingGroup?.let { group ->
        FavoriteNameDialog(
            title = stringResource(R.string.favorite_edit_collection),
            confirmLabel = stringResource(R.string.favorite_save_action),
            initialValue = group.name,
            isSubmitting = uiState.isSubmitting,
            onDismiss = { editingGroup = null },
            onConfirm = { name ->
                editingGroup = null
                viewModel.renameGroup(group.id, name)
            },
        )
    }

    deletingGroup?.let { group ->
        DeleteFavoriteDialog(
            name = group.name,
            isSubmitting = uiState.isSubmitting,
            onDismiss = { deletingGroup = null },
            onConfirm = {
                deletingGroup = null
                viewModel.deleteGroup(group.id)
            },
        )
    }
}

@Composable
private fun FavoritesTopBar(
    onBack: () -> Unit,
    onCreateClick: () -> Unit,
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .background(Color.White.copy(alpha = 0.88f))
            .padding(horizontal = 20.dp, vertical = 16.dp),
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.SpaceBetween,
    ) {
        Row(verticalAlignment = Alignment.CenterVertically) {
            IconAction(
                icon = Icons.AutoMirrored.Outlined.ArrowBack,
                contentDescription = stringResource(R.string.favorite_back),
                onClick = onBack,
            )
            Text(
                text = stringResource(R.string.profile_my_favorites),
                fontFamily = ManropeFontFamily,
                fontWeight = FontWeight.Bold,
                fontSize = 20.sp,
                color = BrandRed,
                modifier = Modifier.padding(start = 8.dp),
            )
        }

        IconAction(
            icon = Icons.Filled.CreateNewFolder,
            contentDescription = stringResource(R.string.favorite_create_collection),
            onClick = onCreateClick,
        )
    }
}

@Composable
private fun FavoritesHero() {
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .height(170.dp)
    ) {
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .height(154.dp)
                .clip(RoundedCornerShape(40.dp))
                .background(SurfaceContainerHighest.copy(alpha = 0.42f))
        )

        Column(
            modifier = Modifier
                .fillMaxWidth()
                .align(Alignment.CenterStart)
                .padding(horizontal = 24.dp),
            verticalArrangement = Arrangement.spacedBy(8.dp),
        ) {
            Text(
                text = stringResource(R.string.profile_favorites_eyebrow),
                style = MaterialTheme.typography.labelMedium,
                fontWeight = FontWeight.Bold,
                color = AccentBlue,
                letterSpacing = 2.sp,
            )
            Text(
                text = stringResource(R.string.favorite_hero_title),
                fontFamily = ManropeFontFamily,
                fontWeight = FontWeight.ExtraBold,
                fontSize = 32.sp,
                lineHeight = 36.sp,
                color = OnSurface,
            )
        }
    }
}

@Composable
private fun FavoriteGroupCard(
    group: FavoriteGroupSummary,
    accent: FavoriteAccent,
    onClick: () -> Unit,
    onEdit: () -> Unit,
    onDelete: () -> Unit,
) {
    var expanded by remember { mutableStateOf(false) }

    Box(
        modifier = Modifier
            .fillMaxWidth()
            .height(188.dp)
            .clip(RoundedCornerShape(18.dp))
            .background(SurfaceContainerLowest)
            .clickable(
                interactionSource = remember { MutableInteractionSource() },
                indication = ripple(),
                onClick = onClick,
            )
            .padding(18.dp),
    ) {
        Column(
            modifier = Modifier.fillMaxSize(),
            verticalArrangement = Arrangement.SpaceBetween,
        ) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.Top,
            ) {
                Box(
                    modifier = Modifier
                        .size(48.dp)
                        .clip(RoundedCornerShape(14.dp))
                        .background(accent.container),
                    contentAlignment = Alignment.Center,
                ) {
                    Icon(
                        imageVector = accent.icon,
                        contentDescription = null,
                        tint = accent.tint,
                        modifier = Modifier.size(24.dp),
                    )
                }

                Box {
                    IconAction(
                        icon = Icons.Outlined.MoreVert,
                        contentDescription = stringResource(R.string.favorite_more_options),
                        onClick = { expanded = true },
                    )
                    DropdownMenu(
                        expanded = expanded,
                        onDismissRequest = { expanded = false },
                    ) {
                        DropdownMenuItem(
                            text = { Text(stringResource(R.string.favorite_edit_action)) },
                            leadingIcon = {
                                Icon(Icons.Outlined.Edit, contentDescription = null)
                            },
                            onClick = {
                                expanded = false
                                onEdit()
                            },
                        )
                        DropdownMenuItem(
                            text = { Text(stringResource(R.string.favorite_delete_action)) },
                            leadingIcon = {
                                Icon(Icons.Outlined.DeleteOutline, contentDescription = null)
                            },
                            onClick = {
                                expanded = false
                                onDelete()
                            },
                        )
                    }
                }
            }

            Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
                Text(
                    text = group.name,
                    fontFamily = ManropeFontFamily,
                    fontWeight = FontWeight.Bold,
                    fontSize = 20.sp,
                    color = OnSurface,
                    maxLines = 2,
                )
                Text(
                    text = pluralStringResource(
                        R.plurals.favorite_products_count,
                        group.itemCount,
                        group.itemCount,
                    ),
                    style = MaterialTheme.typography.bodyMedium,
                    color = OnSurfaceVariant,
                )
                if (group.isDefault) {
                    Text(
                        text = stringResource(R.string.favorite_default_collection),
                        style = MaterialTheme.typography.labelSmall,
                        fontWeight = FontWeight.Bold,
                        color = BrandRed,
                        letterSpacing = 1.sp,
                    )
                }
            }
        }

        Box(
            modifier = Modifier
                .align(Alignment.BottomEnd)
                .size(72.dp)
                .clip(RoundedCornerShape(16.dp))
                .background(accent.container.copy(alpha = 0.55f)),
            contentAlignment = Alignment.Center,
        ) {
            Icon(
                imageVector = accent.icon,
                contentDescription = null,
                tint = accent.tint.copy(alpha = 0.85f),
                modifier = Modifier.size(32.dp),
            )
        }
    }
}

@Composable
private fun CreateCollectionCard(
    onClick: () -> Unit,
) {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .height(188.dp)
            .clip(RoundedCornerShape(18.dp))
            .background(Color.Transparent)
            .clickable(
                interactionSource = remember { MutableInteractionSource() },
                indication = ripple(),
                onClick = onClick,
            )
            .padding(2.dp)
            .clip(RoundedCornerShape(18.dp))
            .background(BrandRed.copy(alpha = 0.04f))
            .padding(18.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center,
    ) {
        Box(
            modifier = Modifier
                .size(52.dp)
                .clip(RoundedCornerShape(16.dp))
                .background(SurfaceContainerLow),
            contentAlignment = Alignment.Center,
        ) {
            Icon(
                imageVector = Icons.Filled.CreateNewFolder,
                contentDescription = null,
                tint = OnSurfaceVariant,
                modifier = Modifier.size(26.dp),
            )
        }
        Text(
            text = stringResource(R.string.favorite_create_collection),
            fontFamily = ManropeFontFamily,
            fontWeight = FontWeight.Bold,
            fontSize = 16.sp,
            color = OnSurfaceVariant,
            textAlign = TextAlign.Center,
            modifier = Modifier.padding(top = 12.dp),
        )
    }
}

@Composable
private fun EmptyState(
    onBrowseProducts: () -> Unit,
    onCreateClick: () -> Unit,
) {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .clip(RoundedCornerShape(24.dp))
            .background(SurfaceContainerLowest)
            .padding(horizontal = 24.dp, vertical = 32.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.spacedBy(14.dp),
    ) {
        Text(
            text = stringResource(R.string.profile_favorites_empty_title),
            fontFamily = ManropeFontFamily,
            fontWeight = FontWeight.ExtraBold,
            fontSize = 22.sp,
            color = OnSurface,
            textAlign = TextAlign.Center,
        )
        Text(
            text = stringResource(R.string.favorite_empty_groups_desc),
            style = MaterialTheme.typography.bodyMedium,
            color = OnSurfaceVariant,
            textAlign = TextAlign.Center,
        )
        InaPrimaryButton(
            text = stringResource(R.string.favorite_create_collection),
            onClick = onCreateClick,
            modifier = Modifier.fillMaxWidth(),
        )
        TextButton(onClick = onBrowseProducts) {
            Text(text = stringResource(R.string.profile_favorites_browse_products), color = BrandRed)
        }
    }
}

@Composable
private fun LoadingState() {
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .height(220.dp)
            .clip(RoundedCornerShape(24.dp))
            .background(SurfaceContainerLowest),
        contentAlignment = Alignment.Center,
    ) {
        CircularProgressIndicator(color = BrandRed)
    }
}

@Composable
private fun FavoriteNameDialog(
    title: String,
    confirmLabel: String,
    initialValue: String,
    isSubmitting: Boolean,
    onDismiss: () -> Unit,
    onConfirm: (String) -> Unit,
) {
    var value by remember(initialValue) { mutableStateOf(initialValue) }

    AlertDialog(
        onDismissRequest = {
            if (!isSubmitting) onDismiss()
        },
        title = { Text(title, fontFamily = ManropeFontFamily, fontWeight = FontWeight.Bold) },
        text = {
            InaTextField(
                value = value,
                onValueChange = { value = it },
                placeholder = stringResource(R.string.favorite_name_placeholder),
            )
        },
        confirmButton = {
            TextButton(
                enabled = value.trim().isNotEmpty() && !isSubmitting,
                onClick = { onConfirm(value.trim()) },
            ) {
                Text(confirmLabel)
            }
        },
        dismissButton = {
            TextButton(
                enabled = !isSubmitting,
                onClick = onDismiss,
            ) {
                Text(stringResource(R.string.dialog_cancel))
            }
        },
    )
}

@Composable
private fun DeleteFavoriteDialog(
    name: String,
    isSubmitting: Boolean,
    onDismiss: () -> Unit,
    onConfirm: () -> Unit,
) {
    AlertDialog(
        onDismissRequest = {
            if (!isSubmitting) onDismiss()
        },
        title = { Text(stringResource(R.string.favorite_delete_action), fontFamily = ManropeFontFamily, fontWeight = FontWeight.Bold) },
        text = {
            Text(stringResource(R.string.favorite_delete_confirmation, name))
        },
        confirmButton = {
            TextButton(
                enabled = !isSubmitting,
                onClick = onConfirm,
            ) {
                Text(stringResource(R.string.favorite_delete_action), color = BrandRed)
            }
        },
        dismissButton = {
            TextButton(
                enabled = !isSubmitting,
                onClick = onDismiss,
            ) {
                Text(stringResource(R.string.dialog_cancel))
            }
        },
    )
}

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

private data class FavoriteAccent(
    val icon: ImageVector,
    val tint: Color,
    val container: Color,
)

private fun accentFor(index: Int): FavoriteAccent = when (index % 3) {
    0 -> FavoriteAccent(
        icon = Icons.Outlined.HomeWork,
        tint = BrandRed,
        container = BrandRedLight.copy(alpha = 0.18f),
    )
    1 -> FavoriteAccent(
        icon = Icons.Outlined.Restaurant,
        tint = AccentBlue,
        container = AccentBlueContainer.copy(alpha = 0.45f),
    )
    else -> FavoriteAccent(
        icon = Icons.Outlined.CardGiftcard,
        tint = AccentPurple,
        container = AccentPurpleContainer.copy(alpha = 0.45f),
    )
}
