package main

import androidx.compose.foundation.VerticalScrollbar
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.foundation.rememberScrollbarAdapter
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Delete
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.key.*
import androidx.compose.ui.unit.dp
import main.component.dropdownButtonComponent
import java.io.File

data class Project(val name: String)

fun loadProjects(): List<Project> {
    val projectsDirectory = File("src/main/resources/projects/")

    return projectsDirectory.listFiles()?.map { Project(it.name) } ?: emptyList()
}

@Composable
fun projectsPage(
    languageManager: LanguageManager,
    currentPage: MutableState<String>,
    onProjectClick: () -> Unit,
    onCodeToVerifyClick: () -> Unit
) {
    val noFileSnackbarVisibleState = remember { mutableStateOf(false) }
    var projects: List<Project> by remember { mutableStateOf(loadProjects()) }
    var isCompareClicked by remember { mutableStateOf(false) }

    Column(
        modifier = Modifier.fillMaxSize(),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {

        Text(languageManager.getSelectProjectText(), style = MaterialTheme.typography.h5)

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

        Box(
            modifier = Modifier
                .height(300.dp)
                .width(250.dp)
                .padding(10.dp),
            contentAlignment = Alignment.Center
        ) {
            val scrollState = rememberLazyListState()
            projects = loadProjects()
            if (projects.isEmpty()) {
                    Text(languageManager.getNoProjectText())
            } else {
                LazyColumn(
                    state = scrollState,
                    modifier = Modifier.padding(10.dp),
                    verticalArrangement = Arrangement.spacedBy(10.dp)
                ) {
                    println(projects)
                    items(projects) { project ->
                        Row(
                            modifier = Modifier.width(200.dp).fillMaxWidth(),
                            horizontalArrangement = Arrangement.SpaceBetween
                        ) {
                            Button(
                                onClick = {
                                    appState.selectedProject = project
                                    currentPage.value = "glossaires"
                                },
                                modifier = Modifier
                                    .width(150.dp),
                                colors = ButtonDefaults.buttonColors(
                                    backgroundColor = customRedColor,
                                    contentColor = Color.White
                                )
                            ) {
                                Text(project.name)
                            }

                            IconButton(
                                onClick = {
                                    // Handle delete glossary action
                                    projects = projects.filterNot { it == project }
                                    val directory = File("src/main/resources/projects/${project.name}/")
                                    directory.deleteRecursively()
                                    currentPage.value = "projects"
                                }
                            ) {
                                Icon(
                                    imageVector = Icons.Default.Delete,
                                    contentDescription = "Delete Project"
                                )
                            }
                        }
                    }
                }
            }
            VerticalScrollbar(
                modifier = Modifier.align(Alignment.CenterEnd).fillMaxHeight(),
                adapter = rememberScrollbarAdapter(scrollState)
            )
        }

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

        Button(
            onClick = {
                currentPage.value = "nouveauProjet"
            },
            modifier = Modifier
                .width(300.dp),
            colors = ButtonDefaults.buttonColors(
                backgroundColor = customRedColor,
                contentColor = Color.White
            )
        ) {
            Text(languageManager.getNewProjectText())
        }

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

        Button(
            onClick = {
                currentPage.value = "accueil"
            },
            modifier = Modifier
                .width(250.dp),
            colors = 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
                }
            }
        }
    }
}

@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun newProject(
    languageManager: LanguageManager,
    currentPage: MutableState<String>
){
    var projectName by remember { mutableStateOf("") }

    val isEmptySnackbarVisibleState = remember { mutableStateOf(false) }
    val containsSpaceSnackbarVisibleState = remember { mutableStateOf(false) }
    val glossaryAlreadyExistsSnackbarVisibleState = remember { mutableStateOf(false) }
    val invalidCharacterSnackbarVisibleState = remember { mutableStateOf(false) }

    Column(
        modifier = Modifier.fillMaxSize(),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ){
        Text(languageManager.getNameProjectText(), style = MaterialTheme.typography.h5)

        Spacer(modifier = Modifier.height(16.dp))
        val projectsList = loadProjects()

        TextField(
            value = projectName,
            singleLine = true,
            onValueChange = { projectName = it },
            label = { Text(languageManager.getNameProjectText()) },
            colors = TextFieldDefaults.textFieldColors(
                focusedIndicatorColor = customRedColor,
                unfocusedIndicatorColor = Color.Gray,
                focusedLabelColor = customRedColor
            ),
            modifier = Modifier
                .width(300.dp)
                .fillMaxWidth()
                .onKeyEvent { event ->
                    if (event.key == Key.Enter && event.type == KeyEventType.KeyDown) {
                        if (projectName.isEmpty()) {
                            println(languageManager.getEnterProjectNameText())
                            isEmptySnackbarVisibleState.value = true
                        } else if (projectName.contains(" ")) {
                            println(languageManager.getNoSpaceInProjectNameText())
                            containsSpaceSnackbarVisibleState.value = true
                        } else if (projectsList.any { it.name == projectName }) {
                            println(languageManager.getGlossaryAlreadyExistsText())
                            glossaryAlreadyExistsSnackbarVisibleState.value = true
                        } else if (!isValidFileName(projectName)) {
                            println(languageManager.getInvalidCharacterText())
                            invalidCharacterSnackbarVisibleState.value = true
                        } else {
                            val directory = File("src/main/resources/projects/$projectName/")
                            directory.mkdirs()
                            println("Project $projectName created")
                            currentPage.value = "projects"
                        }
                        true
                    } else {
                        false
                    }
                }
        )

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

        Button(
            onClick = {
                if (projectName.isEmpty()) {
                    println(languageManager.getEnterProjectNameText())
                    isEmptySnackbarVisibleState.value = true
                } else if (projectName.contains(" ")) {
                    println(languageManager.getNoSpaceInProjectNameText())
                    containsSpaceSnackbarVisibleState.value = true
                } else if (projectsList.any { it.name == projectName }) {
                    println(languageManager.getGlossaryAlreadyExistsText())
                    glossaryAlreadyExistsSnackbarVisibleState.value = true
                } else if (!isValidFileName(projectName)) {
                    println(languageManager.getInvalidCharacterText())
                    invalidCharacterSnackbarVisibleState.value = true
                } else {
                    val directory = File("src/main/resources/projects/$projectName/")
                    directory.mkdirs()
                    println("Project $projectName created")
                    currentPage.value = "projects"
                }
            },
            modifier = Modifier
                .width(300.dp),
            colors = ButtonDefaults.buttonColors(
                backgroundColor = customRedColor,
                contentColor = Color.White
            )
        ) {
            Text(languageManager.getCreateProjectText().toString())
        }

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

        Button(
            onClick = {
                currentPage.value = "projects"
            },
            modifier = Modifier
                .width(250.dp),
            colors = ButtonDefaults.buttonColors(
                backgroundColor = customRedColor,
                contentColor = Color.White
            )
        ) {
            Text(languageManager.getBackText())
        }

        if (isEmptySnackbarVisibleState.value) {
            Snackbar(
                modifier = Modifier.padding(16.dp),
                action = {
                    Button(
                        onClick = { isEmptySnackbarVisibleState.value = false },
                        colors = ButtonDefaults.buttonColors(
                            backgroundColor = customRedColor,
                            contentColor = Color.White
                        )
                    ) {
                        Text("OK")
                    }
                }
            ) {
                Text(languageManager.getEnterProjectNameText().toString())
            }
        }
        if (containsSpaceSnackbarVisibleState.value) {
            Snackbar(
                modifier = Modifier.padding(16.dp),
                action = {
                    Button(
                        onClick = { containsSpaceSnackbarVisibleState.value = false },
                        colors = ButtonDefaults.buttonColors(
                            backgroundColor = customRedColor,
                            contentColor = Color.White
                        )
                    ) {
                        Text("OK")
                    }
                }
            ) {
                Text(languageManager.getNoSpaceInProjectNameText().toString())
            }
        }
        if (glossaryAlreadyExistsSnackbarVisibleState.value) {
            Snackbar(
                modifier = Modifier.padding(16.dp),
                action = {
                    Button(
                        onClick = { glossaryAlreadyExistsSnackbarVisibleState.value = false },
                        colors = ButtonDefaults.buttonColors(
                            backgroundColor = customRedColor,
                            contentColor = Color.White
                        )
                    ) {
                        Text("OK")
                    }
                }
            ) {
                Text(languageManager.getGlossaryAlreadyExistsText().toString())
            }
        }
        if (invalidCharacterSnackbarVisibleState.value) {
            Snackbar(
                modifier = Modifier.padding(16.dp),
                action = {
                    Button(
                        onClick = { invalidCharacterSnackbarVisibleState.value = false },
                        colors = ButtonDefaults.buttonColors(
                            backgroundColor = customRedColor,
                            contentColor = Color.White
                        )
                    ) {
                        Text("OK")
                    }
                }
            ) {
                Text(languageManager.getInvalidCharacterText().toString())
            }
        }
    }
}




