@file:Suppress("HardCodedStringLiteral", "AssignedValueIsNeverRead")

package eu.gaudian.translator.view.vocabulary

import android.os.Parcelable
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.Crossfade
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.FlowRow
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.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.lazy.rememberLazyListState
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.FabPosition
import androidx.compose.material3.FilterChip
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
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.hilt.lifecycle.viewmodel.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavHostController
import eu.gaudian.translator.R
import eu.gaudian.translator.model.Language
import eu.gaudian.translator.model.VocabularyItem
import eu.gaudian.translator.model.VocabularyStage
import eu.gaudian.translator.ui.theme.ThemePreviews
import eu.gaudian.translator.utils.findActivity
import eu.gaudian.translator.view.composable.AppIcons
import eu.gaudian.translator.view.composable.AppScaffold
import eu.gaudian.translator.view.composable.AppSwitch
import eu.gaudian.translator.view.composable.AppTopAppBar
import eu.gaudian.translator.view.composable.MultipleLanguageDropdown
import eu.gaudian.translator.view.dialogs.CategoryDropdown
import eu.gaudian.translator.view.dialogs.CategorySelectionDialog
import eu.gaudian.translator.view.dialogs.StageSelectionDialog
import eu.gaudian.translator.view.library.AllCardsView
import eu.gaudian.translator.viewmodel.CategoryViewModel
import eu.gaudian.translator.viewmodel.LanguageConfigViewModel
import eu.gaudian.translator.viewmodel.LanguageViewModel
import eu.gaudian.translator.viewmodel.VocabularyViewModel
import eu.gaudian.translator.viewmodel.VocabularyViewModel.SortOrder
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.launch
import kotlinx.parcelize.Parcelize


@Parcelize
private data class VocabularyFilterState(
    val searchQuery: String = "",
    val selectedStage: VocabularyStage? = null,
    val sortOrder: SortOrder = SortOrder.NEWEST_FIRST,
    val categoryIds: List<Int> = emptyList(),
    val dueTodayOnly: Boolean = false,
    val selectedLanguageIds: List<Int> = emptyList(),
    val selectedWordClass: String? = null
) : Parcelable

@Composable
fun AllCardsListScreen(
    categoryId: Int? = null,
    showDueTodayOnly: Boolean? = null,
    stage: VocabularyStage? = null,
    onNavigateToItem: (VocabularyItem) -> Unit?,
    onNavigateBack: (() -> Unit)? = null,
    navController: NavHostController? = null,
    itemsToShow: List<VocabularyItem> = emptyList(),
    isRemoveFromCategoryEnabled: Boolean = false,
    showTopBar: Boolean = true,
    enableNavigationButtons: Boolean = false
) {
    val scope = rememberCoroutineScope()
    val activity = LocalContext.current.findActivity()
    val lazyListState = rememberLazyListState()
    val vocabularyViewModel: VocabularyViewModel = hiltViewModel(viewModelStoreOwner = activity)
    val languageViewModel: LanguageViewModel = hiltViewModel(viewModelStoreOwner = activity)
    val categoryViewModel: CategoryViewModel = hiltViewModel(viewModelStoreOwner = activity)
    val context = LocalContext.current

    var filterState by rememberSaveable {
        mutableStateOf(
            VocabularyFilterState(
                categoryIds = categoryId?.let { listOf(it) } ?: emptyList(),
                dueTodayOnly = showDueTodayOnly == true,
                selectedStage = stage
            )
        )
    }
    val isFilterActive by remember(filterState) {
        derivedStateOf {
            filterState.selectedStage != null ||
                    filterState.categoryIds.isNotEmpty() ||
                    filterState.dueTodayOnly ||
                    filterState.selectedLanguageIds.isNotEmpty() ||
                    !filterState.selectedWordClass.isNullOrBlank()
        }
    }
    var showFilterSheet by remember { mutableStateOf(false) }

    var selection by remember { mutableStateOf<Set<Long>>(emptySet()) }
    val isInSelectionMode = selection.isNotEmpty()

    var showCategoryDialog by remember { mutableStateOf(false) }
    var showStageDialog by remember { mutableStateOf(false) }
    var isSearchActive by rememberSaveable { mutableStateOf(false) }

    val allLanguages by languageViewModel.allLanguages.collectAsStateWithLifecycle(initialValue = emptyList())
    val languagesPresent by vocabularyViewModel.languagesPresent.collectAsStateWithLifecycle(initialValue = emptySet())
    val categoryNameFlow = remember(categoryId) { categoryId?.let { categoryViewModel.getCategoryById(it) } }

    val vocabularyItemsFlow: Flow<List<VocabularyItem>> = remember(filterState) {
        vocabularyViewModel.filterVocabularyItems(
            languages = filterState.selectedLanguageIds,
            query = filterState.searchQuery.takeIf { it.isNotBlank() },
            categoryIds = filterState.categoryIds,
            stage = filterState.selectedStage,
            wordClass = filterState.selectedWordClass,
            dueTodayOnly = filterState.dueTodayOnly,
            sortOrder = filterState.sortOrder
        )
    }

    val vocabularyItems: List<VocabularyItem> = itemsToShow.ifEmpty {
        vocabularyItemsFlow.collectAsStateWithLifecycle(initialValue = emptyList()).value
    }

    LaunchedEffect(categoryId, showDueTodayOnly, stage) {
        filterState = filterState.copy(
            categoryIds = categoryId?.let { listOf(it) } ?: emptyList(),
            dueTodayOnly = showDueTodayOnly == true,
            selectedStage = stage
        )
    }

    // Set navigation context when navigation buttons are enabled
    LaunchedEffect(vocabularyItems, enableNavigationButtons) {
        if (enableNavigationButtons && vocabularyItems.isNotEmpty()) {
            // Set the first item as the current navigation context
            vocabularyViewModel.setNavigationContext(vocabularyItems, vocabularyItems.first().id)
        }
    }


    val allItemsSelected = remember(vocabularyItems, selection) {
        vocabularyItems.isNotEmpty() && selection.size == vocabularyItems.size
    }


    AppScaffold(
        modifier = Modifier
            .padding(0.dp)
            .background(Color.Magenta),
        topBar = {
            val topBarMode = when {
                isInSelectionMode -> "selection"
                isSearchActive -> "search"
                showTopBar -> "default"
                else -> "none"
            }
            Crossfade(
                modifier = Modifier.padding(0.dp),
                targetState = topBarMode,
                label = "top-bar-anim"
            ) { state ->
                when (state) {
                    "selection" -> ContextualTopAppBar(
                        modifier = Modifier.padding(0.dp),
                        selectionCount = selection.size,
                        allItemsSelected = allItemsSelected,
                        isRemoveEnabled = isRemoveFromCategoryEnabled,
                        onSelectAllClick = {
                            selection = if (allItemsSelected) {
                                emptySet()
                            } else {
                                vocabularyItems.map { it.id.toLong() }.toSet()
                            }
                        },
                        onCloseClick = { selection = emptySet() },
                        onDeleteClick = {
                            vocabularyViewModel.deleteVocabularyItemsById(selection.map { it.toInt() })
                            selection = emptySet()
                        },
                        onMoveToCategoryClick = { showCategoryDialog = true },
                        onMoveToStageClick = { showStageDialog = true },
                        onRemoveFromCategoryClick = {
                            if (categoryId != null) {
                                val itemsToRemove = vocabularyItems.filter { selection.contains(it.id.toLong()) }
                                vocabularyViewModel.removeVocabularyItemsFromCategory(itemsToRemove, categoryId)
                                selection = emptySet()
                            }
                        }
                    )

                    "search" -> SearchTopAppBar(
                        onCloseSearch = {
                            isSearchActive = false
                            filterState = filterState.copy(searchQuery = "")
                        }
                    )

                    "default" -> DefaultTopAppBar(
                        title = when {
                            filterState.searchQuery.isNotBlank() -> "Results for: \"${filterState.searchQuery}\"" // Consider using a string resource

                            stage != null -> stringResource(R.string.text_stage_2d, stage.toString(context))
                            categoryId != null && categoryId != 0 -> stringResource(R.string.label_category_2d,
                                categoryNameFlow?.collectAsStateWithLifecycle(initialValue = null)?.value?.name
                                    ?: ""
                            )
                            showDueTodayOnly == true -> stringResource(R.string.text_due_today)
                            else -> stringResource(R.string.label_all_vocabulary)
                        },
                        currentSortOrder = filterState.sortOrder,
                        isFilterActive = isFilterActive,
                        onSortOrderChanged = { newOrder ->
                            filterState = filterState.copy(sortOrder = newOrder)
                        },
                        onFilterClick = { showFilterSheet = true },
                        onSearchClick = { isSearchActive = true },
                        onNavigateBack = onNavigateBack
                    )
                }
            }
        },
        floatingActionButton = {
            val showFab by remember { derivedStateOf { lazyListState.firstVisibleItemIndex > 5 && !isInSelectionMode } }
            AnimatedVisibility(visible = showFab) {
                FloatingActionButton(
                    onClick = { scope.launch { lazyListState.animateScrollToItem(0) } },
                    shape = CircleShape,
                    modifier = Modifier.size(50.dp),
                    containerColor = MaterialTheme.colorScheme.surfaceVariant
                ) {
                    Icon(AppIcons.ArrowCircleUp, contentDescription = "Scroll to top")
                }
            }
        },
        floatingActionButtonPosition = FabPosition.Center
    ) { paddingValues ->
        Column(modifier = Modifier.padding(paddingValues).padding(bottom = 0.dp)) {
            AllCardsView(
                vocabularyItems = vocabularyItems,
                allLanguages = allLanguages,
                selection = selection,
                listState = lazyListState,
                modifier = Modifier
                    .fillMaxSize()
                    .padding(horizontal = 8.dp),
                onItemClick = { item ->
                    val isSelected = selection.contains(item.id.toLong())
                    if (isInSelectionMode) {
                        selection = if (isSelected) {
                            selection - item.id.toLong()
                        } else {
                            selection + item.id.toLong()
                        }
                    } else {
                        if (navController != null && enableNavigationButtons) {
                            vocabularyViewModel.setNavigationContext(vocabularyItems, item.id)
                            navController.navigate("vocabulary_detail/${item.id}")
                        } else {
                            onNavigateToItem(item)
                        }
                    }
                },
                onItemLongClick = { item ->
                    if (!isInSelectionMode) {
                        selection = setOf(item.id.toLong())
                    }
                },
                onDeleteClick = { item ->
                    vocabularyViewModel.deleteData(VocabularyViewModel.DeleteType.VOCABULARY_ITEM, item = item)
                }
            )
        }


        if (showFilterSheet) {
            FilterSortBottomSheet(
                currentFilterState = filterState,
                onDismiss = { showFilterSheet = false },
                        onApplyFilters = { newState ->
                    filterState = newState
                    showFilterSheet = false
                    scope.launch { lazyListState.scrollToItem(0) }
                },
                languageViewModel = languageViewModel,
                languagesPresent = allLanguages.filter { it.nameResId in languagesPresent },
                hideCategory = categoryId != null && categoryId != 0,
                hideStage = stage != null
            )
        }

        if (showCategoryDialog) {
            val selectedItems = vocabularyItems.filter { selection.contains(it.id.toLong()) }
            CategorySelectionDialog(
                onCategorySelected = {
                    vocabularyViewModel.addVocabularyItemToCategories(
                        selectedItems,
                        it.mapNotNull { category -> category?.id }
                    )
                    //showCategoryDialog = false
                },
                onDismissRequest = { showCategoryDialog = false }
            )
        }

        if (showStageDialog) {
            val selectedItems = vocabularyItems.filter { selection.contains(it.id.toLong()) }
            StageSelectionDialog(
                onStageSelected = { selectedStage ->
                    selectedStage?.let {
                        vocabularyViewModel.addVocabularyItemToStage(selectedItems, it)
                    }
                    showStageDialog = false
                    selection = emptySet()
                },
                onDismissRequest = { showStageDialog = false }
            )
        }
    }
}

@Deprecated("Use AllCardsListScreen which renders AllCardsView")
@Composable
fun VocabularyListScreen(
    categoryId: Int? = null,
    showDueTodayOnly: Boolean? = null,
    stage: VocabularyStage? = null,
    onNavigateToItem: (VocabularyItem) -> Unit?,
    onNavigateBack: (() -> Unit)? = null,
    navController: NavHostController? = null,
    itemsToShow: List<VocabularyItem> = emptyList(),
    isRemoveFromCategoryEnabled: Boolean = false,
    showTopBar: Boolean = true,
    enableNavigationButtons: Boolean = false
) {
    AllCardsListScreen(
        categoryId = categoryId,
        showDueTodayOnly = showDueTodayOnly,
        stage = stage,
        onNavigateToItem = onNavigateToItem,
        onNavigateBack = onNavigateBack,
        navController = navController,
        itemsToShow = itemsToShow,
        isRemoveFromCategoryEnabled = isRemoveFromCategoryEnabled,
        showTopBar = showTopBar,
        enableNavigationButtons = enableNavigationButtons
    )
}

@Composable
private fun DefaultTopAppBar(
    title: String,
    onFilterClick: () -> Unit,
    onNavigateBack: (() -> Unit)?,
    currentSortOrder: SortOrder,
    isFilterActive: Boolean, // <-- Add new parameter
    onSortOrderChanged: (SortOrder) -> Unit,
    onSearchClick: () -> Unit
) {

    var showSortMenu by remember { mutableStateOf(false) }
    AppTopAppBar(
        modifier = Modifier.height(56.dp),
        title = title,
        onNavigateBack = onNavigateBack,
        actions = {
            IconButton(onClick = onSearchClick) {
                Icon(
                    imageVector = AppIcons.Search,
                    contentDescription = stringResource(R.string.cd_search))
            }

            Box {
                IconButton(onClick = { showSortMenu = true }) {
                    Icon(
                        imageVector = AppIcons.Sort,
                        contentDescription = stringResource(R.string.sort)
                    )
                }
                DropdownMenu(
                    expanded = showSortMenu,
                    onDismissRequest = { showSortMenu = false }
                ) {
                    SortOrder.entries.forEach { order ->
                        DropdownMenuItem(
                            text = { Text(order.name.replace('_', ' ').lowercase().replaceFirstChar { it.titlecase() }) },
                            onClick = {
                                onSortOrderChanged(order)
                                showSortMenu = false
                            },
                            leadingIcon = {
                                if (currentSortOrder == order) {
                                    Icon(
                                        imageVector = AppIcons.Check,
                                        contentDescription = stringResource(R.string.text_selected)
                                    )
                                }
                            }
                        )
                    }
                }
            }
            IconButton(onClick = onFilterClick) {
                Icon(
                    imageVector = if (isFilterActive) {
                        AppIcons.FilterFilled
                    } else {
                        AppIcons.FilterOutlined
                    },
                    contentDescription = stringResource(R.string.filter_and_sort),
                    tint = if (isFilterActive) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurface
                )
            }
        }

    )
}



@Composable
private fun SearchTopAppBar(
    onCloseSearch: () -> Unit
) {
    val focusRequester = remember { FocusRequester() }

    LaunchedEffect(Unit) {
        focusRequester.requestFocus()
    }

    AppTopAppBar(
        modifier = Modifier.height(56.dp),
        title = "TODO",
        navigationIcon = {
            IconButton(onClick = onCloseSearch) {
                Icon(
                    imageVector = AppIcons.Close,
                    contentDescription = stringResource(R.string.label_close_search)
                )
            }
        },
        actions = {
        }
    )
}

@ThemePreviews
@Composable
fun SearchTopAppBarPreview() {
    SearchTopAppBar(
        onCloseSearch = {}
    )
}

@Composable
private fun ContextualTopAppBar(
    modifier: Modifier = Modifier,
    selectionCount: Int,
    allItemsSelected: Boolean,
    isRemoveEnabled: Boolean,
    onCloseClick: () -> Unit,
    onSelectAllClick: () -> Unit,
    onDeleteClick: () -> Unit,
    onMoveToCategoryClick: () -> Unit,
    onMoveToStageClick: () -> Unit,
    onRemoveFromCategoryClick: () -> Unit
) {
    var showOverflowMenu by remember { mutableStateOf(false) }

    AppTopAppBar(
        modifier = modifier.height(56.dp),
        title = stringResource(R.string.d_selected, selectionCount),
        navigationIcon = {
            IconButton(onClick = onCloseClick) {
                Icon(imageVector = AppIcons.Close, contentDescription = stringResource(R.string.label_close_selection_mode))
            }
        },
        actions = {
            IconButton(onClick = onSelectAllClick) {
                Icon(
                    imageVector = AppIcons.SelectAll,
                    contentDescription = if (allItemsSelected) stringResource(R.string.deselect_all) else stringResource(R.string.select_all)
                )
            }

            IconButton(onClick = onDeleteClick) {
                Icon(AppIcons.Delete, contentDescription = stringResource(R.string.label_delete))
            }

            Box {
                IconButton(onClick = { showOverflowMenu = true }) {
                    Icon(imageVector = AppIcons.More, contentDescription = stringResource(R.string.more_actions))
                }
                DropdownMenu(
                    expanded = showOverflowMenu,
                    onDismissRequest = { showOverflowMenu = false }
                ) {
                    DropdownMenuItem(
                        text = { Text(stringResource(R.string.move_to_category)) },
                        onClick = {
                            onMoveToCategoryClick()
                            showOverflowMenu = false
                        },
                        leadingIcon = { Icon(AppIcons.Category, contentDescription = null) }
                    )
                    if (isRemoveEnabled) {
                        DropdownMenuItem(
                            text = { Text(stringResource(R.string.remove_from_category)) },
                            onClick = {
                                onRemoveFromCategoryClick()
                                showOverflowMenu = false
                            },
                            leadingIcon = { Icon(AppIcons.Remove, contentDescription = null) }
                        )
                    }
                    DropdownMenuItem(
                        text = { Text(stringResource(R.string.move_to_stage)) },
                        onClick = {
                            onMoveToStageClick()
                            showOverflowMenu = false
                        },
                        leadingIcon = { Icon(AppIcons.Stages, contentDescription = null) }
                    )
                }
            }
        },
        colors = TopAppBarDefaults.topAppBarColors(
            containerColor = MaterialTheme.colorScheme.primaryContainer,
            titleContentColor = MaterialTheme.colorScheme.onPrimaryContainer,
            actionIconContentColor = MaterialTheme.colorScheme.onPrimaryContainer,
            navigationIconContentColor = MaterialTheme.colorScheme.onPrimaryContainer
        )
    )
}


@ThemePreviews
@Composable
fun ContextualTopAppBarPreview() {
    ContextualTopAppBar(
        selectionCount = 5,
        allItemsSelected = false,
        isRemoveEnabled = true,
        onCloseClick = {},
        onSelectAllClick = {},
        onDeleteClick = {},
        onMoveToCategoryClick = {},
        onMoveToStageClick = {},
        onRemoveFromCategoryClick = {}
    )
}


@Composable
private fun FilterSortBottomSheet(
    currentFilterState: VocabularyFilterState,
    languageViewModel: LanguageViewModel,
    languagesPresent: List<Language>,
    onDismiss: () -> Unit,
    onApplyFilters: (VocabularyFilterState) -> Unit,
    hideCategory: Boolean = false,
    hideStage: Boolean = false
) {
    var selectedStage by rememberSaveable { mutableStateOf(currentFilterState.selectedStage) }
    var dueTodayOnly by rememberSaveable { mutableStateOf(currentFilterState.dueTodayOnly) }
    var selectedCategoryIds by rememberSaveable { mutableStateOf(currentFilterState.categoryIds) }
    var selectedLanguageIds by rememberSaveable { mutableStateOf(currentFilterState.selectedLanguageIds) }
    var selectedWordClass by rememberSaveable { mutableStateOf(currentFilterState.selectedWordClass) }

    val context = LocalContext.current
    val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
    val activity = LocalContext.current.findActivity()

    val languageConfigViewModel: LanguageConfigViewModel = hiltViewModel(activity)
    val allWordClasses by languageConfigViewModel.allWordClasses.collectAsStateWithLifecycle()

    ModalBottomSheet(
        onDismissRequest = onDismiss,
        sheetState = sheetState
    ) {
        Column(
            modifier = Modifier
                .padding(horizontal = 16.dp)
                .navigationBarsPadding()
        ) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                verticalAlignment = Alignment.CenterVertically,
            ) {
                Text(stringResource(R.string.text_filter), style = MaterialTheme.typography.titleLarge)
                Spacer(Modifier.weight(1f))
                TextButton(onClick = {
                    if (!hideStage) selectedStage = null
                    dueTodayOnly = false
                    if (!hideCategory) selectedCategoryIds = emptyList()
                    selectedLanguageIds = emptyList()
                    selectedWordClass = null
                }) {
                    Text(stringResource(R.string.label_clear_all), color = MaterialTheme.colorScheme.error)
                }
                Spacer(Modifier.width(8.dp))
                TextButton(
                    onClick = {
                        onApplyFilters(
                            currentFilterState.copy(
                                selectedStage = selectedStage,
                                dueTodayOnly = dueTodayOnly,
                                categoryIds = selectedCategoryIds,
                                selectedLanguageIds = selectedLanguageIds,
                                selectedWordClass = selectedWordClass
                            )
                        )
                    }
                ) {
                    Text(stringResource(R.string.label_apply_filters), fontWeight = FontWeight.Bold)
                }
            }
            HorizontalDivider(modifier = Modifier.padding(vertical = 8.dp))

            Column(modifier = Modifier.verticalScroll(rememberScrollState())) {
                Spacer(Modifier.height(16.dp))

                Row(
                    modifier = Modifier.fillMaxWidth(),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(stringResource(R.string.text_due_today_only), style = MaterialTheme.typography.bodyMedium)
                    Spacer(Modifier.width(8.dp))
                    AppSwitch(checked = dueTodayOnly, onCheckedChange = { dueTodayOnly = it })
                }
                Spacer(Modifier.height(16.dp))

                Text(stringResource(R.string.language), style = MaterialTheme.typography.titleMedium)
                Spacer(Modifier.height(8.dp))
                MultipleLanguageDropdown(
                    languageViewModel = languageViewModel,
                    onLanguagesSelected = { languages ->
                        selectedLanguageIds = languages.map { it.nameResId }
                    },
                    alternateLanguages = languagesPresent
                )
                Spacer(Modifier.height(16.dp))

                if (!hideCategory) {
                    Text(stringResource(R.string.label_category), style = MaterialTheme.typography.titleMedium)
                    Spacer(Modifier.height(8.dp))
                    CategoryDropdown(
                        initialCategoryId = selectedCategoryIds.firstOrNull(),
                        onCategorySelected = { categories ->
                            selectedCategoryIds = categories.mapNotNull { it?.id }
                        },
                        multipleSelectable = true,
                        noneSelectable = false
                    )
                    Spacer(Modifier.height(16.dp))
                }

                if (!hideStage) {
                    Text(stringResource(R.string.label_filter_by_stage), style = MaterialTheme.typography.titleMedium)
                    FlowRow(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.spacedBy(8.dp)
                    ) {
                        FilterChip(
                            selected = selectedStage == null,
                            onClick = { selectedStage = null },
                            label = { Text(stringResource(R.string.label_all_stages)) }
                        )
                        VocabularyStage.entries.forEach { stage ->
                            FilterChip(
                                selected = selectedStage == stage,
                                onClick = { selectedStage = stage },
                                label = { Text(stage.toString(context)) }
                            )
                        }
                    }
                }

                if (allWordClasses.isNotEmpty()) {
                    Spacer(Modifier.height(16.dp))
                    Text(stringResource(R.string.filter_by_word_type), style = MaterialTheme.typography.titleMedium)
                    FlowRow(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.spacedBy(8.dp)
                    ) {
                        FilterChip(
                            selected = selectedWordClass == null,
                            onClick = { selectedWordClass = null },
                            label = { Text(stringResource(R.string.label_all_types)) }
                        )
                        allWordClasses.forEach { wordClass ->
                            FilterChip(
                                selected = selectedWordClass == wordClass,
                                onClick = { selectedWordClass = wordClass },
                                label = { Text(wordClass.replaceFirstChar { it.titlecase() }) }
                            )
                        }
                    }
                }
                // Add padding at the bottom for better scrolling experience
                Spacer(Modifier.height(16.dp))
            }
        }
    }
}

