package eu.gaudian.translator.view.dialogs

import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.foundation.clickable
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.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.SegmentedButton
import androidx.compose.material3.SegmentedButtonDefaults
import androidx.compose.material3.SingleChoiceSegmentedButtonRow
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
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.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import eu.gaudian.translator.R
import eu.gaudian.translator.model.VocabularyItem
import eu.gaudian.translator.ui.theme.ThemePreviews
import eu.gaudian.translator.utils.StatusMessageService
import eu.gaudian.translator.utils.findActivity
import eu.gaudian.translator.view.LocalConnectionConfigured
import eu.gaudian.translator.view.composable.AppButton
import eu.gaudian.translator.view.composable.AppCheckbox
import eu.gaudian.translator.view.composable.AppDialog
import eu.gaudian.translator.view.composable.AppOutlinedTextField
import eu.gaudian.translator.view.composable.SourceLanguageDropdown
import eu.gaudian.translator.view.composable.TargetLanguageDropdown
import eu.gaudian.translator.viewmodel.LanguageViewModel
import eu.gaudian.translator.viewmodel.TranslationViewModel
import eu.gaudian.translator.viewmodel.VocabularyViewModel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch


enum class VocabularyDialogTab { SINGLE, MULTIPLE, TEXT }

@Composable
fun AddVocabularyDialog(
    initialWord: String? = null,
    translation: String? = null,
    onDismissRequest: () -> Unit,
    showMultiple: Boolean = true
) {
    val activity = LocalContext.current.findActivity()
    val languageViewModel: LanguageViewModel = hiltViewModel(viewModelStoreOwner = activity)
    val vocabularyViewModel = hiltViewModel<VocabularyViewModel>(viewModelStoreOwner = activity)
    val coroutineScope = rememberCoroutineScope()
    val translationViewModel: TranslationViewModel = hiltViewModel(viewModelStoreOwner = activity)
    val connectionConfigured = LocalConnectionConfigured.current
    val statusMessageService = StatusMessageService



    var selectedTab by remember { mutableStateOf(VocabularyDialogTab.SINGLE) }
    var word by remember { mutableStateOf(initialWord ?: "") }
    var showSuccessMessage by remember { mutableStateOf(false) }

    var singleTranslation by remember { mutableStateOf(translation ?: "") }
    val translatedText by translationViewModel.translatedVocabulary.collectAsState()

    var multipleTranslations by remember { mutableStateOf<List<String>>(emptyList()) }
    val selectedTranslations = remember { mutableStateListOf<String>() }

    val selectedSourceLanguage by languageViewModel.selectedSourceLanguage.collectAsState()
    val selectedTargetLanguage by languageViewModel.selectedTargetLanguage.collectAsState()

    var showReview by remember { mutableStateOf(false) }

    val isAddButtonEnabled = word.isNotBlank() &&
            (selectedTab == VocabularyDialogTab.SINGLE && singleTranslation.isNotBlank() ||
                    selectedTab == VocabularyDialogTab.MULTIPLE && selectedTranslations.isNotEmpty()) &&
            selectedTab != VocabularyDialogTab.TEXT

    LaunchedEffect(translatedText, selectedTab) {
        if (selectedTab == VocabularyDialogTab.SINGLE) {
            translatedText?.let { singleTranslation = it }
        }
    }

    AppDialog(onDismissRequest = onDismissRequest, title = { Text(stringResource(R.string.label_add_vocabulary)) }) {
            Column(
                modifier = Modifier.padding(0.dp),
                verticalArrangement = Arrangement.spacedBy(4.dp)
            ) {
                if(showMultiple){
                SingleChoiceSegmentedButtonRow(modifier = Modifier.fillMaxWidth()) {
                    SegmentedButton(
                        selected = selectedTab == VocabularyDialogTab.SINGLE,
                        onClick = { selectedTab = VocabularyDialogTab.SINGLE },
                        shape = SegmentedButtonDefaults.itemShape(index = 0, count = if (connectionConfigured) 3 else 1)
                    ) {
                        Text(stringResource(R.string.title_single))
                    }
                    if(connectionConfigured){
                    SegmentedButton(
                        selected = selectedTab == VocabularyDialogTab.MULTIPLE,
                        onClick = { selectedTab = VocabularyDialogTab.MULTIPLE },
                        shape = SegmentedButtonDefaults.itemShape(index = 1, count = 3)
                    ) {
                        Text(stringResource(R.string.title_multiple))
                    }

                    SegmentedButton(
                        selected = selectedTab == VocabularyDialogTab.TEXT,
                        onClick = { selectedTab = VocabularyDialogTab.TEXT },
                        shape = SegmentedButtonDefaults.itemShape(index = 2, count = 3)
                    ) {
                        Text(stringResource(R.string.text_text))
                    }
                    }}
                }

                if (selectedTab != VocabularyDialogTab.TEXT) {
                    AppOutlinedTextField(
                        value = word,
                        onValueChange = { word = it },
                        label = { Text(stringResource(R.string.text_label_word)) },
                        modifier = Modifier.fillMaxWidth(),
                    )
                }
                SourceLanguageDropdown(
                    languageViewModel = languageViewModel,
                    modifier = Modifier.fillMaxWidth()
                )
                TargetLanguageDropdown(
                    languageViewModel = languageViewModel,
                    modifier = Modifier.fillMaxWidth()
                )

                when (selectedTab) {
                    VocabularyDialogTab.SINGLE -> {
                        Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
                            if(connectionConfigured) {
                                AppButton(
                                    onClick = {
                                        if (word.isNotBlank()) translationViewModel.translateVocabulary(
                                            word
                                        )
                                    },
                                    modifier = Modifier.fillMaxWidth()
                                ) { Text(stringResource(R.string.label_translate)) }
                            }
                            AppOutlinedTextField(
                                value = singleTranslation,
                                onValueChange = { singleTranslation = it },
                                label = { Text(stringResource(R.string.text_translation)) },
                                modifier = Modifier.fillMaxWidth(),
                            )
                        }
                    }
                    VocabularyDialogTab.MULTIPLE -> {
                        Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
                            val textFailedToGetTranslations = stringResource(R.string.text_failed_to_get_translations)
                            AppButton(
                                onClick = {
                                    if (word.isNotBlank()) {
                                        coroutineScope.launch {
                                            translationViewModel.getMultipleTranslations(word)
                                                .onSuccess { fetched ->
                                                    multipleTranslations = fetched
                                                    selectedTranslations.clear()
                                                }
                                                .onFailure { exception ->
                                                    statusMessageService.showErrorMessage(
                                                        textFailedToGetTranslations + exception.message)
                                                }
                                        }
                                    }
                                },
                                modifier = Modifier.fillMaxWidth()
                            ) { Text(stringResource(R.string.find_translations)) }

                            if (multipleTranslations.isNotEmpty()) {
                                Text(stringResource(R.string.text_select_translations_to_add), style = MaterialTheme.typography.titleMedium)
                                LazyColumn(modifier = Modifier.heightIn(max = 150.dp)) {
                                    items(multipleTranslations) { trans ->
                                        Row(
                                            verticalAlignment = Alignment.CenterVertically,
                                            modifier = Modifier
                                                .fillMaxWidth()
                                                .clickable {
                                                    if (selectedTranslations.contains(trans)) selectedTranslations.remove(
                                                        trans
                                                    )
                                                    else selectedTranslations.add(trans)
                                                }
                                                .padding(vertical = 4.dp)
                                        ) {
                                            AppCheckbox(
                                                checked = selectedTranslations.contains(trans),
                                                onCheckedChange = { isChecked ->
                                                    if (isChecked) selectedTranslations.add(trans)
                                                    else selectedTranslations.remove(trans)
                                                }
                                            )
                                            Spacer(modifier = Modifier.width(8.dp))
                                            Text(trans, style = MaterialTheme.typography.bodyMedium)
                                        }
                                    }
                                }
                            }
                        }
                    }
                    VocabularyDialogTab.TEXT -> {
                        val isGenerating by vocabularyViewModel.isGenerating.collectAsState()
                        val generated by vocabularyViewModel.generatedVocabularyItems.collectAsState()
                        LaunchedEffect(isGenerating, generated) {
                            @Suppress("ControlFlowWithEmptyBody")
                            if (!isGenerating && showReview) {
                                //TODO think if we still need this
                            }
                        }
                        Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
                            Text(stringResource(R.string.text_enter_a_text_to_extract))
                            Box(Modifier.fillMaxWidth().padding(0.dp).heightIn(max = 300.dp)){
                            AppOutlinedTextField(
                                value = word,
                                onValueChange = { word = it },
                                label = { Text(stringResource(R.string.label_enter_a_text)) },
                                modifier = Modifier.fillMaxWidth(),
                                maxLines = 5,
                                paste = true,
                                clear = true,

                            )}
                            if (isGenerating) {
                                androidx.compose.material3.CircularProgressIndicator()
                            } else {
                                AppButton(
                                    onClick = {
                                        if (word.isNotBlank()) {
                                            vocabularyViewModel.generateVocabularyFromText(word)
                                            // defer showing review until generation completes
                                            showReview = true
                                        }
                                    },
                                    modifier = Modifier.fillMaxWidth(),
                                ) { Text(stringResource(R.string.find_translations)) }
                            }
                        }
                    }
                }

                AnimatedVisibility(
                    visible = showSuccessMessage,
                    enter = fadeIn(),
                    exit = fadeOut()
                ) {
                    Text(
                        text = stringResource(R.string.vocabulary_added_successfully),
                        style = MaterialTheme.typography.bodyMedium,
                        color = MaterialTheme.colorScheme.primary,
                        textAlign = TextAlign.Center,
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(top = 8.dp)
                    )
                }

                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(top = 16.dp),
                    horizontalArrangement = Arrangement.End
                ) {
                    TextButton(onClick = onDismissRequest) { Text(stringResource(R.string.label_close)) }
                    Spacer(modifier = Modifier.width(8.dp))
                    TextButton(
                        enabled = isAddButtonEnabled,
                        onClick = {
                            coroutineScope.launch {
                                val newItems = when (selectedTab) {
                                    VocabularyDialogTab.SINGLE -> listOf(
                                        VocabularyItem(
                                            languageFirstId = selectedSourceLanguage?.nameResId,
                                            languageSecondId = selectedTargetLanguage?.nameResId,
                                            wordFirst = word,
                                            wordSecond = singleTranslation,
                                            id = 0,
                                        )
                                    )
                                    VocabularyDialogTab.MULTIPLE -> selectedTranslations.map { selectedTrans ->
                                        VocabularyItem(
                                            languageFirstId = selectedSourceLanguage?.nameResId,
                                            languageSecondId = selectedTargetLanguage?.nameResId,
                                            wordFirst = word,
                                            wordSecond = selectedTrans,
                                            id = 0,
                                        )
                                    }
                                    VocabularyDialogTab.TEXT -> emptyList()
                                }
                                vocabularyViewModel.addVocabularyItems(newItems)

                                word = ""
                                singleTranslation = ""
                                multipleTranslations = emptyList()
                                selectedTranslations.clear()
                                showSuccessMessage = true
                                delay(2000)
                                showSuccessMessage = false
                            }
                        }
                    ) { Text(stringResource(R.string.label_add)) }
                }
            }
        }
        if (showReview && !vocabularyViewModel.isGenerating.collectAsState().value) {
            androidx.compose.ui.window.Dialog(
                onDismissRequest = { showReview = false },
                properties = androidx.compose.ui.window.DialogProperties(usePlatformDefaultWidth = false)
            ) {
                androidx.compose.material3.Surface(modifier = Modifier.fillMaxSize()) {
                    VocabularyReviewScreen(
                        onConfirm = { selectedItems, categoryIds ->
                            vocabularyViewModel.addVocabularyItems(selectedItems, categoryIds)
                            showReview = false
                            onDismissRequest()
                        },
                        onCancel = { showReview = false }
                    )
                }
            }
        }
}

@ThemePreviews
@Composable
fun AddVocabularyDialogPreview() {

    AddVocabularyDialog(
        onDismissRequest = {})
}