package eu.gaudian.translator.view.dialogs

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
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.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.DividerDefaults
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
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.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import eu.gaudian.translator.R
import eu.gaudian.translator.model.Language
import eu.gaudian.translator.model.VocabularyItem
import eu.gaudian.translator.utils.findActivity
import eu.gaudian.translator.view.composable.AppButton
import eu.gaudian.translator.view.composable.AppDialog
import eu.gaudian.translator.view.composable.AppOutlinedButton
import eu.gaudian.translator.view.composable.DialogButton
import eu.gaudian.translator.view.composable.SingleLanguageDropDown
import eu.gaudian.translator.viewmodel.LanguageViewModel

@Composable
fun MissingLanguageDialog(
    showDialog: Boolean,
    missingLanguageId: Int,
    affectedItems: List<VocabularyItem>,
    languageViewModel: LanguageViewModel,
    onDismiss: () -> Unit,
    onDelete: (List<VocabularyItem>) -> Unit,
    onReplace: (Int, Int) -> Unit,
    onCreate: (Language) -> Unit
) {
    if (!showDialog) return

    var showAddLanguageDialog by remember { mutableStateOf(false) }
    var selectedReplacementLanguage by remember { mutableStateOf<Language?>(null) }

    if (showAddLanguageDialog) {
        AddCustomLanguageDialog(
            showDialog = true,
            onDismiss = {
                @Suppress("AssignedValueIsNeverRead")
                showAddLanguageDialog = false
            },
            onAddLanguage = { newLanguage ->
                onCreate(newLanguage)
                @Suppress("AssignedValueIsNeverRead")
                showAddLanguageDialog = false
                onDismiss()
            }
        )
    }

    AppDialog(onDismissRequest = onDismiss, title = {
        Text(text = stringResource(R.string.resolve_missing_language_id, missingLanguageId))
    }) { Column(
                modifier = Modifier.padding(24.dp),
                verticalArrangement = Arrangement.spacedBy(16.dp),
            ) {
                Text(
                    text = stringResource(R.string.resolve_missing_language_id, missingLanguageId),
                    style = MaterialTheme.typography.titleLarge,
                    color = MaterialTheme.colorScheme.onSurface,
                    modifier = Modifier.padding(bottom = 8.dp)
                )

                Text(
                    stringResource(
                        R.string.found_d_items_using_this_missing_language_id,
                        affectedItems.size
                    ),
                    style = MaterialTheme.typography.bodyLarge,
                    modifier = Modifier.padding(bottom = 8.dp)
                )

                var itemsVisible by remember { mutableStateOf(false) }
                TextButton(onClick = { itemsVisible = !itemsVisible }) {
                    Text(if (itemsVisible) stringResource(R.string.hide_affected_items) else stringResource(
                        R.string.show_affected_items
                    ))
                }

                if (itemsVisible) {
                    Card(modifier = Modifier.heightIn(max = 150.dp)) {
                        LazyColumn(modifier = Modifier.padding(8.dp)) {
                            items(affectedItems) { item ->
                                Text("• ${item.wordFirst} / ${item.wordSecond}")
                            }
                        }
                    }
                }

                Spacer(Modifier.height(16.dp))

                Text(stringResource(R.string.solution_1_delete_items), fontWeight = FontWeight.Bold)
                Text(
                    stringResource(
                        R.string.permanently_delete_all_d_affected_vocabulary_items,
                        affectedItems.size
                    ), style = MaterialTheme.typography.bodySmall)
                AppButton(
                    onClick = { onDelete(affectedItems) },
                    colors = ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.error),
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(top = 4.dp)
                ) {
                    Text(stringResource(R.string.delete_d_items, affectedItems.size))
                }
                HorizontalDivider(
                    Modifier.padding(vertical = 12.dp),
                    DividerDefaults.Thickness,
                    DividerDefaults.color
                )

                Text(stringResource(R.string.solution_2_replace_id), fontWeight = FontWeight.Bold)
                Text(stringResource(R.string.text_assign_a_different_language_items), style = MaterialTheme.typography.bodySmall)

        SingleLanguageDropDown(
            modifier = Modifier
                .fillMaxWidth()
                .padding(top = 4.dp),
            languageViewModel = languageViewModel,
            selectedLanguage = selectedReplacementLanguage,
            onLanguageSelected = { selectedReplacementLanguage = it }
        )

                AppButton(
                    onClick = {
                        selectedReplacementLanguage?.nameResId?.let {
                            onReplace(missingLanguageId, it)
                        }
                    },
                    enabled = selectedReplacementLanguage != null,
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(top = 4.dp)
                ) {
                    Text(
                        stringResource(
                            R.string.replace_with_d,
                            selectedReplacementLanguage?.name ?: "..."
                        ))
                }
                HorizontalDivider(
                    Modifier.padding(vertical = 12.dp),
                    DividerDefaults.Thickness,
                    DividerDefaults.color
                )

                Text(stringResource(R.string.solution_3_create_language), fontWeight = FontWeight.Bold)
                Text(stringResource(R.string.create_a_new_custom_language_entry_for_this_id), style = MaterialTheme.typography.bodySmall)
                AppOutlinedButton(
                    onClick = {
                        @Suppress("AssignedValueIsNeverRead")
                        showAddLanguageDialog = true
                    },
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(top = 4.dp)
                ) {
                    Text(stringResource(R.string.create_new_language))
                }

                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(top = 16.dp),
                    horizontalArrangement = Arrangement.End,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    DialogButton(
                        content = { Text(stringResource(R.string.label_close)) },
                        onClick = onDismiss
                    )
                }
            }
    }
}

@Suppress("HardCodedStringLiteral")
@OptIn(ExperimentalComposeUiApi::class)
@Preview
@Composable
fun MissingLanguageDialogPreview() {
    LocalContext.current
    val activity = LocalContext.current.findActivity()
    val affectedItems = listOf(
        VocabularyItem(id = 1, languageFirstId = 1, languageSecondId = 2, wordFirst = "Hello", wordSecond = "Hola"),
        VocabularyItem(id = 2, languageFirstId = 1, languageSecondId = 2, wordFirst = "World", wordSecond = "Mundo"),
        VocabularyItem(id = 3, languageFirstId = 1, languageSecondId = 2, wordFirst = "Cat", wordSecond = "Gato")
    )
    val languageViewModel: LanguageViewModel = hiltViewModel(viewModelStoreOwner = activity)

    MissingLanguageDialog(
        showDialog = true,
        missingLanguageId = 999,
        affectedItems = affectedItems,
        languageViewModel = languageViewModel,
        onDismiss = {},
        onDelete = {},
        onReplace = { _, _ -> },
        onCreate = {}
    )
}
