package main

import androidx.compose.foundation.*
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.Button
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
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.dropdownButtonComponent
import org.apache.poi.ss.usermodel.HorizontalAlignment

@Composable
fun compareResults(
    languageManager: LanguageManager,
    glossaryWords: List<Word>,
    codeWords: List<String>,
    onBackClick: () -> Unit,
    onProjectClick: () -> Unit,
    onCodeToVerifyClick: () -> Unit,
) {
    println(glossaryWords)
    val commonWords = findCommonWords(glossaryWords, codeWords)
    var isCompareClicked by remember { mutableStateOf(false) }
    val noFileSnackbarVisibleState = remember { mutableStateOf(false) }

    Column(
        modifier = Modifier.fillMaxSize(),
        verticalArrangement = Arrangement.Top,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Text(text = "Comparaison glossaire / code", style = MaterialTheme.typography.h3)

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

        commonWordsTable(glossaryWords, codeWords)

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

        // Légende
        Row(
            modifier = Modifier.fillMaxWidth().padding(16.dp),
            // Espace entre les éléments
            horizontalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            LegendItem(color = customGreenColor, label = "Mot dans le glossaire et dans le code")
            LegendItem(color = Color.White, label = "Mot seulement dans le glossaire")
            LegendItem(color = customYellowColor, label = "Mot seulement dans le code")
        }


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

        Button(
            onClick = onBackClick,
            colors = androidx.compose.material.ButtonDefaults.buttonColors(
                backgroundColor = customRedColor,
                contentColor = Color.White
            )
        ) {
            Text(languageManager.getBackText())
        }
    }
    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 {
                    isCompareClicked = true
                }
            }
        }
    }
}

// Ajouter une légende au tableau
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun commonWordsTable(
    glossaryWords: List<Word>,
    codeWords: List<String>
) {
    val glossaryWordsSet = glossaryWords.map { it.name }.toSet()

    Box(
        modifier = Modifier
            .height(500.dp)
    ) {
        val scrollState = rememberLazyListState()
        LazyColumn(
            state = scrollState,
            modifier = Modifier.fillMaxSize().padding(16.dp),
            content = {
                stickyHeader {
                    commonWordsHeaderRow()
                }
                items(glossaryWords) { word ->
                    commonWordsDataRow(word.name, codeWords, glossaryWordsSet)
                }
                items(codeWords) { word ->
                    if (word !in glossaryWordsSet) {
                        commonWordsDataRow(word, codeWords, glossaryWordsSet)
                    }
                }
            }
        )
        VerticalScrollbar(
            modifier = Modifier.align(Alignment.CenterEnd).fillMaxHeight(),
            adapter = rememberScrollbarAdapter(scrollState)
        )
    }
}

@Composable
fun LegendItem(color: Color, label: String) {
    Row(
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.spacedBy(4.dp)
    ) {
        Box(
            modifier = Modifier
                .width(24.dp)
                .height(14.dp)
                .background(color)
                .border(1.dp, Color.Black)
        )
        Text(text = label)
    }
}


@Composable
fun commonWordsHeaderRow() {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .background(customRedColor)
            .border(1.dp, Color.Black),
        verticalAlignment = Alignment.CenterVertically
    ) {
        listOf("Mot du glossaire", "Mot du code", "Présence commune").forEach { header ->
            Text(
                text = header,
                fontWeight = FontWeight.Bold,
                modifier = Modifier.weight(1f).padding(8.dp),
                color = Color.White
            )
        }
    }
}

@Composable
fun commonWordsDataRow(
    word: String,
    codeWords: List<String>,
    glossaryWordsSet: Set<String>
) {
    val modifier = Modifier
        .fillMaxWidth()

    val isCommon = word in codeWords && word in glossaryWordsSet

    val backgroundColor = when {
        isCommon -> customGreenColor // Couleur pour les mots communs
        word in codeWords -> customYellowColor // Couleur pour les mots du code
        word in glossaryWordsSet -> Color.White // Couleur pour les mots du glossaire
        else -> Color.White
    }

    Row(
        modifier = modifier.background(backgroundColor)
            .border(1.dp, Color.Black)
            .padding(8.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        cellContent(word, modifier)
        cellContent(if (word in codeWords) "Oui" else "Non", modifier)
        cellContent(if (isCommon) "Oui" else "Non", modifier)
    }
}

fun findCommonWords(glossaryWords: List<Word>, codeWords: List<String>): List<String> {
    val glossaryWordsSet = glossaryWords.map { it.name }.toSet()
    return codeWords.filter { it in glossaryWordsSet }
}