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.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import main.component.buttonComponent
import main.component.dropdownButtonComponent

var mostUsedWordList = mutableMapOf<String, Int>()

enum class Language {
    FRENCH, ENGLISH
}

@Composable
fun homePage(
    languageManager: LanguageManager,
    onProjectClick: () -> Unit,
    onCodeToVerifyClick: () -> Unit
) {
    val appState = AppState
    val noFileSnackbarVisibleState = remember { mutableStateOf(false) }
    var isCompareClicked by remember { mutableStateOf(false) }
    var selectedGlossary by remember { mutableStateOf<Glossary?>(null) }

    var showHelpPage by remember { mutableStateOf(false) }


    if (showHelpPage) {
        HelpPage {
            // Retour depuis la page d'aide
            showHelpPage = false
            print("Retour depuis la page d'aide")
        }
    } else {

        if (!isCompareClicked && selectedGlossary == null) {
            // Utilisez un Box pour placer le drapeau en haut à droite
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(16.dp),
                contentAlignment = Alignment.TopEnd
            ) {
                // Utilisez les images des drapeaux
                Image(
                    painter = painterResource(if (languageManager.currentLanguage == Language.FRENCH) "FR.png" else "EN.png"),
                    contentDescription = "Language Flag",
                    modifier = Modifier.size(48.dp)
                        .clickable { languageManager.changeLanguage() }
                )
            }

            Column(
                modifier = Modifier.fillMaxSize(),
                verticalArrangement = Arrangement.Center,
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                Text("Quali'Nomme", style = MaterialTheme.typography.h3)

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

                Column {
                    Row(
                        horizontalArrangement = Arrangement.spacedBy(16.dp)
                    ) {
                        buttonComponent(languageManager.getGlossaryText(), onProjectClick)

                        buttonComponent(languageManager.getCodeToVerifyText(), onCodeToVerifyClick)

                        Button(
                            onClick = {
                                if (mostUsedWordList.isEmpty()) {
                                    noFileSnackbarVisibleState.value = true
                                    return@Button
                                } else {
                                    isCompareClicked = true
                                }
                            },
                            modifier = Modifier.width(200.dp),
                            colors = ButtonDefaults.buttonColors(
                                backgroundColor = customRedColor,
                                contentColor = Color.White
                            ),
                            enabled = mostUsedWordList.isNotEmpty()
                        ) {
                            Text(languageManager.getCompareText())
                        }
                    }
                }

                if (noFileSnackbarVisibleState.value) {
                    Snackbar(
                        modifier = Modifier.padding(16.dp),
                        action = {
                            buttonComponent("OK", { noFileSnackbarVisibleState.value = false })
                        }
                    ) {
                        Text("Veuillez d'abord importer un fichier")
                    }
                }
            }

            // Example usage with text options
            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
                        }
                    }
                }
            }
        }
        var selectedProject by remember { mutableStateOf<Project?>(null) }


        when {
            isCompareClicked && selectedProject == null && selectedGlossary == null -> {
                projectList(
                    projects = loadProjects(),
                    onProjectSelected = { project ->
                        selectedProject = project
                        appState.selectedProject = selectedProject
                    },
                    onBackClick = {
                        isCompareClicked = false
                        selectedGlossary = null
                        selectedProject = null
                    },
                    onProjectClick = { currentPage.value = "projects" },
                    languageManager = languageManager,
                    onCodeToVerifyClick = { currentPage.value = "choixLangage" }
                )
            }

            isCompareClicked && selectedGlossary == null -> {
                glossaryList(
                    glossaries = loadGlossaries(appState.selectedProject!!),
                    onGlossarySelected = { glossary ->
                        selectedGlossary = glossary
                    },
                    onBackClick = {
                        isCompareClicked = false
                        selectedGlossary = null
                        selectedProject = null
                    },
                    onProjectClick = { currentPage.value = "projects" },
                    languageManager = languageManager,
                    onCodeToVerifyClick = { currentPage.value = "choixLangage" }
                )
            }

            isCompareClicked -> {
                selectedGlossary?.let {
                    compareResults(
                        languageManager = languageManager,
                        glossaryWords = loadDatasFromFile(it.jsonFilePath),
                        codeWords = mostUsedWordList.keys.toList(),
                        onBackClick = {
                            isCompareClicked = false
                            selectedGlossary = null
                            selectedProject = null
                        },
                        onProjectClick = { currentPage.value = "projects" },
                        onCodeToVerifyClick = { currentPage.value = "choixLangage" },
                    )

                }
            }
        }

        HelpButton {
            showHelpPage = true
        }

    }
}

@Composable
fun glossaryList(
    languageManager: LanguageManager,
    glossaries: List<Glossary>,
    onGlossarySelected: (Glossary) -> Unit,
    onBackClick: () -> Unit,
    onProjectClick: () -> Unit,
    onCodeToVerifyClick: () -> Unit
) {

    var isCompareClicked by remember { mutableStateOf(false) }
    val noFileSnackbarVisibleState = remember { mutableStateOf(false) }

    Column(
        modifier = Modifier.fillMaxSize(),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Text("Sélectionnez un glossaire", style = MaterialTheme.typography.h5)

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

        Box(
            modifier = Modifier
                .height(500.dp)
                .width(250.dp)
                .padding(10.dp)
        ) {
            val scrollState = rememberLazyListState()
            LazyColumn(
                state = scrollState,
                modifier = Modifier
                    .padding(10.dp)
                    .width(200.dp),
                verticalArrangement = Arrangement.spacedBy(10.dp)
            ) {
                if (glossaries.isEmpty()) {
                    item {
                        Text("Aucun glossaire disponible")
                    }
                } else {
                    items(glossaries) { glossary ->
                        Row(
                            modifier = Modifier.width(200.dp).fillMaxWidth(),
                            horizontalArrangement = Arrangement.SpaceBetween,
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            buttonComponent(glossary.name, { onGlossarySelected(glossary) }, width = 200)
                        }
                    }
                }
            }
            VerticalScrollbar(
                modifier = Modifier.align(Alignment.CenterEnd).fillMaxHeight(),
                adapter = rememberScrollbarAdapter(scrollState)
            )
            Spacer(modifier = Modifier.height(6.dp))
        }
        Spacer(modifier = Modifier.height(16.dp))

        buttonComponent("Retour", onBackClick)
    }

    dropdownButtonComponent(
        languageManager,
        items = listOf("Glossaire", "Code à vérifier", "Comparer")
    ) { selectedOption ->
        // Handle the selected option
        when (selectedOption) {
            "Glossaire" -> onProjectClick()
            "Code à vérifier" -> onCodeToVerifyClick()
            "Comparer" -> {
                if (mostUsedWordList.isEmpty()) {
                    noFileSnackbarVisibleState.value = true
                    return@dropdownButtonComponent
                } else {
                    isCompareClicked = true
                }
            }
        }
    }
}

@Composable
fun projectList(
    languageManager: LanguageManager,
    projects: List<Project>,
    onProjectSelected: (Project) -> Unit,
    onBackClick: () -> Unit,
    onProjectClick: () -> Unit,
    onCodeToVerifyClick: () -> Unit
) {

    var isCompareClicked by remember { mutableStateOf(false) }
    val noFileSnackbarVisibleState = remember { mutableStateOf(false) }

    Column(
        modifier = Modifier.fillMaxSize(),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Text("Sélectionnez un projet", style = MaterialTheme.typography.h5)

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

        Box(
            modifier = Modifier
                .height(500.dp)
                .width(250.dp)
                .padding(10.dp)
        ) {
            val scrollState = rememberLazyListState()
            LazyColumn(
                state = scrollState,
                modifier = Modifier
                    .padding(10.dp)
                    .width(200.dp),
                verticalArrangement = Arrangement.spacedBy(10.dp)
            ) {
                if (projects.isEmpty()) {
                    item {
                        Text("Aucun glossaire disponible")
                    }
                } else {
                    items(projects) { project ->
                        Row(
                            modifier = Modifier.width(200.dp).fillMaxWidth(),
                            horizontalArrangement = Arrangement.SpaceBetween,
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            buttonComponent(project.name, { onProjectSelected(project) }, width = 200)
                        }
                    }
                }
            }
            VerticalScrollbar(
                modifier = Modifier.align(Alignment.CenterEnd).fillMaxHeight(),
                adapter = rememberScrollbarAdapter(scrollState)
            )
            Spacer(modifier = Modifier.height(6.dp))
        }
        Spacer(modifier = Modifier.height(16.dp))

        buttonComponent("Retour", onBackClick)
    }
    dropdownButtonComponent(
        languageManager,
        items = listOf("Glossaire", "Code à vérifier", "Comparer")
    ) { selectedOption ->
        // Handle the selected option
        when (selectedOption) {
            "Glossaire" -> onProjectClick()
            "Code à vérifier" -> onCodeToVerifyClick()
            "Comparer" -> {
                if (mostUsedWordList.isEmpty()) {
                    noFileSnackbarVisibleState.value = true
                    return@dropdownButtonComponent
                } else {
                    isCompareClicked = true
                }
            }
        }
    }
}