package eu.gaudian.translator.view.vocabulary

import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
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.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.layout.widthIn
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.AutoAwesome
import androidx.compose.material.icons.filled.DriveFolderUpload
import androidx.compose.material.icons.filled.EditNote
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableIntStateOf
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.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringArrayResource
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.navigation.NavHostController
import eu.gaudian.translator.R
import eu.gaudian.translator.model.Language
import eu.gaudian.translator.model.VocabularyItem
import eu.gaudian.translator.utils.StatusMessageId
import eu.gaudian.translator.utils.StatusMessageService
import eu.gaudian.translator.utils.findActivity
import eu.gaudian.translator.view.NavigationRoutes
import eu.gaudian.translator.view.composable.AppButton
import eu.gaudian.translator.view.composable.AppCard
import eu.gaudian.translator.view.composable.AppIcons
import eu.gaudian.translator.view.composable.AppOutlinedButton
import eu.gaudian.translator.view.composable.AppSlider
import eu.gaudian.translator.view.composable.AppTopAppBar
import eu.gaudian.translator.view.composable.InspiringSearchField
import eu.gaudian.translator.view.composable.Screen
import eu.gaudian.translator.view.composable.SourceLanguageDropdown
import eu.gaudian.translator.view.composable.TargetLanguageDropdown
import eu.gaudian.translator.view.hints.HintDefinition
import eu.gaudian.translator.view.library.VocabularyCard
import eu.gaudian.translator.viewmodel.LanguageViewModel
import eu.gaudian.translator.viewmodel.VocabularyViewModel
import kotlinx.coroutines.launch

@Composable
fun NewWordScreen(
    navController: NavHostController,
    modifier: Modifier = Modifier
) {
    val activity = LocalContext.current.findActivity()
    val vocabularyViewModel: VocabularyViewModel = hiltViewModel(viewModelStoreOwner = activity)
    val languageViewModel: LanguageViewModel = hiltViewModel(viewModelStoreOwner = activity)
    val isGenerating by vocabularyViewModel.isGenerating.collectAsState()
    val generatedItems by vocabularyViewModel.generatedVocabularyItems.collectAsState()
    val allLanguages by languageViewModel.allLanguages.collectAsState()
    val recentItems by vocabularyViewModel.vocabularyItems.collectAsState()
    val coroutineScope = rememberCoroutineScope()
    var category by remember { mutableStateOf("") }
    var amount by remember { mutableFloatStateOf(8f) }
    var navigateToReview by remember { mutableStateOf(false) }

    LaunchedEffect(isGenerating, generatedItems, navigateToReview) {
        if (navigateToReview && !isGenerating) {
            if (generatedItems.isNotEmpty()) {
                navController.navigate(NavigationRoutes.NEW_WORD_REVIEW)
            }
            navigateToReview = false
        }
    }

    val statusMessageService = StatusMessageService

    val context = LocalContext.current
    val showTableImportDialog = remember { mutableStateOf(false) }
    var parsedTable by remember { mutableStateOf<List<List<String>>>(emptyList()) }
    var selectedColFirst by remember { mutableIntStateOf(0) }
    var selectedColSecond by remember { mutableIntStateOf(1) }
    var skipHeader by remember { mutableStateOf(true) }
    var selectedLangFirst by remember { mutableStateOf<Language?>(null) }
    var selectedLangSecond by remember { mutableStateOf<Language?>(null) }

    val recentlyAdded = remember(recentItems) {
        recentItems.sortedByDescending { it.id }.take(4)
    }

    fun parseCsv(text: String): List<List<String>> {
        if (text.isBlank()) return emptyList()
        val candidates = listOf(',', ';', '\t')
        val sampleLine = text.lineSequence().firstOrNull { it.isNotBlank() } ?: return emptyList()
        val delimiter = candidates.maxBy { c -> sampleLine.count { it == c } }

        val rows = mutableListOf<List<String>>()
        var current = StringBuilder()
        var inQuotes = false
        val currentRow = mutableListOf<String>()

        var i = 0
        while (i < text.length) {
            when (val ch = text[i]) {
                '"' -> {
                    if (inQuotes && i + 1 < text.length && text[i + 1] == '"') {
                        current.append('"')
                        i++
                    } else {
                        inQuotes = !inQuotes
                    }
                }
                '\r' -> {
                    // ignore
                }
                '\n' -> {
                    val field = current.toString()
                    current = StringBuilder()
                    currentRow.add(field)
                    rows.add(currentRow.toList())
                    currentRow.clear()
                    inQuotes = false
                }
                else -> {
                    if (ch == delimiter && !inQuotes) {
                        val field = current.toString()
                        currentRow.add(field)
                        current = StringBuilder()
                    } else {
                        current.append(ch)
                    }
                }
            }
            i++
        }
        if (current.isNotEmpty() || currentRow.isNotEmpty()) {
            currentRow.add(current.toString())
            rows.add(currentRow.toList())
        }
        return rows.map { row ->
            row.map { it.trim().trim('"') }
        }.filter { r -> r.any { it.isNotBlank() } }
    }

    val importTableLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.OpenDocument(),
        onResult = { uri ->
            uri?.let { u ->
                try {
                    context.contentResolver.takePersistableUriPermission(u, android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION)
                } catch (_: Exception) {}
                try {
                    val mime = context.contentResolver.getType(u)
                    val isExcel = mime == "application/vnd.ms-excel" ||
                        mime == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                    if (isExcel) {
                        statusMessageService.showErrorById(StatusMessageId.ERROR_EXCEL_NOT_SUPPORTED)
                        return@let
                    }
                    context.contentResolver.openInputStream(u)?.use { inputStream ->
                        val text = inputStream.bufferedReader().use { it.readText() }
                        val rows = parseCsv(text)
                        if (rows.isNotEmpty() && rows.maxOf { it.size } >= 2) {
                            parsedTable = rows
                            selectedColFirst = 0
                            selectedColSecond = 1.coerceAtMost(rows.first().size - 1)
                            showTableImportDialog.value = true
                        } else {
                            statusMessageService.showErrorById(StatusMessageId.ERROR_PARSING_TABLE)
                        }
                    }
                } catch (_: Exception) {
                    statusMessageService.showErrorById(StatusMessageId.ERROR_PARSING_TABLE_WITH_REASON)
                }
            }
        }
    )

    Box(
        modifier = modifier
            .fillMaxSize()
            .padding(16.dp),
        contentAlignment = Alignment.TopCenter
    ) {
        Column(
            modifier = Modifier
                .widthIn(max = 700.dp) // Perfect scaling for tablets/foldables
                .fillMaxSize()
                .verticalScroll(rememberScrollState())
                .padding(0.dp)
        ) {
            AppTopAppBar(
                title = stringResource(R.string.label_new_words),
                onNavigateBack = { navController.popBackStack() }
            )

            Spacer(modifier = Modifier.height(16.dp))

            AIGeneratorCard(
                category = category,
                onCategoryChange = { category = it },
                amount = amount,
                onAmountChange = { amount = it },
                languageViewModel = languageViewModel,
                isGenerating = isGenerating,
                onGenerate = {
                    if (category.isNotBlank() && !isGenerating) {
                        coroutineScope.launch {
                            vocabularyViewModel.generateVocabularyItems(category.trim(), amount.toInt())
                            navigateToReview = true
                        }
                    }
                },
            )

            Spacer(modifier = Modifier.height(24.dp))

            AddManuallyCard(
                languageViewModel = languageViewModel,
                vocabularyViewModel = vocabularyViewModel,
            )

            Spacer(modifier = Modifier.height(24.dp))

            BottomActionCardsRow(
                onImportCsvClick = {
                    @Suppress("HardCodedStringLiteral")
                    importTableLauncher.launch(
                        arrayOf(
                            "text/csv",
                            "text/comma-separated-values",
                            "text/tab-separated-values",
                            "text/plain",
                            "application/vnd.ms-excel",
                            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                        )
                    )
                }
            )

            if (recentlyAdded.isNotEmpty()) {
                Spacer(modifier = Modifier.height(32.dp))

                Column  {
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Text(
                            text = stringResource(R.string.label_recently_added),
                            style = MaterialTheme.typography.titleMedium,
                            fontWeight = FontWeight.Bold
                        )
                        TextButton(onClick = { navController.navigate(Screen.Library.route) }) {
                            Text(stringResource(R.string.label_view_all))
                        }
                    }
                    Spacer(modifier = Modifier.height(12.dp))
                    Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
                        recentlyAdded.forEach { item ->
                            VocabularyCard(
                                item = item,
                                allLanguages = allLanguages,
                                isSelected = false,
                                onItemClick = {
                                    @Suppress("HardCodedStringLiteral")
                                    navController.navigate("${NavigationRoutes.VOCABULARY_DETAIL}/${item.id}")
                                },
                                onItemLongClick = {},
                                onDeleteClick = {}
                            )
                        }
                    }
                }
            }

            // Extra padding at the bottom for scroll clearance
            Spacer(modifier = Modifier.height(100.dp))
        }
    }

    if (showTableImportDialog.value) {
        AlertDialog(
            onDismissRequest = { showTableImportDialog.value = false },
            title = { Text(stringResource(R.string.label_import_table_csv_excel)) },
            text = {
                Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
                    val columnCount = parsedTable.maxOfOrNull { it.size } ?: 0
                    Row(verticalAlignment = Alignment.CenterVertically) {
                        Text(stringResource(R.string.label_first_column), modifier = Modifier.weight(1f))
                        var menu1Expanded by remember { mutableStateOf(false) }
                        AppOutlinedButton(onClick = { menu1Expanded = true }) {
                            Text(stringResource(R.string.label_column_n, selectedColFirst + 1))
                        }
                        DropdownMenu(expanded = menu1Expanded, onDismissRequest = { menu1Expanded = false }) {
                            (0 until columnCount).forEach { idx ->
                                val header = parsedTable.firstOrNull()?.getOrNull(idx).orEmpty()
                                DropdownMenuItem(
                                    text = { Text("#${idx + 1} • $header") },
                                    onClick = { selectedColFirst = idx; menu1Expanded = false }
                                )
                            }
                        }
                    }
                    Row(verticalAlignment = Alignment.CenterVertically) {
                        Text(stringResource(R.string.label_second_column), modifier = Modifier.weight(1f))
                        var menu2Expanded by remember { mutableStateOf(false) }
                        AppOutlinedButton(onClick = { menu2Expanded = true }) {
                            Text(stringResource(R.string.label_column_n, selectedColSecond + 1))
                        }
                        DropdownMenu(expanded = menu2Expanded, onDismissRequest = { menu2Expanded = false }) {
                            (0 until columnCount).forEach { idx ->
                                val header = parsedTable.firstOrNull()?.getOrNull(idx).orEmpty()
                                DropdownMenuItem(
                                    text = { Text("#${idx + 1} • $header") },
                                    onClick = { selectedColSecond = idx; menu2Expanded = false }
                                )
                            }
                        }
                    }
                    Text(stringResource(R.string.label_languages))
                    Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) {
                        Column(modifier = Modifier.weight(1f)) {
                            Text(stringResource(R.string.label_first_language))
                            eu.gaudian.translator.view.composable.SingleLanguageDropDown(
                                languageViewModel = languageViewModel,
                                selectedLanguage = selectedLangFirst,
                                onLanguageSelected = { selectedLangFirst = it }
                            )
                        }
                        Column(modifier = Modifier.weight(1f)) {
                            Text(stringResource(R.string.label_second_language))
                            eu.gaudian.translator.view.composable.SingleLanguageDropDown(
                                languageViewModel = languageViewModel,
                                selectedLanguage = selectedLangSecond,
                                onLanguageSelected = { selectedLangSecond = it }
                            )
                        }
                    }
                    Row(verticalAlignment = Alignment.CenterVertically) {
                        androidx.compose.material3.Checkbox(checked = skipHeader, onCheckedChange = { skipHeader = it })
                        Spacer(modifier = Modifier.width(4.dp))
                        Text(stringResource(R.string.label_header_row))
                    }
                    val startIdx = if (skipHeader) 1 else 0
                    val previewA = parsedTable.drop(startIdx).take(5).mapNotNull { it.getOrNull(selectedColFirst) }.joinToString(", ")
                    val previewB = parsedTable.drop(startIdx).take(5).mapNotNull { it.getOrNull(selectedColSecond) }.joinToString(", ")
                    Text(stringResource(R.string.label_preview_first, previewA))
                    Text(stringResource(R.string.label_preview_second, previewB))
                    val totalRows = parsedTable.drop(startIdx).count { row ->
                        val a = row.getOrNull(selectedColFirst).orEmpty().isNotBlank()
                        val b = row.getOrNull(selectedColSecond).orEmpty().isNotBlank()
                        a || b
                    }
                    Text(stringResource(R.string.text_rows_to_import_1d, totalRows))
                }
            },
            confirmButton = {
                TextButton(onClick = {
                    if (selectedColFirst == selectedColSecond) {
                        statusMessageService.showErrorById(StatusMessageId.ERROR_SELECT_TWO_COLUMNS)
                        return@TextButton
                    }
                    val langA = selectedLangFirst
                    val langB = selectedLangSecond
                    if (langA == null || langB == null) {
                        statusMessageService.showErrorById(StatusMessageId.ERROR_SELECT_LANGUAGES)
                        return@TextButton
                    }
                    val startIdx = if (skipHeader) 1 else 0
                    val items = parsedTable.drop(startIdx).mapNotNull { row ->
                        val a = row.getOrNull(selectedColFirst)?.trim().orEmpty()
                        val b = row.getOrNull(selectedColSecond)?.trim().orEmpty()
                        if (a.isBlank() && b.isBlank()) null else VocabularyItem(
                            id = 0,
                            languageFirstId = langA.nameResId,
                            languageSecondId = langB.nameResId,
                            wordFirst = a,
                            wordSecond = b
                        )
                    }
                    if (items.isEmpty()) {
                        statusMessageService.showErrorById(StatusMessageId.ERROR_NO_ROWS_TO_IMPORT)
                        return@TextButton
                    }
                    vocabularyViewModel.addVocabularyItems(items)
                    statusMessageService.showSuccessById(StatusMessageId.SUCCESS_ITEMS_IMPORTED)
                    showTableImportDialog.value = false
                }) { Text(stringResource(R.string.label_import)) }
            },
            dismissButton = {
                TextButton(onClick = { showTableImportDialog.value = false }) {
                    Text(stringResource(R.string.label_cancel))
                }
            }
        )
    }
}

// --- AI GENERATOR CARD (From previous implementation) ---

@Composable
fun AIGeneratorCard(
    category: String,
    onCategoryChange: (String) -> Unit,
    amount: Float,
    onAmountChange: (Float) -> Unit,
    languageViewModel: LanguageViewModel,
    isGenerating: Boolean,
    onGenerate: () -> Unit,
    modifier: Modifier = Modifier
) {

    val icon = Icons.Default.AutoAwesome
    val hints = stringArrayResource(R.array.vocabulary_hints)
    AppCard(
        modifier = modifier.fillMaxWidth(),
        title = stringResource(R.string.label_ai_generator),
        icon = icon,
        hintContent = HintDefinition.VOCABULARY_GENERATE_AI.hint(),
    ) {
        Column(modifier = Modifier.padding(8.dp)) {

            Text(
                text = stringResource(R.string.text_search_term),
                style = MaterialTheme.typography.labelLarge,
                fontWeight = FontWeight.SemiBold
            )
            Spacer(modifier = Modifier.height(8.dp))
            InspiringSearchField(
                value = category,
                hints = hints,
                onValueChange = onCategoryChange
            )
            Spacer(modifier = Modifier.height(24.dp))
            Text(
                text = stringResource(R.string.text_select_languages),
                style = MaterialTheme.typography.labelLarge,
                fontWeight = FontWeight.SemiBold
            )
            Spacer(modifier = Modifier.height(8.dp))
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.spacedBy(12.dp)
            ) {
                SourceLanguageDropdown(
                    modifier = Modifier.weight(1f),
                    languageViewModel = languageViewModel,
                    iconEnabled = false,
                    noBorder = true
                )
                TargetLanguageDropdown(
                    modifier = Modifier.weight(1f),
                    languageViewModel = languageViewModel,
                    iconEnabled = false,
                    noBorder = true
                )
            }
            Spacer(modifier = Modifier.height(24.dp))
            Text(
                text = stringResource(R.string.text_select_amount),
                style = MaterialTheme.typography.labelLarge,
                fontWeight = FontWeight.SemiBold
            )
            Spacer(modifier = Modifier.height(8.dp))
            AppSlider(
                value = amount,
                onValueChange = onAmountChange,
                valueRange = 1f..25f,
                steps = 24,
                modifier = Modifier.fillMaxWidth()
            )
            Text(
                text = stringResource(R.string.text_amount_2d, amount.toInt()),
                style = MaterialTheme.typography.bodyMedium,
                modifier = Modifier.padding(top = 8.dp)
            )
            Spacer(modifier = Modifier.height(32.dp))

            if (isGenerating) {
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.Center
                ) {
                    CircularProgressIndicator()
                }
                Spacer(modifier = Modifier.height(16.dp))
            }

            AppButton(
                onClick = onGenerate,
                modifier = Modifier
                    .fillMaxWidth()
                    .height(56.dp),
                enabled = category.isNotBlank() && !isGenerating
            ) {
                Row(
                    horizontalArrangement = Arrangement.Center,
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier.fillMaxWidth()
                ) {
                    Icon(imageVector = Icons.Default.AutoAwesome, contentDescription = null, modifier = Modifier.size(20.dp))
                    Spacer(modifier = Modifier.width(8.dp))
                    Text(
                        text = stringResource(R.string.text_generate),
                        style = MaterialTheme.typography.titleMedium,
                        fontWeight = FontWeight.Bold
                    )
                }
            }
        }
    }
}

// --- NEW COMPONENTS START HERE ---

@Composable
fun AddManuallyCard(
    languageViewModel: LanguageViewModel,
    vocabularyViewModel: VocabularyViewModel,
    modifier: Modifier = Modifier
) {
    var wordText by remember { mutableStateOf("") }
    var translationText by remember { mutableStateOf("") }
    val selectedSourceLanguage by languageViewModel.selectedSourceLanguage.collectAsState()
    val selectedTargetLanguage by languageViewModel.selectedTargetLanguage.collectAsState()

    val canAdd = wordText.isNotBlank() && translationText.isNotBlank() &&
        selectedSourceLanguage != null && selectedTargetLanguage != null

    AppCard(
        modifier = modifier.fillMaxWidth(),
    ) {
       Column(modifier = Modifier.padding(24.dp)) {
            // Header Row
            Row(
                modifier = Modifier.fillMaxWidth(),
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.SpaceBetween
            ) {
                Row(verticalAlignment = Alignment.CenterVertically) {
                    Box(
                        modifier = Modifier
                            .size(40.dp)
                            .clip(RoundedCornerShape(12.dp))
                            .background(MaterialTheme.colorScheme.surfaceVariant),
                        contentAlignment = Alignment.Center
                    ) {
                        Icon(
                            imageVector = Icons.Default.EditNote,
                            contentDescription = null,
                            tint = MaterialTheme.colorScheme.primary
                        )
                    }
                    Spacer(modifier = Modifier.width(16.dp))
                    Text(
                        text = stringResource(R.string.label_add_vocabulary),
                        style = MaterialTheme.typography.titleLarge,
                        fontWeight = FontWeight.Bold
                    )
                }

            }

            Spacer(modifier = Modifier.height(24.dp))

            // Input Fields
            TextField(
                value = wordText,
                onValueChange = { wordText = it },
                placeholder = { Text(stringResource(R.string.text_label_word), color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.6f)) },
                modifier = Modifier.fillMaxWidth(),
                shape = RoundedCornerShape(12.dp),
                colors = TextFieldDefaults.colors(
                    focusedContainerColor = MaterialTheme.colorScheme.surface, // Very dark background
                    unfocusedContainerColor = MaterialTheme.colorScheme.surface,
                    focusedIndicatorColor = Color.Transparent,
                    unfocusedIndicatorColor = Color.Transparent
                ),
                singleLine = true
            )

            Spacer(modifier = Modifier.height(16.dp))

            TextField(
                value = translationText,
                onValueChange = { translationText = it },
                placeholder = { Text(stringResource(R.string.text_translation), color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.6f)) },
                modifier = Modifier.fillMaxWidth(),
                shape = RoundedCornerShape(12.dp),
                colors = TextFieldDefaults.colors(
                    focusedContainerColor = MaterialTheme.colorScheme.surface,
                    unfocusedContainerColor = MaterialTheme.colorScheme.surface,
                    focusedIndicatorColor = Color.Transparent,
                    unfocusedIndicatorColor = Color.Transparent
                ),
                singleLine = true
            )

            Spacer(modifier = Modifier.height(16.dp))

            Text(
                text = stringResource(R.string.text_select_languages),
                style = MaterialTheme.typography.labelLarge,
                fontWeight = FontWeight.SemiBold
            )
            Spacer(modifier = Modifier.height(8.dp))
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .clip(RoundedCornerShape(16.dp))
                    .background(MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.35f))
                    .padding(12.dp),
                horizontalArrangement = Arrangement.spacedBy(12.dp)
            ) {
                SourceLanguageDropdown(
                    modifier = Modifier.weight(1f),
                    languageViewModel = languageViewModel,
                    iconEnabled = false,
                    noBorder = true
                )
                TargetLanguageDropdown(
                    modifier = Modifier.weight(1f),
                    languageViewModel = languageViewModel,
                    iconEnabled = false,
                    noBorder = true
                )
            }

            Spacer(modifier = Modifier.height(24.dp))

            // Add to List Button (Darker variant)
            AppButton(
                onClick = {
                    val newItem = VocabularyItem(
                        languageFirstId = selectedSourceLanguage?.nameResId,
                        languageSecondId = selectedTargetLanguage?.nameResId,
                        wordFirst = wordText.trim(),
                        wordSecond = translationText.trim(),
                        id = 0
                    )
                    vocabularyViewModel.addVocabularyItems(listOf(newItem))
                    wordText = ""
                    translationText = ""
                },
                modifier = Modifier
                    .fillMaxWidth()
                    .height(56.dp),
                enabled = canAdd
            ) {
                Text(
                    text = stringResource(R.string.label_add),
                    style = MaterialTheme.typography.titleMedium,
                    fontWeight = FontWeight.Bold
                )
            }
        }
    }
}

@Composable
fun BottomActionCardsRow(
    modifier: Modifier = Modifier,
    onImportCsvClick: () -> Unit
) {
    Row(
        modifier = modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.spacedBy(16.dp)
    ) {
        //TODO Explore Packs Card
        AppCard(
            modifier = Modifier
                .weight(1f)
                .height(120.dp),
        ) {
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .alpha(0.6f),
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.Center
            ) {
                Box(
                    modifier = Modifier
                        .size(48.dp)
                        .clip(CircleShape)
                        .background(MaterialTheme.colorScheme.surfaceVariant),
                    contentAlignment = Alignment.Center
                ) {
                    Icon(
                        imageVector = AppIcons.Vocabulary,
                        contentDescription = null,
                        tint = MaterialTheme.colorScheme.primary
                    )
                }
                Spacer(modifier = Modifier.height(12.dp))
                @Suppress("HardCodedStringLiteral")
                Text(
                    text = "Explore Packs",
                    style = MaterialTheme.typography.labelLarge,
                    fontWeight = FontWeight.Bold,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
                Spacer(modifier = Modifier.height(6.dp))
                @Suppress("HardCodedStringLiteral")
                Text(
                    text = "Coming soon",
                    style = MaterialTheme.typography.labelSmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f)
                )
            }
        }

        // Import CSV Card
        AppCard(
            modifier = Modifier
                .weight(1f)
                .height(120.dp),
            onClick = onImportCsvClick
        ) {
            Column(
                modifier = Modifier.fillMaxSize(),
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.Center
            ) {
                Box(
                    modifier = Modifier
                        .size(48.dp)
                        .clip(CircleShape)
                        .background(MaterialTheme.colorScheme.surfaceVariant),
                    contentAlignment = Alignment.Center
                ) {
                    Icon(
                        imageVector = Icons.Default.DriveFolderUpload,
                        contentDescription = null,
                        tint = MaterialTheme.colorScheme.primary
                    )
                }
                Spacer(modifier = Modifier.height(12.dp))
                Text(
                    text = stringResource(R.string.label_import_csv),
                    style = MaterialTheme.typography.labelLarge,
                    fontWeight = FontWeight.Bold
                )
            }
        }
    }
}