@file:Suppress("AssignedValueIsNeverRead")

package eu.gaudian.translator.view.vocabulary

import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeOut
import androidx.compose.animation.slideOutHorizontally
import androidx.compose.foundation.BorderStroke
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.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
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.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.DividerDefaults
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.FilterChipDefaults
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.SuggestionChip
import androidx.compose.material3.SuggestionChipDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
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.rememberCoroutineScope
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.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import androidx.navigation.NavHostController
import eu.gaudian.translator.R
import eu.gaudian.translator.model.Language
import eu.gaudian.translator.model.TagCategory
import eu.gaudian.translator.model.VocabularyItem
import eu.gaudian.translator.model.VocabularyStage
import eu.gaudian.translator.utils.StringHelper
import eu.gaudian.translator.utils.findActivity
import eu.gaudian.translator.view.composable.AppButton
import eu.gaudian.translator.view.composable.AppCard
import eu.gaudian.translator.view.composable.AppDialog
import eu.gaudian.translator.view.composable.AppIcons
import eu.gaudian.translator.view.composable.AppOutlinedTextField
import eu.gaudian.translator.view.composable.AppScaffold
import eu.gaudian.translator.view.composable.AppTopAppBar
import eu.gaudian.translator.view.composable.SingleLanguageDropDown
import eu.gaudian.translator.view.dialogs.CategoryDropdown
import eu.gaudian.translator.view.dialogs.CreateCategoryListDialog
import eu.gaudian.translator.view.hints.HintDefinition
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 kotlinx.coroutines.delay
import kotlinx.coroutines.launch

enum class FilterMode {
    NEW, DUPLICATES, FAULTY
}

@Composable
fun VocabularySortingScreen(
    navController: NavHostController,
    initialFilterMode: String? = null
) {
    val activity = LocalContext.current.findActivity()
    val vocabularyViewModel: VocabularyViewModel = hiltViewModel(viewModelStoreOwner = activity)
    val categoryViewModel: CategoryViewModel = hiltViewModel(viewModelStoreOwner = activity)


    var sortOrder by remember { mutableStateOf(VocabularyViewModel.SortOrder.NEWEST_FIRST) }
    val allDuplicateItems by vocabularyViewModel.allDuplicateItems.collectAsState()
    val allFaultyItems by vocabularyViewModel.allFaultyItems.collectAsState()
    val startingMode = remember {
        try {
            initialFilterMode?.let { FilterMode.valueOf(it.uppercase()) }
        } catch (_: IllegalArgumentException) {
            FilterMode.NEW
        }
    }
    var filterMode by remember { mutableStateOf(startingMode) }

    LaunchedEffect(filterMode, allDuplicateItems, allFaultyItems) {
        when (filterMode) {
            FilterMode.DUPLICATES -> vocabularyViewModel.filterByIds(allDuplicateItems.map { it.id })
            FilterMode.FAULTY -> vocabularyViewModel.filterByIds(allFaultyItems.map { it.id })
            else -> vocabularyViewModel.clearFilter() // For NEW or null mode
        }
    }

    DisposableEffect(Unit) {
        onDispose {
            vocabularyViewModel.clearFilter()
        }
    }

    val itemsToDisplay
    by vocabularyViewModel.filterVocabularyItems(
        languages = null,
        query = null,
        categoryIds = null,
        stage = if (filterMode == FilterMode.NEW) VocabularyStage.NEW else null, // Only filter by NEW stage in that mode
        sortOrder = sortOrder,
    ).collectAsState(initial = emptyList())

    var showCreateCategoryDialog by remember { mutableStateOf(false) }

    if (showCreateCategoryDialog) {
        CreateCategoryListDialog(
            onDismiss = { showCreateCategoryDialog = false },
            onConfirm = { categoryName ->
                categoryViewModel.createCategory(
                    TagCategory(
                        id = 0,
                        name = categoryName
                    )
                )
                showCreateCategoryDialog = false
            }
        )
    }

    AppScaffold(
        modifier = Modifier.fillMaxSize(),
        topBar = {
            var showSortMenu by remember { mutableStateOf(false) }
            var showFilterMenu by remember { mutableStateOf(false) }

            AppTopAppBar(
                title = stringResource(R.string.sort_new_vocabulary),
                actions = {
                    Box {
                        IconButton(onClick = { showFilterMenu = true }) {
                            Icon(
                                imageVector = AppIcons.Filter,
                                contentDescription = stringResource(R.string.text_filter)
                            )
                        }
                        DropdownMenu(
                            expanded = showFilterMenu,
                            onDismissRequest = { showFilterMenu = false }
                        ) {
                            DropdownMenuItem(
                                text = { Text(stringResource(R.string.new_items_only)) },
                                onClick = {
                                    filterMode = if (filterMode == FilterMode.NEW) null else FilterMode.NEW
                                    showFilterMenu = false
                                },
                                trailingIcon = { if (filterMode == FilterMode.NEW) Icon(AppIcons.Check, stringResource(R.string.enabled)) }
                            )
                            DropdownMenuItem(
                                text = { Text(stringResource(R.string.duplicates_only)) },
                                onClick = {
                                    filterMode = if (filterMode == FilterMode.DUPLICATES) null else FilterMode.DUPLICATES
                                    showFilterMenu = false
                                },
                                trailingIcon = { if (filterMode == FilterMode.DUPLICATES) Icon(AppIcons.Check, stringResource(R.string.enabled)) }
                            )
                            DropdownMenuItem(
                                text = { Text(stringResource(R.string.faulty_items_only)) },
                                onClick = {
                                    filterMode = if (filterMode == FilterMode.FAULTY) null else FilterMode.FAULTY
                                    showFilterMenu = false
                                },
                                trailingIcon = { if (filterMode == FilterMode.FAULTY) Icon(AppIcons.Check, stringResource(R.string.enabled)) }
                            )
                        }
                    }

                    // Sort Button and Menu
                    Box {
                        IconButton(onClick = { showSortMenu = true }) {
                            Icon(
                                imageVector = AppIcons.Sort,
                                contentDescription = stringResource(R.string.sort)
                            )
                        }
                        DropdownMenu(
                            expanded = showSortMenu,
                            onDismissRequest = { showSortMenu = false }
                        ) {
                            DropdownMenuItem(
                                text = { Text(stringResource(R.string.newest_first)) },
                                onClick = {
                                    sortOrder = VocabularyViewModel.SortOrder.NEWEST_FIRST
                                    showSortMenu = false
                                }
                            )
                            DropdownMenuItem(
                                text = { Text(stringResource(R.string.oldest_first)) },
                                onClick = {
                                    sortOrder = VocabularyViewModel.SortOrder.OLDEST_FIRST
                                    showSortMenu = false
                                }
                            )
                            DropdownMenuItem(
                                text = { Text(stringResource(R.string.label_by_language)) },
                                onClick = {
                                    sortOrder = VocabularyViewModel.SortOrder.LANGUAGE
                                    showSortMenu = false
                                }
                            )
                        }
                    }
                },
                onNavigateBack = { navController.popBackStack() },
                hintContent = HintDefinition.SORTING.hint()
            )
        },

    ) { paddingValues ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
        ) {
            if (itemsToDisplay.isEmpty()) {
                Text(
                    text = stringResource(R.string.no_new_vocabulary_to_sort),
                    style = MaterialTheme.typography.bodyLarge,
                    modifier = Modifier
                        .align(Alignment.CenterHorizontally)
                        .padding(16.dp)
                )
            } else {
                LazyColumn(
                    modifier = Modifier.weight(1f),
                    verticalArrangement = Arrangement.spacedBy(8.dp),
                    contentPadding = paddingValues
                ) {
                    items(itemsToDisplay, key = { it.id }) { item ->
                        VocabularySortingItem(
                            item = item,
                            filterMode = filterMode, // NEW: Pass the mode to the item
                            vocabularyViewModel = vocabularyViewModel
                        )
                    }
                }
                AppButton(
                    onClick = { showCreateCategoryDialog = true },
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(16.dp)
                ) {
                    Text(stringResource(R.string.create_new_category))
                }
            }
        }
    }
}

@Preview
@Composable
fun VocabularySortingScreenPreview() {
    VocabularySortingScreen(
        navController = NavHostController(LocalContext.current),
        initialFilterMode = "NEW"
    )
}

@Composable
fun VocabularySortingItem(
    item: VocabularyItem,
    filterMode: FilterMode?,
    vocabularyViewModel: VocabularyViewModel
) {
    val activity = LocalContext.current.findActivity()
    val languageConfigViewModel: LanguageConfigViewModel = hiltViewModel(viewModelStoreOwner = activity)
    val languageViewModel: LanguageViewModel = hiltViewModel(viewModelStoreOwner = activity)
    var wordFirst by remember { mutableStateOf(item.wordFirst) }
    var wordSecond by remember { mutableStateOf(item.wordSecond) }
    var selectedCategories by remember { mutableStateOf<List<Int>>(emptyList()) }
    var langFirst by remember { mutableStateOf<Language?>(null) }
    var langSecond by remember { mutableStateOf<Language?>(null) }
    val isDuplicate by vocabularyViewModel.isDuplicateFlow(item.id).collectAsState(initial = false)
    val duplicates by vocabularyViewModel.getDuplicatesOf(item).collectAsState(initial = emptyList())
    var visible by remember { mutableStateOf(true) }
    val scope = rememberCoroutineScope()

    var articlesLangFirst by remember { mutableStateOf(emptySet<String>()) }
    var articlesLangSecond by remember { mutableStateOf(emptySet<String>()) }

    var showDuplicateDialog by remember { mutableStateOf(false) }

    // NEW: Calculate if the item is valid for the "Done" button in faulty mode
    val isItemNowValid by remember(wordFirst, wordSecond, langFirst, langSecond) {
        mutableStateOf(
            wordFirst.isNotBlank() &&
                    wordSecond.isNotBlank() &&
                    langFirst != null &&
                    langSecond != null &&
                    langFirst?.nameResId != langSecond?.nameResId &&
                    langFirst?.nameResId != 0 &&
                    langSecond?.nameResId != 0
        )
    }

    if (showDuplicateDialog && duplicates.isNotEmpty()) {
        EnhancedDuplicateDialog(
            newItem = item,
            existingItem = duplicates.first(),
            onDismiss = { showDuplicateDialog = false },
            onDelete = {
                scope.launch {
                    showDuplicateDialog = false
                    visible = false
                    delay(350)
                    vocabularyViewModel.deleteVocabularyItemsById(listOf(item.id))
                }
            },
            onMerge = {
                scope.launch {
                    showDuplicateDialog = false
                    visible = false
                    delay(350)
                    vocabularyViewModel.mergeDuplicateItems(item, duplicates.first())
                }
            }
        )
    }

    LaunchedEffect(item) {
        wordFirst = item.wordFirst
        wordSecond = item.wordSecond
    }

    LaunchedEffect(item.languageFirstId, item.languageSecondId) {
        langFirst = languageViewModel.getLanguageById(item.languageFirstId ?: 0)
        langSecond = languageViewModel.getLanguageById(item.languageSecondId ?: 0)
    }


    LaunchedEffect(langFirst, langSecond) {
        langFirst?.code?.let { code ->
            articlesLangFirst = languageConfigViewModel.getArticlesForLanguage(code)
        }
        langSecond?.code?.let { code ->
            articlesLangSecond = languageConfigViewModel.getArticlesForLanguage(code)
        }
    }

    val canRemoveArticles = remember(wordFirst, wordSecond, articlesLangFirst, articlesLangSecond) {
        val wordFirstHasArticle = articlesLangFirst.any { wordFirst.startsWith("$it ", ignoreCase = true) }
        val wordSecondHasArticle = articlesLangSecond.any { wordSecond.startsWith("$it ", ignoreCase = true) }

        val isAnyWordASentence = StringHelper.isSentenceStrict(wordFirst) || StringHelper.isSentenceStrict(wordSecond)

        (wordFirstHasArticle || wordSecondHasArticle) && !isAnyWordASentence
    }


    fun processAndHide(action: suspend () -> Unit) {
        scope.launch {
            visible = false
            delay(350)
            action()
        }
    }

    AnimatedVisibility(
        visible = visible,
        exit = slideOutHorizontally(
            targetOffsetX = { fullWidth -> fullWidth },
            animationSpec = tween(durationMillis = 300)
        ) + fadeOut(animationSpec = tween(durationMillis = 200))
    ) {
        AppCard(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 16.dp, vertical = 4.dp)
        ) {
            Column(
                modifier = Modifier.padding(16.dp),
                verticalArrangement = Arrangement.spacedBy(16.dp)
            ) {
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    if (isDuplicate) {
                        SuggestionChip(
                            onClick = {
                                if (duplicates.isNotEmpty()) {
                                    showDuplicateDialog = true
                                }
                            },
                            label = { Text(stringResource(R.string.duplicate)) },
                            icon = {
                                Icon(
                                    imageVector = AppIcons.Warning,
                                    contentDescription = stringResource(R.string.label_warning),
                                    modifier = Modifier.size(FilterChipDefaults.IconSize)
                                )
                            },
                            colors = SuggestionChipDefaults.suggestionChipColors(
                                containerColor = MaterialTheme.colorScheme.errorContainer,
                                labelColor = MaterialTheme.colorScheme.onErrorContainer,
                                iconContentColor = MaterialTheme.colorScheme.onErrorContainer
                            ),
                            border = BorderStroke(1.dp, MaterialTheme.colorScheme.error)
                        )
                    } else {
                        Spacer(modifier = Modifier.height(1.dp))
                    }

                    AnimatedVisibility(visible = canRemoveArticles) {
                        SuggestionChip(
                            onClick = {
                                vocabularyViewModel.removeArticles(item, articlesLangFirst, articlesLangSecond)
                            },
                            label = { Text(stringResource(R.string.label_remove_articles)) },
                            icon = {
                                Icon(
                                    imageVector = AppIcons.Clean,
                                    contentDescription = stringResource(R.string.label_remove_articles),
                                    modifier = Modifier.size(FilterChipDefaults.IconSize)
                                )
                            },
                            border = BorderStroke(1.dp, MaterialTheme.colorScheme.onSurface)
                        )
                    }
                }

                Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
                    AppOutlinedTextField(
                        value = wordFirst,
                        onValueChange = { wordFirst = it },
                        label = { Text(stringResource(R.string.label_word)) },
                        modifier = Modifier.fillMaxWidth()
                    )
                    SingleLanguageDropDown(
                        languageViewModel = languageViewModel,
                        selectedLanguage = langFirst,
                        onLanguageSelected = { langFirst = it }
                    )
                }

                Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
                    AppOutlinedTextField(
                        value = wordSecond,
                        onValueChange = { wordSecond = it },
                        label = { Text(stringResource(R.string.label_translation)) },
                        modifier = Modifier.fillMaxWidth()
                    )
                    SingleLanguageDropDown(
                        languageViewModel = languageViewModel,
                        selectedLanguage = langSecond,
                        onLanguageSelected = { langSecond = it }
                    )
                }

                CategoryDropdown(
                    onCategorySelected = { categories ->
                        selectedCategories = categories.mapNotNull { it?.id }
                    },
                    multipleSelectable = true,
                    onlyLists = true
                )


                HorizontalDivider(Modifier, DividerDefaults.Thickness, DividerDefaults.color)

                // UPDATED: Conditionally display action buttons based on the filter mode
                when (filterMode) {
                    FilterMode.FAULTY -> {
                        FaultyItemActions(
                            isDoneEnabled = isItemNowValid,
                            onDeleteClick = {
                                processAndHide {
                                    vocabularyViewModel.deleteVocabularyItemsById(listOf(item.id))
                                }
                            },
                            onDoneClick = {
                                processAndHide {
                                    val updatedItem = item.copy(
                                        wordFirst = wordFirst, wordSecond = wordSecond,
                                        languageFirstId = langFirst?.nameResId, languageSecondId = langSecond?.nameResId
                                    )
                                    vocabularyViewModel.editVocabularyItem(updatedItem)

                                    vocabularyViewModel.addVocabularyItemToStage(listOf(updatedItem), VocabularyStage.NEW)
                                }
                            }
                        )
                    }
                    else -> {
                        LabeledSegmentedIconButtons(
                            onDeleteClick = {
                                processAndHide {
                                    vocabularyViewModel.deleteVocabularyItemsById(listOf(item.id))
                                }
                            },
                            onLearnedClick = {
                                processAndHide {
                                    val updatedItem = item.copy(wordFirst = wordFirst, wordSecond = wordSecond, languageFirstId = langFirst?.nameResId, languageSecondId = langSecond?.nameResId)
                                    vocabularyViewModel.editVocabularyItem(updatedItem)
                                    selectedCategories.forEach { catId -> vocabularyViewModel.addVocabularyItemToCategory(listOf(updatedItem), catId) }
                                    vocabularyViewModel.addVocabularyItemToStage(listOf(updatedItem), VocabularyStage.LEARNED)
                                }
                            },
                            onDoneClick = {
                                processAndHide {
                                    val updatedItem = item.copy(wordFirst = wordFirst, wordSecond = wordSecond, languageFirstId = langFirst?.nameResId, languageSecondId = langSecond?.nameResId)
                                    vocabularyViewModel.editVocabularyItem(updatedItem)
                                    selectedCategories.forEach { catId -> vocabularyViewModel.addVocabularyItemToCategory(listOf(updatedItem), catId) }
                                    vocabularyViewModel.addVocabularyItemToStage(listOf(updatedItem), VocabularyStage.STAGE_1)
                                }
                            }
                        )
                    }
                }
            }
        }
    }
}

@Suppress("HardCodedStringLiteral")
@Preview
@Composable
fun VocabularySortingItemPreview() {
    val item = VocabularyItem(id = 1, wordFirst = "Hello", wordSecond = "Hola", languageFirstId = 1, languageSecondId = 2)
    VocabularySortingItem(
        item = item,
        filterMode = FilterMode.NEW,
        vocabularyViewModel = hiltViewModel()
    )
}

@Preview
@Composable
fun FaultyItemActionsPreview() {
    FaultyItemActions(isDoneEnabled = true, onDeleteClick = {}, onDoneClick = {})
}

@Composable
fun FaultyItemActions(
    isDoneEnabled: Boolean,
    onDeleteClick: () -> Unit,
    onDoneClick: () -> Unit
) {
    Column(
        modifier = Modifier.fillMaxWidth(),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        val buttonHeight = 48.dp
        val cornerRadius = 24.dp

        Row(
            modifier = Modifier
                .fillMaxWidth()
                .height(buttonHeight)
                .clip(RoundedCornerShape(cornerRadius)),
            verticalAlignment = Alignment.CenterVertically
        ) {
            // Delete Button
            AppButton(
                onClick = onDeleteClick,
                modifier = Modifier
                    .weight(1f)
                    .fillMaxHeight(),
                shape = RoundedCornerShape(0.dp),
                colors = ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.errorContainer)
            ) {
                Icon(AppIcons.Delete, contentDescription = stringResource(R.string.label_delete), tint = MaterialTheme.colorScheme.onErrorContainer)
            }

            AppButton(
                onClick = onDoneClick,
                enabled = isDoneEnabled, // Button is enabled only when the item is valid
                modifier = Modifier
                    .weight(2f)
                    .fillMaxHeight(),
                shape = RoundedCornerShape(0.dp),
                colors = ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.primary)
            ) {
                Icon(AppIcons.Check, contentDescription = stringResource(R.string.label_done), tint = MaterialTheme.colorScheme.onPrimary)
            }
        }

        Spacer(Modifier.height(4.dp))

        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 8.dp)
        ) {
            Text(stringResource(R.string.label_delete), Modifier.weight(1f), textAlign = TextAlign.Center, fontSize = 12.sp, color = MaterialTheme.colorScheme.error)
            Text(stringResource(R.string.label_done), Modifier.weight(2f), textAlign = TextAlign.Center, fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurface)
        }
    }
}

@Preview
@Composable
fun LabeledSegmentedIconButtonsPreview() {
    LabeledSegmentedIconButtons(onDeleteClick = {}, onLearnedClick = {}, onDoneClick = {})
}
@Composable
fun LabeledSegmentedIconButtons(
    onDeleteClick: () -> Unit,
    onLearnedClick: () -> Unit,
    onDoneClick: () -> Unit
) {
    Column(
        modifier = Modifier.fillMaxWidth(),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        val buttonHeight = 48.dp
        val cornerRadius = 24.dp
        val secondaryButtonColor = MaterialTheme.colorScheme.surfaceVariant

        Row(
            modifier = Modifier
                .fillMaxWidth()
                .height(buttonHeight)
                .clip(RoundedCornerShape(cornerRadius)),
            verticalAlignment = Alignment.CenterVertically
        ) {
            AppButton(
                onClick = onDeleteClick,
                modifier = Modifier
                    .weight(1f)
                    .fillMaxHeight(),
                shape = RoundedCornerShape(0.dp),
                colors = ButtonDefaults.buttonColors(containerColor = secondaryButtonColor)
            ) {
                Icon(AppIcons.Delete, contentDescription = stringResource(R.string.label_delete), tint = MaterialTheme.colorScheme.onSurfaceVariant)
            }

            VerticalDivider()

            AppButton(
                onClick = onLearnedClick,
                modifier = Modifier
                    .weight(1f)
                    .fillMaxHeight(),
                shape = RoundedCornerShape(0.dp),
                colors = ButtonDefaults.buttonColors(containerColor = secondaryButtonColor)
            ) {
                Icon(AppIcons.StageLearned, contentDescription = stringResource(R.string.label_learned), tint = MaterialTheme.colorScheme.onSurfaceVariant)
            }

            AppButton(
                onClick = onDoneClick,
                modifier = Modifier
                    .weight(2f)
                    .fillMaxHeight(),
                shape = RoundedCornerShape(0.dp),
                colors = ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.primary)
            ) {
                Icon(AppIcons.Stage1, contentDescription = stringResource(R.string.label_done), tint = MaterialTheme.colorScheme.onPrimary)
            }
        }

        Spacer(Modifier.height(4.dp))

        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 8.dp)
        ) {
            Text(stringResource(R.string.label_delete), Modifier.weight(1f), textAlign = TextAlign.Center, fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
            Text(stringResource(R.string.label_learned), Modifier.weight(1f), textAlign = TextAlign.Center, fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
            Text(stringResource(R.string.label_move_first_stage), Modifier.weight(2f), textAlign = TextAlign.Center, fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurface)
        }
    }
}

@Composable
fun VerticalDivider(
    modifier: Modifier = Modifier,
    thickness: Dp = 1.dp,
    color: Color = MaterialTheme.colorScheme.background.copy(alpha = 0.5f)
) {
    Box(
        modifier
            .fillMaxHeight()
            .width(thickness)
            .background(color = color)
    )
}

@Preview
@Composable
fun VerticalDividerPreview() {
    VerticalDivider()
}

@Composable
fun EnhancedDuplicateDialog(
    newItem: VocabularyItem,
    existingItem: VocabularyItem,
    onDismiss: () -> Unit,
    onDelete: () -> Unit,
    onMerge: () -> Unit
) {
    AppDialog(onDismissRequest = onDismiss, title = {Text(stringResource(R.string.duplicate_detected), style = MaterialTheme.typography.headlineSmall)}) {
            Column(Modifier.padding(24.dp)) {
                Text(
                    stringResource(R.string.text_a_similar_item_already_exists),
                    style = MaterialTheme.typography.bodyMedium
                )
                Spacer(Modifier.height(16.dp))

                Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceAround) {
                    Column(Modifier.weight(1f)) {
                        Text(stringResource(R.string.new_item), style = MaterialTheme.typography.titleSmall)
                        Text(newItem.wordFirst)
                        Text(newItem.wordSecond)
                    }
                    Column(Modifier.weight(1f)) {
                        Text(stringResource(R.string.existing_item_id_d, existingItem.id), style = MaterialTheme.typography.titleSmall)
                        Text(existingItem.wordFirst)
                        Text(existingItem.wordSecond)
                    }
                }
                Spacer(Modifier.height(24.dp))
                DialogSegmentedButtons(
                    onDeleteClick = onDelete,
                    onKeepBothClick = onDismiss,
                    onMergeClick = onMerge
                )
            }
    }
}

@Suppress("HardCodedStringLiteral")
@Preview
@Composable
fun EnhancedDuplicateDialogPreview() {
    val newItem = VocabularyItem(id = 1, wordFirst = "Test New", wordSecond = "Test Neu", languageFirstId = 1, languageSecondId = 2)
    val existingItem = VocabularyItem(id = 2, wordFirst = "Test Old", wordSecond = "Test Alt", languageFirstId = 1, languageSecondId = 2)
    EnhancedDuplicateDialog(
        newItem = newItem,
        existingItem = existingItem,
        onDismiss = {},
        onDelete = {},
        onMerge = {}
    )
}

@Composable
fun DialogSegmentedButtons(
    onDeleteClick: () -> Unit,
    onKeepBothClick: () -> Unit,
    onMergeClick: () -> Unit
) {
    Column(
        modifier = Modifier.fillMaxWidth(),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        val buttonHeight = 48.dp
        val cornerRadius = 24.dp
        val secondaryButtonColor = MaterialTheme.colorScheme.surfaceVariant
        val onSecondaryTextColor = MaterialTheme.colorScheme.onSurfaceVariant

        Row(
            modifier = Modifier
                .fillMaxWidth()
                .height(buttonHeight)
                .clip(RoundedCornerShape(cornerRadius)),
            verticalAlignment = Alignment.CenterVertically
        ) {

            AppButton(
                onClick = onDeleteClick,
                modifier = Modifier
                    .weight(1f)
                    .fillMaxHeight(),
                shape = RoundedCornerShape(0.dp),
                colors = ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.errorContainer)
            ) {
                Icon(AppIcons.Delete, contentDescription = stringResource(R.string.delete_new), tint = MaterialTheme.colorScheme.onErrorContainer)
            }

            VerticalDivider()


            AppButton(
                onClick = onKeepBothClick,
                modifier = Modifier
                    .weight(1f)
                    .fillMaxHeight(),
                shape = RoundedCornerShape(0.dp),
                colors = ButtonDefaults.buttonColors(containerColor = secondaryButtonColor)
            ) {
                Icon(AppIcons.Copy, contentDescription = stringResource(R.string.keep_both), tint = onSecondaryTextColor)
            }

            // Merge Button
            AppButton(
                onClick = onMergeClick,
                modifier = Modifier
                    .weight(2f)
                    .fillMaxHeight(),
                shape = RoundedCornerShape(0.dp),
                colors = ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.primary)
            ) {
                Icon(AppIcons.Merge, contentDescription = stringResource(R.string.merge), tint = MaterialTheme.colorScheme.onPrimary)
            }
        }

        Spacer(Modifier.height(4.dp))

        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 4.dp)
        ) {
            Text(stringResource(R.string.delete_new), Modifier.weight(1f), textAlign = TextAlign.Center, fontSize = 12.sp, color = MaterialTheme.colorScheme.error)
            Text(stringResource(R.string.keep_both), Modifier.weight(1f), textAlign = TextAlign.Center, fontSize = 12.sp, color = onSecondaryTextColor)
            Text(stringResource(R.string.merge_items), Modifier.weight(2f), textAlign = TextAlign.Center, fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurface)
        }
    }
}

@Preview
@Composable
fun DialogSegmentedButtonsPreview() {
    DialogSegmentedButtons(onDeleteClick = {}, onKeepBothClick = {}, onMergeClick = {})
}