package eu.gaudian.translator.view.settings

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.defaultMinSize
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.derivedStateOf
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.unit.dp
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavController
import eu.gaudian.translator.R
import eu.gaudian.translator.utils.findActivity
import eu.gaudian.translator.view.composable.ApiModelDropDown
import eu.gaudian.translator.view.composable.AppCard
import eu.gaudian.translator.view.composable.AppOutlinedTextField
import eu.gaudian.translator.view.composable.AppScaffold
import eu.gaudian.translator.view.composable.AppTopAppBar
import eu.gaudian.translator.view.composable.PrimaryButton
import eu.gaudian.translator.view.composable.SecondaryButton
import eu.gaudian.translator.viewmodel.ApiViewModel
import eu.gaudian.translator.viewmodel.SettingsViewModel

@Composable
fun ExerciseSettingsScreen(
    navController: NavController
) {
    val activity = LocalContext.current.findActivity()
    val settingsViewModel: SettingsViewModel = hiltViewModel(viewModelStoreOwner = activity)
    val apiViewModel: ApiViewModel = hiltViewModel(viewModelStoreOwner = activity)
    val customPrompt by settingsViewModel.customPromptExercise.collectAsStateWithLifecycle()
    var tempPrompt by remember(customPrompt) { mutableStateOf(customPrompt) }

    // Get all models and all providers from the ApiViewModel
    val allModels by apiViewModel.allValidModels.collectAsStateWithLifecycle()
    val allProviders by apiViewModel.allValidProviders.collectAsStateWithLifecycle()

    // Get the state from the SettingsViewModel which knows which providers have keys
    val apiKeyState by apiViewModel.apiKeyManagementState.collectAsStateWithLifecycle()

    // Derive the list of models that are actually available (i.e., their provider has a key)
    val availableModels by remember(allModels, apiKeyState) {
        derivedStateOf {
            val providersWithKeys = apiKeyState.providerStates.filter { it.hasKey }.map { it.provider.key }.toSet()
            allModels.filter { it.providerKey in providersWithKeys }
        }
    }

    val selectedModel by apiViewModel.exerciseModel.collectAsStateWithLifecycle()
    val examplePrompts = stringArrayResource(R.array.exercise_example_prompts).toList()

    AppScaffold(
        topBar = {
            AppTopAppBar(
                title = stringResource(R.string.exercise_settings),
                onNavigateBack = { navController.popBackStack() },
            )
        }
    ) { paddingValues ->
        LazyColumn(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
                .padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            item {
                AppCard {
                    Text(
                        text = stringResource(R.string.exercise_settings_description),
                        style = MaterialTheme.typography.bodyLarge,
                        modifier = Modifier.padding(16.dp)
                    )
                }
            }

            item {
                AppCard {
                    Column(
                        modifier = Modifier.padding(16.dp),
                        verticalArrangement = Arrangement.spacedBy(16.dp)
                    ) {
                        Text(
                            stringResource(R.string.label_ai_model_and_prompt),
                            style = MaterialTheme.typography.titleMedium
                        )
                        ApiModelDropDown(
                            models = availableModels, // Use the filtered list
                            providers = allProviders,
                            selectedModel = selectedModel,
                            onModelSelected = { model ->
                                apiViewModel.setExerciseModel(model)
                            },
                        )
                        AppOutlinedTextField(
                            value = tempPrompt,
                            onValueChange = { tempPrompt = it },
                            label = { Text(stringResource(R.string.custom_exercise_prompt)) },
                            modifier = Modifier.defaultMinSize(minHeight = 150.dp)
                        )
                        PrimaryButton(
                            onClick = { settingsViewModel.saveCustomExercisePrompt(tempPrompt) },
                            text = stringResource(R.string.text_save_prompt),
                            modifier = Modifier.align(Alignment.End)
                        )
                    }
                }
            }

            if (examplePrompts.isNotEmpty()) {
                item {
                    AppCard {
                        Column(Modifier.padding(16.dp)) {
                            Text(
                                stringResource(R.string.examples),
                                style = MaterialTheme.typography.titleMedium,
                                modifier = Modifier.padding(bottom = 8.dp)
                            )
                            LazyRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                                items(examplePrompts) { prompt ->
                                    SecondaryButton(
                                        onClick = { tempPrompt = prompt },
                                        text = prompt
                                    )
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
