package eu.gaudian.translator.view.dialogs

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.width
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
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.stringArrayResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import androidx.navigation.NavController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import eu.gaudian.translator.R
import eu.gaudian.translator.utils.findActivity
import eu.gaudian.translator.view.composable.AppDialog
import eu.gaudian.translator.view.composable.AppSlider
import eu.gaudian.translator.view.composable.DialogButton
import eu.gaudian.translator.view.composable.InspiringSearchField
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.viewmodel.LanguageViewModel
import eu.gaudian.translator.viewmodel.VocabularyViewModel
import kotlinx.coroutines.launch

@Composable
fun ImportVocabularyDialog(
    onDismiss: () -> Unit,
    languageViewModel: LanguageViewModel,
    vocabularyViewModel : VocabularyViewModel,
    optionalDescription: String? = null,
    optionalSearchTerm: String? = null
) {

    val navController = rememberNavController()
    NavHost(navController = navController, startDestination = "import") {
        composable("import") {
            ImportDialogContent(
                navController = navController,
                onDismiss = onDismiss,
                languageViewModel = languageViewModel,
                optionalDescription = optionalDescription,
                optionalSearchTerm = optionalSearchTerm
            )
        }
        @Suppress("HardCodedStringLiteral")
        composable("review") {
            Dialog(
                onDismissRequest = onDismiss,
                properties = DialogProperties(usePlatformDefaultWidth = false)
            ) {
                // Full-screen surface to ensure the dialog covers content and stays above the main FAB/menu
                Surface(modifier = Modifier.fillMaxSize()) {
                    VocabularyReviewScreen(
                        onConfirm = { selectedItems, categoryIds ->
                            vocabularyViewModel.addVocabularyItems(selectedItems, categoryIds)
                            onDismiss()
                        },
                        onCancel = onDismiss
                    )
                }
            }
        }
    }
}

@Composable
fun ImportDialogContent(
    navController: NavController,
    onDismiss: () -> Unit,
    languageViewModel: LanguageViewModel,
    optionalDescription: String? = null,
    optionalSearchTerm: String? = null
) {
    val activity = LocalContext.current.findActivity()
    val vocabularyViewModel: VocabularyViewModel = hiltViewModel(viewModelStoreOwner = activity)
    var category by remember { mutableStateOf(optionalSearchTerm ?: "") }
    var amount by remember { mutableFloatStateOf(1f) }
    val coroutineScope = rememberCoroutineScope()
    val descriptionText = optionalDescription ?: stringResource(R.string.text_let_ai_find_vocabulary_for_you)
    val isGenerating by vocabularyViewModel.isGenerating.collectAsState()

    AppDialog(
        onDismissRequest = onDismiss,
        title = { Text(descriptionText) },
        hintContent =  HintDefinition.IMPORT.hint(),
        content = {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(4.dp)
            ) {
                if (isGenerating) {
                    Box(
                        modifier = Modifier.fillMaxWidth().padding(16.dp),
                        contentAlignment = Alignment.Center
                    ) {
                        CircularProgressIndicator()
                    }
                } else {
                    Text(
                        text = stringResource(R.string.text_search_term),
                        style = MaterialTheme.typography.labelLarge,
                        modifier = Modifier.padding(bottom = 8.dp)
                    )
                    // Modern rotating field using XML resource array
                    InspiringSearchField(
                        value = category,
                        hints = stringArrayResource(R.array.vocabulary_hints),
                        onValueChange = { category = it }
                    )

                    // The "Dica" string has been removed to keep the interface clean

                    Spacer(modifier = Modifier.height(16.dp))
                    Text(
                        text = stringResource(R.string.text_select_languages),
                        style = MaterialTheme.typography.labelLarge,
                        modifier = Modifier.padding(bottom = 8.dp)
                    )
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.spacedBy(1.dp)
                    ) {
                        SourceLanguageDropdown(languageViewModel = languageViewModel)
                    }
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.spacedBy(1.dp)
                    ) {
                        TargetLanguageDropdown(languageViewModel = languageViewModel)
                    }
                    Spacer(modifier = Modifier.height(16.dp))
                    Text(
                        text = stringResource(R.string.text_select_amount),
                        style = MaterialTheme.typography.labelLarge,
                        modifier = Modifier.padding(bottom = 8.dp)
                    )
                    AppSlider(
                        value = amount,
                        onValueChange = { amount = it },
                        valueRange = 1f..25f,
                        steps = 24,
                        modifier = Modifier.fillMaxWidth()
                    )
                    Text(
                        text = stringResource(R.string.text_amount_2d, amount.toInt()),
                        style = MaterialTheme.typography.bodyMedium,
                        modifier = Modifier.fillMaxWidth().padding(top = 8.dp)
                    )
                    Spacer(modifier = Modifier.height(8.dp))
                }

                Spacer(modifier = Modifier.height(16.dp))
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.End
                ) {
                    DialogButton(
                        onClick = onDismiss,
                        content = { Text(stringResource(R.string.label_cancel)) }
                    )
                    if (category.isNotBlank() && !isGenerating) {
                        Spacer(modifier = Modifier.width(8.dp))
                        DialogButton(onClick = {
                            coroutineScope.launch {
                                vocabularyViewModel.generateVocabularyItems(category, amount.toInt())
                                @Suppress("HardCodedStringLiteral")
                                navController.navigate("review")
                            }
                        }) { Text(stringResource(R.string.text_generate)) }
                    }
                }
            }
        }
    )
}

@Suppress("HardCodedStringLiteral")
@Preview
@Composable
fun ImportDialogContentPreview() {
    val activity = LocalContext.current.findActivity()
    val languageViewModel: LanguageViewModel = hiltViewModel(viewModelStoreOwner = activity)

    ImportDialogContent(
        navController = rememberNavController(),
        onDismiss = {},
        languageViewModel = languageViewModel,
        optionalDescription = "Let AI find vocabulary for you",
        optionalSearchTerm = "Travel"
    )
}
