@file:Suppress("HardCodedStringLiteral")

package eu.gaudian.translator.view.settings

import android.speech.tts.Voice
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.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
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.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
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.stringResource
import androidx.compose.ui.unit.dp
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import androidx.navigation.NavController
import eu.gaudian.translator.R
import eu.gaudian.translator.model.Language
import eu.gaudian.translator.utils.Log
import eu.gaudian.translator.utils.TextToSpeechHelper
import eu.gaudian.translator.utils.findActivity
import eu.gaudian.translator.view.composable.AppButton
import eu.gaudian.translator.view.composable.AppCard
import eu.gaudian.translator.view.composable.AppIcons
import eu.gaudian.translator.view.composable.AppScaffold
import eu.gaudian.translator.view.composable.AppSlider
import eu.gaudian.translator.view.composable.AppTopAppBar
import eu.gaudian.translator.view.composable.SecondaryButton
import eu.gaudian.translator.view.composable.SingleLanguageDropDown
import eu.gaudian.translator.viewmodel.LanguageViewModel
import eu.gaudian.translator.viewmodel.SettingsViewModel
import kotlinx.coroutines.launch

@Composable
fun TextToSpeechSettingsScreen(
    navController: NavController,
) {
    val activity = LocalContext.current.findActivity()
    val languageViewModel: LanguageViewModel = hiltViewModel(viewModelStoreOwner = activity)
    val settingsViewModel: SettingsViewModel = hiltViewModel(viewModelStoreOwner = activity)
    val scope = rememberCoroutineScope()
    val speakingSpeed by settingsViewModel.speakingSpeed.collectAsState()
    val context = LocalContext.current

    // Single language selection
    var selectedLanguage by remember { mutableStateOf<Language?>(null) }

    // Available voices and current selection for the chosen language
    var availableVoices by remember { mutableStateOf<List<Voice>>(emptyList()) }
    var selectedVoiceName by remember { mutableStateOf<String?>(null) }

    // Load stored voice whenever language changes
    LaunchedEffect(selectedLanguage) {
        val lang = selectedLanguage ?: run {
            availableVoices = emptyList()
            selectedVoiceName = null
            return@LaunchedEffect
        }
        val voices = TextToSpeechHelper.getVoicesForLanguage(context, lang)
        availableVoices = voices
        val stored = settingsViewModel.getTtsVoiceForLanguage(lang.code, lang.region)
        selectedVoiceName = stored
    }

    AppScaffold(
        topBar = {
            AppTopAppBar(
                title = stringResource(R.string.settings_title_voice),
                onNavigateBack = { navController.popBackStack() },
            )
        }
    ) { paddingValues ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .verticalScroll(rememberScrollState())
                .padding(paddingValues)
                .padding(8.dp),
            verticalArrangement = Arrangement.spacedBy(8.dp)
        ) {
            // Language selection card
            AppCard {
                Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
                    Text(stringResource(R.string.language), style = MaterialTheme.typography.titleMedium)
                    SingleLanguageDropDown(
                        languageViewModel = languageViewModel,
                        selectedLanguage = selectedLanguage,
                        onLanguageSelected = { selectedLanguage = it },
                        showNoneOption = true,
                        onNoneSelected = { selectedLanguage = null }
                    )
                }
            }

            // Voice selection for the selected language
            val lang = selectedLanguage
            Log.d("Selected language: $lang")
            if (lang != null) {
                AppCard {
                    Column(modifier = Modifier.padding(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
                        Text(text = lang.name, style = MaterialTheme.typography.titleMedium)
                        Row(modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                            SecondaryButton(
                                onClick = { 
                                    selectedVoiceName = null 
                                    scope.launch { settingsViewModel.saveTtsVoiceForLanguage(lang.code, lang.region, null) }
                                },
                                text = stringResource(R.string.default_value),
                                icon = if (selectedVoiceName == null) AppIcons.Check else null,
                                inverse = true
                            )
                            Spacer(Modifier.weight(1f))
                        }
                        // Bounded scrollable list of voices to save space
                        if (availableVoices.isEmpty()) {
                            Text(
                                text = "No TTS voices found for this language on your device.",
                                style = MaterialTheme.typography.bodyMedium
                            )
                        } else {
                            LazyColumn(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .heightIn(max = 300.dp),
                                verticalArrangement = Arrangement.spacedBy(8.dp)
                            ) {
                                items(availableVoices) { v ->
                                    SecondaryButton(
                                        onClick = {
                                            selectedVoiceName = v.name
                                            scope.launch { settingsViewModel.saveTtsVoiceForLanguage(lang.code, lang.region, selectedVoiceName) }
                                        },
                                        modifier = Modifier.fillMaxWidth(),
                                        text = v.name,
                                        icon = if (selectedVoiceName == v.name) AppIcons.Check else null,
                                        inverse = true
                                    )
                                }
                            }
                        }
                        Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                            val sample = stringResource(R.string.tts_test_phrase)
                            AppButton(
                                onClick = {
                                    scope.launch {
                                        val ts = eu.gaudian.translator.utils.TranslationService(context)
                                        val translated = if(lang.code != "en") ts.simpleTranslateTo(sample, lang).getOrElse { sample } else sample

                                        TextToSpeechHelper.speakOut(
                                            context,
                                             translated,
                                            lang,
                                            selectedVoiceName,
                                        )
                                    }
                                },
                                modifier = Modifier.weight(1f),
                                content = {Text(stringResource(R.string.test))}
                            )
                        }
                    }
                }
            }

            AppCard {
                var speedLocal by remember { mutableFloatStateOf(speakingSpeed.toFloat()) }
                var isDragging by remember { mutableStateOf(false) }
                var saveJob by remember { mutableStateOf<kotlinx.coroutines.Job?>(null) }

                LaunchedEffect(speakingSpeed) {
                    if (!isDragging) {
                        speedLocal = speakingSpeed.toFloat()
                    }
                }

                Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
                    Text(text = stringResource(R.string.label_speaking_speed), style = MaterialTheme.typography.titleMedium)
                    Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) {
                        Text(text = speedLocal.toInt().toString(), style = MaterialTheme.typography.bodyMedium)
                    }
                    AppSlider(
                        value = speedLocal,
                        onValueChange = { value ->
                            isDragging = true
                            val coerced = value.coerceIn(50f, 200f)
                            speedLocal = coerced
                            // Debounce persistence: cancel previous pending save and schedule a new one
                            saveJob?.cancel()
                            saveJob = scope.launch {
                                kotlinx.coroutines.delay(350)
                                settingsViewModel.saveSpeakingSpeed(coerced.toInt())
                                isDragging = false
                            }
                        },
                        valueRange = 50f..200f,
                        steps = 14
                    )
                }
            }
        }
    }
}