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.padding
import androidx.compose.foundation.lazy.LazyColumn
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.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.hilt.lifecycle.viewmodel.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavController
import androidx.navigation.compose.rememberNavController
import eu.gaudian.translator.R
import eu.gaudian.translator.utils.findActivity
import eu.gaudian.translator.view.LocalShowExperimentalFeatures
import eu.gaudian.translator.view.composable.AppCard
import eu.gaudian.translator.view.composable.AppScaffold
import eu.gaudian.translator.view.composable.AppTopAppBar
import eu.gaudian.translator.view.composable.OptionItemSwitch
import eu.gaudian.translator.view.dictionary.DictionaryManagerContent
import eu.gaudian.translator.view.hints.HintDefinition
import eu.gaudian.translator.viewmodel.ApiViewModel
import eu.gaudian.translator.viewmodel.DictionaryViewModel
import eu.gaudian.translator.viewmodel.SettingsViewModel

/**
 * A settings screen for configuring dictionary content and the related AI prompt.
 */
@Composable
fun DictionaryOptionsScreen(
    navController: NavController
) {
    val activity = LocalContext.current.findActivity()
    val settingsViewModel: SettingsViewModel = hiltViewModel(viewModelStoreOwner = activity)
    val apiViewModel: ApiViewModel = hiltViewModel(viewModelStoreOwner = activity)
    val dictionaryViewModel : DictionaryViewModel =  hiltViewModel(viewModelStoreOwner = activity)
    val showExperimental = LocalShowExperimentalFeatures.current
    val dictionarySwitches by settingsViewModel.dictionarySwitches.collectAsStateWithLifecycle()
    val dictionaryOptionLabels = stringArrayResource(R.array.dictionary_content).toList()
    val dictionaryOptionKeys = stringArrayResource(R.array.dictionary_content_keys).toList()
    val customPrompt by settingsViewModel.customPromptDictionary.collectAsStateWithLifecycle()
    var tempPrompt by remember(customPrompt) { mutableStateOf(customPrompt) }
    val availableModels by apiViewModel.allValidModels.collectAsStateWithLifecycle()
    val allProviders by apiViewModel.allValidProviders.collectAsStateWithLifecycle()
    val selectedModel by apiViewModel.dictionaryModel.collectAsStateWithLifecycle()
    val tryWiktionaryFirst by settingsViewModel.tryWiktionaryFirst.collectAsStateWithLifecycle()

    AppScaffold(
        topBar = {
            AppTopAppBar(
                title = stringResource(R.string.label_dictionary_options),
                onNavigateBack = { navController.popBackStack() },
                hintContent = HintDefinition.DICTIONARY_OPTIONS.hint()
            )
        }
    ) { paddingValues ->
        LazyColumn(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
                .padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            if (showExperimental) {
                item {
                    AppCard {
                        Column(
                            modifier = Modifier.padding(0.dp),
                            verticalArrangement = Arrangement.spacedBy(8.dp)
                        ) {
                            Row(
                                modifier = Modifier.fillMaxWidth(),
                                verticalAlignment = Alignment.CenterVertically
                            ) {
                                Column(modifier = Modifier.weight(1f)) {
                                    OptionItemSwitch(
                                        title = stringResource(R.string.text_try_wiktionary_first),
                                        description = stringResource(R.string.text_try_first_finding_the_word_on),
                                        checked = tryWiktionaryFirst,
                                        onCheckedChange = { settingsViewModel.setTryWiktionaryFirst(it) },
                                    )
                                }
                            }
                        }
                    }
                }
            }

            item {
                val screenState = PromptSettingsState(
                    availableModels = availableModels,
                    selectedModel = selectedModel,
                    customPrompt = tempPrompt,
                    examplePrompts = emptyList()
                )

                BasePromptSettingsScreen(
                    state = screenState,
                    providers = allProviders,
                    description = stringResource(R.string.text_description_dictionary_prompt),
                    onPromptChanged = { tempPrompt = it },
                    onSaveClicked = { settingsViewModel.saveCustomPromptDictionary(tempPrompt) },
                    onModelSelected = { apiViewModel.setDictionaryModel(it) },
                    hints = emptyArray(), //TODO
                )
            }

            item {
                AppCard(
                    title = stringResource(R.string.label_dictionary_content),
                    text = stringResource(R.string.text_select_the_content_dictionary),
                    expandable = true,
                    initiallyExpanded = false,
                ) {
                    Column(Modifier.padding(0.dp)) {
                        dictionaryOptionKeys.zip(dictionaryOptionLabels).forEach { (key, label) ->
                            val isChecked = dictionarySwitches.contains(key) || dictionarySwitches.contains(label)

                            Row(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .clickable {
                                        settingsViewModel.setDictionarySwitch(key, !isChecked)
                                    }
                                    .padding(vertical = 4.dp),
                                verticalAlignment = Alignment.CenterVertically
                            ) {
                                OptionItemSwitch(
                                    title = label,
                                    // TODO description = "TODO()",
                                    checked = isChecked,
                                    onCheckedChange = { checked ->
                                        settingsViewModel.setDictionarySwitch(key, checked)
                                    },
                                )
                            }
                        }
                    }
                }
            }

            item {
                // The AppCard and callbacks are now handled internally by DictionaryManagerContent
                DictionaryManagerContent(
                    dictionaryViewModel = dictionaryViewModel
                )
            }
        }
    }
}

@Preview
@Composable
fun DictionaryOptionsScreenPreview() {
    val navController = rememberNavController()
    DictionaryOptionsScreen(navController = navController)
}