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.material.MaterialTheme
import androidx.compose.material.Text
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

@Composable
fun parsedWordsTable(
    languageManager: LanguageManager,
    parsedWords: Map<String, Int>,
    onBackClick: () -> Unit,
    onProjectClick: () -> Unit,
    onCodeToVerifyClick: () -> Unit,
    onCompareClick: () -> Unit,
) {
    val noFileSnackbarVisibleState = remember { mutableStateOf(false) }

    // State pour stocker la liste triée des mots
    var sortedWords by remember { mutableStateOf(parsedWords.toList()) }

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

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

    // Fonction pour trier par ordre alphabétique
    fun sortByAlphabet(isAscendingOrder: Boolean) {
        sortList(compareBy { it.first }, isAscendingOrder)
    }

    // Fonction pour trier par nombre d'occurrences
    fun sortByOccurrences(isAscendingOrder: Boolean) {
        sortList(compareByDescending { it.second }, isAscendingOrder)
    }


    Column(
        modifier = Modifier.fillMaxSize(),
        verticalArrangement = Arrangement.Top,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Text(text = "Mots parsés", style = MaterialTheme.typography.h3)

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

        // Tableau des mots parsés
        LazyColumn(modifier = Modifier.padding(16.dp)) {
            item {
                parsedWordsHeaderRow(
                    onWordHeaderClick = {
                        sortByAlphabet(!isAscendingOrderByWord)
                        isAscendingOrderByWord = !isAscendingOrderByWord
                    },
                    onOccurrencesHeaderClick = {
                        sortByOccurrences(!isAscendingOrderByOccurrences)
                        isAscendingOrderByOccurrences = !isAscendingOrderByOccurrences
                    },
                    isAscendingOrderByWord = isAscendingOrderByWord,
                    isAscendingOrderByOccurrences = isAscendingOrderByOccurrences
                )
            }
            items(sortedWords) { word ->
                val backgroundColor = if (sortedWords.indexOf(word) % 2 == 0) {
                    Color.White
                } else {
                    Color.LightGray
                }
                parsedWordsDataRow(word = word.first, count = word.second, backgroundColor = backgroundColor)
            }
        }

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

        Row (
            horizontalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            buttonComponent(
                text = languageManager.getBackText(),
                onClick = { onBackClick() },
                icon = Icons.Filled.ArrowBack,
                modifier = Modifier.height(40.dp)
            )
            buttonComponent(
                text = languageManager.getCompareText(),
                onClick = onCompareClick,
                modifier = Modifier.height(40.dp),
            )
        }
    }
    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"
                }
            }
        }
    }
}

@Composable
fun parsedWordsHeaderRow(
    onWordHeaderClick: () -> Unit,
    onOccurrencesHeaderClick: () -> Unit,
    isAscendingOrderByWord: Boolean,
    isAscendingOrderByOccurrences: Boolean
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .background(customRedColor)
            .border(1.dp, Color.Black),
        verticalAlignment = Alignment.CenterVertically
    ) {
        // En-tête pour le mot
        Text(
            text = "Mot ${if (isAscendingOrderByWord) "▲" else "▼"}",
            fontWeight = FontWeight.Bold,
            modifier = Modifier
                .weight(1f)
                .padding(8.dp)
                .clickable { onWordHeaderClick() },
            color = Color.White
        )

        // En-tête pour les occurrences
        Text(
            text = "Occurrences ${if (isAscendingOrderByOccurrences) "▲" else "▼"}",
            fontWeight = FontWeight.Bold,
            modifier = Modifier
                .weight(1f)
                .padding(8.dp)
                .clickable { onOccurrencesHeaderClick() },
            color = Color.White
        )
    }
}

@Composable
fun parsedWordsDataRow(word: String, count: Int, backgroundColor: Color) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .background(backgroundColor)
            .border(1.dp, Color.Black),
        verticalAlignment = Alignment.CenterVertically
    ) {
        val modifier = Modifier.weight(1f).padding(8.dp)
        cellContent(word, modifier)
        cellContent(count.toString(), modifier)
    }
}