@file:Suppress("AssignedValueIsNeverRead")

package eu.gaudian.translator.view.settings

import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import androidx.navigation.NavController
import eu.gaudian.translator.R
import eu.gaudian.translator.model.Language
import eu.gaudian.translator.utils.findActivity
import eu.gaudian.translator.view.composable.AppCard
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.PrimaryButton
import eu.gaudian.translator.view.dialogs.AddCustomLanguageDialog
import eu.gaudian.translator.view.dialogs.EditLanguageDialog
import eu.gaudian.translator.viewmodel.LanguageViewModel

/**
 * This screen allows users to manage which languages are available in the app and add custom languages.
 */
@Composable
fun LanguageOptionsScreen(
    navController: NavController,
) {
    val activity = LocalContext.current.findActivity()
    val languageViewModel: LanguageViewModel = hiltViewModel(viewModelStoreOwner = activity)
    val enabledLanguages by languageViewModel.allLanguages.collectAsState()
    val masterLanguages by languageViewModel.masterLanguages.collectAsState()
    val isAllSelected by languageViewModel.isAllSelected.collectAsState()
    var showAddLanguageDialog by remember { mutableStateOf(false) }
    var editLanguageTarget by remember { mutableStateOf<Language?>(null) }

    AppScaffold(
        topBar = {
            AppTopAppBar(
                title = stringResource(R.string.text_language_options),
                onNavigateBack = { navController.popBackStack() },
            )
        }
    ) { paddingValues ->
        LazyColumn(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
                .padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            item {
                AppCard {
                    Column(Modifier.padding(16.dp)) {

                        AppCard(
                            title = stringResource(R.string.text_select_languages),
                            text = stringResource(R.string.text_language_settings_description),
                            expandable = true,
                            initiallyExpanded = false
                        ) {

                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .clickable { languageViewModel.selectAllLanguages(!isAllSelected) },
                            verticalAlignment = Alignment.CenterVertically,
                            horizontalArrangement = Arrangement.SpaceBetween
                        ) {
                            Text(stringResource(R.string.text_select_all_languages), style = MaterialTheme.typography.titleMedium)
                            AppSwitch(
                                checked = isAllSelected,
                                onCheckedChange = { languageViewModel.selectAllLanguages(it) }
                            )
                        }

                        HorizontalDivider(modifier = Modifier.padding(vertical = 8.dp))

                        LazyColumn(modifier = Modifier.heightIn(max = 400.dp)) {
                            items(masterLanguages.sortedBy { it.name }) { language ->
                                val isEnabled = enabledLanguages.any { it.nameResId == language.nameResId }
                                LanguageItem(
                                    language = language,
                                    isEnabled = isEnabled,
                                    onLanguageToggled = { lang -> languageViewModel.toggleLanguageSelection(lang) },
                                    onLanguageDeleted = { lang -> languageViewModel.removeCustomLanguage(lang) },
                                    onLanguageEdit = { lang -> editLanguageTarget = lang }
                                )
                            }
                        }
                    }
                    }
                }
            }

            item {
                PrimaryButton(
                    onClick = { showAddLanguageDialog = true },
                    text = stringResource(R.string.text_add_custom_language),
                    modifier = Modifier.fillMaxWidth()
                )
            }
        }
    }

    if (showAddLanguageDialog) {
        @Suppress("KotlinConstantConditions")
        AddCustomLanguageDialog(
            showDialog = showAddLanguageDialog,
            onDismiss = { showAddLanguageDialog = false },
            onAddLanguage = { language ->
                languageViewModel.addCustomLanguage(language)
            }
        )
    }

    editLanguageTarget?.let { lang ->
        EditLanguageDialog(
            language = lang,
            onDismiss = { editLanguageTarget = null },
            onSave = { name, code, region ->
                languageViewModel.editLanguage(lang.nameResId, name, code, region)
                editLanguageTarget = null
            }
        )
    }
}

/**
 * A composable that displays a single language item with a switch and a delete button for custom languages.
 */
@Composable
private fun LanguageItem(
    language: Language,
    isEnabled: Boolean,
    onLanguageToggled: (Language) -> Unit,
    onLanguageDeleted: (Language) -> Unit,
    onLanguageEdit: (Language) -> Unit
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .clickable { onLanguageToggled(language) }
            .padding(vertical = 12.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        Column(modifier = Modifier.weight(1f)) {
            Text(language.name, style = MaterialTheme.typography.bodyLarge)
            Text("${language.code} - ${language.region.uppercase()}", style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
        }

        Row(verticalAlignment = Alignment.CenterVertically) {
            IconButton(onClick = { onLanguageEdit(language) }) {
                Icon(
                    imageVector = AppIcons.Edit,
                    contentDescription = stringResource(R.string.edit)
                )
            }
            if (language.isCustom == true) {
                IconButton(onClick = { onLanguageDeleted(language) }) {
                    Icon(
                        imageVector = AppIcons.Delete,
                        contentDescription = stringResource(R.string.text_delete_custom_language),
                        tint = MaterialTheme.colorScheme.error
                    )
                }
            }
            AppSwitch(
                checked = isEnabled,
                onCheckedChange = { onLanguageToggled(language) }
            )
        }
    }
}