package eu.gaudian.translator.view.dictionary

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.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
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.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import androidx.navigation.NavController
import androidx.navigation.compose.rememberNavController
import eu.gaudian.translator.R
import eu.gaudian.translator.model.EtymologyData
import eu.gaudian.translator.model.EtymologyStep
import eu.gaudian.translator.model.Language
import eu.gaudian.translator.model.RelatedWord
import eu.gaudian.translator.utils.TextToSpeechHelper
import eu.gaudian.translator.utils.findActivity
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.AppTopAppBar
import eu.gaudian.translator.viewmodel.DictionaryViewModel
import eu.gaudian.translator.viewmodel.LanguageViewModel
import eu.gaudian.translator.viewmodel.SettingsViewModel
import kotlinx.coroutines.launch

@Composable
fun EtymologyResultScreen(
    navController: NavController,
    word: String,
    languageCode: Int,
) {
    val activity = LocalContext.current.findActivity()
    val dictionaryViewModel: DictionaryViewModel = hiltViewModel(viewModelStoreOwner = activity)
    val languageViewModel: LanguageViewModel = hiltViewModel(viewModelStoreOwner = activity)
    val settingsViewModel: SettingsViewModel = hiltViewModel(viewModelStoreOwner = activity)
    val uiState by dictionaryViewModel.uiState.collectAsState()

    var etymologyData by remember { mutableStateOf<EtymologyData?>(null) }
    var language by remember { mutableStateOf<Language?>(null) }
    var isTtsAvailable by remember { mutableStateOf(false) }

    val context = LocalContext.current
    val scope = rememberCoroutineScope()

    LaunchedEffect(word, languageCode) {
        language = languageViewModel.getLanguageById(languageCode)
        isTtsAvailable = TextToSpeechHelper.isPlayable(context, language)

        // Fetch etymology data
        dictionaryViewModel.fetchEtymology(word, language!!)
    }

    LaunchedEffect(uiState) {
        if (!uiState.isLoading) {
            etymologyData = dictionaryViewModel.etymologyData.value
        }
    }

    DisposableEffect(Unit) {
        onDispose {
            // Clear etymology data when leaving the screen
        }
    }

    AppScaffold(
        topBar = {
            AppTopAppBar(
                title = "TODO",
                onNavigateBack = { navController.popBackStack() },
                actions = {
                    etymologyData?.let { data ->
                        if (isTtsAvailable) {
                            IconButton(onClick = {
                                scope.launch {
                                    val voice = settingsViewModel.getTtsVoiceForLanguage((language?.code ?: 1).toString(), language?.region ?: "")
                                    TextToSpeechHelper.speakOut(context, data.word, language!!, voice)
                                }
                            }) {
                                Icon(AppIcons.Speech, contentDescription = stringResource(R.string.cd_text_to_speech))
                            }
                        }
                        IconButton(
                            onClick = {
                                // Refresh etymology
                                scope.launch {
                                    dictionaryViewModel.fetchEtymology(word, language!!)
                                }
                            },
                            enabled = !uiState.isLoading
                        ) {
                            if (uiState.isLoading) {
                                CircularProgressIndicator(
                                    modifier = Modifier.size(24.dp),
                                    strokeWidth = 2.5.dp
                                )
                            } else {
                                Icon(AppIcons.Refresh, contentDescription = stringResource(R.string.cd_re_generate_definition))
                            }
                        }
                    }
                }
            )
        }
    ) { paddingValues ->
        etymologyData?.let { data ->
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(paddingValues)
                    .padding(horizontal = 20.dp)
                    .verticalScroll(rememberScrollState())
            ) {
                EtymologyResult(data = data)
            }
        } ?: run {
            // Loading state
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(paddingValues),
                verticalArrangement = Arrangement.Center,
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                CircularProgressIndicator(
                    modifier = Modifier.size(48.dp),
                    strokeWidth = 4.dp
                )
                Spacer(modifier = Modifier.height(16.dp))
                Text(
                    text = stringResource(R.string.text_loading_3d),
                    style = MaterialTheme.typography.bodyLarge
                )
            }
        }
    }
}

@Composable
fun EtymologyResult(data: EtymologyData) {
    Column(
        modifier = Modifier.fillMaxWidth(),
        verticalArrangement = Arrangement.spacedBy(16.dp)
    ) {
        Text(
            text = stringResource(R.string.origin_of_, data.word),
            style = MaterialTheme.typography.headlineMedium,
            fontWeight = FontWeight.Bold,
            color = MaterialTheme.colorScheme.primary
        )
        data.timeline.reversed().forEach { step ->
            AppCard(modifier = Modifier.fillMaxWidth()) {
                Column(modifier = Modifier.padding(16.dp)) {
                    Text(
                        text = "${step.year} - ${step.language}",
                        style = MaterialTheme.typography.titleMedium,
                        fontWeight = FontWeight.Bold,
                        color = MaterialTheme.colorScheme.primary
                    )
                    Spacer(modifier = Modifier.height(8.dp))
                    Text(text = step.description, style = MaterialTheme.typography.bodyLarge)
                }
            }
        }
        if (data.relatedWords.isNotEmpty()) {
            Text(
                text = stringResource(R.string.label_related_words),
                style = MaterialTheme.typography.headlineSmall,
                fontWeight = FontWeight.Bold,
                modifier = Modifier.padding(top = 16.dp),
                color = MaterialTheme.colorScheme.primary
            )
            data.relatedWords.forEach { related ->
                AppCard(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(top = 8.dp),
                ) {
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(16.dp),
                        horizontalArrangement = Arrangement.SpaceBetween
                    ) {
                        Text(text = related.word, fontWeight = FontWeight.SemiBold)
                        Text(text = related.language)
                    }
                }
            }
        }
    }
}

@Suppress("HardCodedStringLiteral")
@Preview
@Composable
fun EtymologyResultPreview() {
    val sampleEtymologyData = EtymologyData(
        word = "example",
        timeline = listOf(
            EtymologyStep("1600s", "Latin", "From Latin 'exemplum'"),
            EtymologyStep("1800s", "English", "Adopted into English")
        ),
        relatedWords = listOf(
            RelatedWord("Latin", "exemplum"),
            RelatedWord("French", "exemple")
        )
    )
    EtymologyResult(data = sampleEtymologyData)
}

@Suppress("HardCodedStringLiteral")
@Composable
@Preview
fun EtymologyResultScreenPreview() {
    EtymologyResultScreen(
        navController = rememberNavController(),
        word = "example",
        languageCode = 1
    )
}