package main

import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import main.component.buttonComponent
import main.component.dropdownButtonComponent

@OptIn(ExperimentalMaterialApi::class)
@Composable
fun glossaryDetailedPage(
    languageManager: LanguageManager,
    glossary: List<Word>,
    glossaryName: String,
    onBackClick: () -> Unit,
    onAddWordClick: () -> Unit,
    onExportClick: () -> Unit,
    onImportClick: () -> Unit,
    onProjectClick: () -> Unit,
    onCodeToVerifyClick: () -> Unit,
) {
    var isCompareClicked by remember { mutableStateOf(false) }
    val noFileSnackbarVisibleState = remember { mutableStateOf(false) }

    println(glossary)
    Column(
        modifier = Modifier.fillMaxSize(),
        verticalArrangement = Arrangement.Top, // Align content at the top
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Text(text = "Glossaire : $glossaryName", style = MaterialTheme.typography.h3)

        Spacer(modifier = Modifier.height(16.dp))

        glossaryTable(glossary = glossary)

        Spacer(modifier = Modifier.height(16.dp))

        Row {
            buttonComponent(
                text = "Retour",
                onClick = { onBackClick() },
                icon = Icons.Filled.ArrowBack,
                modifier = Modifier.padding(10.dp)
            )
            buttonComponent(text = "Ajouter un mot", onClick = { onAddWordClick() }, modifier = Modifier.padding(10.dp))
            buttonComponent(
                text = "Importer un fichier",
                onClick = { onImportClick() },
                modifier = Modifier.padding(10.dp)
            )
            if (importedSuccessfully.value) {
                AlertDialog(
                    onDismissRequest = { importedSuccessfully.value = false },
                    title = { Text("Importation réussie") },
                    text = { Text("Le fichier a été importé avec succès") },
                    confirmButton = {
                        Button(
                            onClick = {
                                importedSuccessfully.value = false
                                frame.dispose()
                            },
                            colors = ButtonDefaults.buttonColors(
                                backgroundColor = customRedColor,
                                contentColor = Color.White
                            )
                        ) {
                            Text("OK")
                        }
                    }
                )

            }

            if (errorImportation.value) {
                AlertDialog(
                    onDismissRequest = { errorImportation.value = false },
                    title = { Text("Importation Echouée") },
                    text = { Text("Le fichier n'a pas pu être importé") },
                    confirmButton = {
                        Button(
                            onClick = {
                                errorImportation.value = false
                                frame.dispose()
                            },
                            colors = ButtonDefaults.buttonColors(
                                backgroundColor = customRedColor,
                                contentColor = Color.White
                            )
                        ) {
                            Text("OK")
                        }
                    }
                )
            }
            buttonComponent(
                text = "Exporter un fichier",
                onClick = { onExportClick() },
                modifier = Modifier.padding(10.dp)
            )
            if (exportedSuccessfully.value) {
                AlertDialog(
                    onDismissRequest = { exportedSuccessfully.value = false },
                    title = { Text("Exportation réussie") },
                    text = { Text("Le fichier a été exporté avec succès") },
                    confirmButton = {
                        Button(
                            onClick = { exportedSuccessfully.value = false },
                            colors = ButtonDefaults.buttonColors(
                                backgroundColor = customRedColor,
                                contentColor = Color.White
                            )
                        ) {
                            Text("OK")
                        }
                    }
                )
            }
        }
    }
    dropdownButtonComponent(
        languageManager = languageManager,
        items = listOf(languageManager.getGlossaryText(), languageManager.getCodeToVerifyText(), languageManager.getCompareText())
    ) { selectedOption ->
        // Handle the selected option
        when (selectedOption) {
            languageManager.getGlossaryText() -> onProjectClick()
            languageManager.getCodeToVerifyText() -> onCodeToVerifyClick()
            languageManager.getCompareText() -> {
                if (mostUsedWordList.isEmpty()) {
                    noFileSnackbarVisibleState.value = true
                    return@dropdownButtonComponent
                } else {
                    currentPage.value = "compareProject"
                }
            }
        }
    }
}

var importedSuccessfully = mutableStateOf(false)
var errorImportation = mutableStateOf(false)
var exportedSuccessfully = mutableStateOf(false)

@Composable
fun glossaryTable(glossary: List<Word>) {
    val listState = rememberLazyListState()

    var sortedWords by remember { mutableStateOf(glossary.toList()) }

    // State pour stocker le sens du tri pour chaque bouton
    var isAscendingOrderByWord by remember { mutableStateOf(true) }
    var isAscendingOrderByMainContext by remember { mutableStateOf(true) }

    // Fonction pour trier par ordre alphabétique ou nombre d'occurrences
    fun sortList(comparator: Comparator<Word>, isAscendingOrder: Boolean) {
        sortedWords = if (isAscendingOrder) {
            sortedWords.sortedWith(comparator)
        } else {
            sortedWords.sortedWith(comparator.reversed())
        }
    }

    // Fonction pour trier par mot
    fun sortByWord(isAscendingOrder: Boolean) {
        sortList(compareBy { it.name }, isAscendingOrder)
    }

    // Fonction pour trier par contexte principal
    fun sortByMainContext(isAscendingOrder: Boolean) {
        sortList(compareBy { it.mainContext }, isAscendingOrder)
    }

    Box(
        modifier = Modifier
            .height(500.dp)
            .padding(10.dp)
    ) {
        LazyColumn(state = listState, modifier = Modifier.padding(16.dp)) {
            item {
                headerRow(
                    onWordHeaderClick = {
                        sortByWord(!isAscendingOrderByWord)
                        isAscendingOrderByWord = !isAscendingOrderByWord
                    },
                    onMainContextHeaderClick = {
                        sortByMainContext(!isAscendingOrderByMainContext)
                        isAscendingOrderByMainContext = !isAscendingOrderByMainContext
                    },
                    isAscendingOrderByWord = isAscendingOrderByWord,
                    isAscendingOrderByMainContext = isAscendingOrderByMainContext
                )
            }
            items(sortedWords) { word ->
                val backgroundColor = if (sortedWords.indexOf(word) % 2 == 0) {
                    Color.White
                } else {
                    Color.LightGray
                }
                glossaryDataRow(word = word, backgroundColor = backgroundColor)
            }
        }
    }
}


@Composable
fun headerRow(
    onWordHeaderClick: () -> Unit = {},
    onMainContextHeaderClick: () -> Unit = {},
    isAscendingOrderByWord: Boolean,
    isAscendingOrderByMainContext: Boolean
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .background(customRedColor)
            .border(1.dp, Color.Black),

        verticalAlignment = Alignment.CenterVertically
    ) {
        Text(
            text = "Mot ${if (isAscendingOrderByWord) "▲" else "▼"}",
            modifier = Modifier
                .weight(1f)
                .padding(8.dp)
                .clickable { onWordHeaderClick() },
            fontWeight = FontWeight.Bold,
            color = Color.White
        )
        Text(
            text = "Description",
            modifier = Modifier
                .weight(1f)
                .padding(8.dp),
            fontWeight = FontWeight.Bold,
            color = Color.White
        )
        Text(
            text = "Contexte principal ${if (isAscendingOrderByMainContext) "▲" else "▼"}",
            modifier = Modifier
                .weight(1f)
                .padding(8.dp)
                .clickable { onMainContextHeaderClick() },
            fontWeight = FontWeight.Bold,
            color = Color.White
        )
        Text(
            text = "Contexte secondaire",
            modifier = Modifier
                .weight(1f)
                .padding(8.dp),
            fontWeight = FontWeight.Bold,
            color = Color.White
        )
        Text(
            text = "Lié à",
            modifier = Modifier
                .weight(0.5f)
                .padding(4.dp),
            fontWeight = FontWeight.Bold,
            color = Color.White
        )
        Text(
            text = "Synonyme",
            modifier = Modifier
                .weight(0.5f)
                .padding(4.dp),
            fontWeight = FontWeight.Bold,
            color = Color.White
        )
        Text(
            text = "Antonyme",
            modifier = Modifier
                .weight(0.5f)
                .padding(4.dp),
            fontWeight = FontWeight.Bold,
            color = Color.White
        )
    }
}

@Composable
fun cellContent(text: String, modifier: Modifier = Modifier) {
    Text(
        text = text,
        modifier = modifier
    )
}

@Composable
fun glossaryDataRow(word: Word, backgroundColor: Color) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .background(backgroundColor)
            .border(1.dp, Color.Black),
        verticalAlignment = Alignment.CenterVertically
    ) {
        val modifier = Modifier.padding(8.dp)
        // Contenu de chaque cellule
        cellContent(word.name, modifier.weight(1f))
        cellContent(word.description, modifier.weight(1f))
        cellContent(word.mainContext, modifier.weight(1f))
        cellContent(word.secondaryContext, modifier.weight(1f))
        cellContent(word.relatedTo, modifier.weight(0.5f))
        cellContent(word.synonymous, modifier.weight(0.5f))
        cellContent(word.antonym, modifier.weight(0.5f))
    }
}