package mg.dot.feufaro.ui

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.KeyboardBackspace
import androidx.compose.material.icons.automirrored.filled.KeyboardTab
import androidx.compose.material.icons.filled.Build
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material.icons.filled.Save
import androidx.compose.material3.*
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.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import mg.dot.feufaro.solfa.Transpose

enum class OctaveMode {
    LOWER, NORMAL, UPPER
}
val SOLFA_NOTES = Transpose.noteToNumber

@Composable
fun SolfaKeyboard(
    currentVoiceIndex: Int,
    currentValue: String = "",
    onNoteClick: (String) -> Unit,
    onTabClick: () -> Unit,
    onBackspaceClick: () -> Unit,
    onBuildClick: () -> Unit,
    onCloseClick: () -> Unit,
    onCustomSymbolClick: (String) -> Unit,
    modifier: Modifier = Modifier
) {
    var selectedOctave by remember { mutableStateOf("") }
    val voiceLabels = listOf("S", "A", "T", "B")

    Surface(
        modifier = modifier
            .fillMaxWidth()
            .background(Color(0xFF232323)),
        color = Color(0xFF232323),
        tonalElevation = 8.dp
    ) {
        Row(
            modifier = Modifier
                .padding(6.dp)
                .fillMaxWidth(),
            horizontalArrangement = Arrangement.spacedBy(5.dp)
        ) {
            Column(
                modifier = Modifier.weight(1f),
                verticalArrangement = Arrangement.spacedBy(5.dp)
            ) {
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(4.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Button(
                        onClick = onTabClick,
                        colors = ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.primary),
                        shape = RoundedCornerShape(4.dp),
                        contentPadding = PaddingValues(horizontal = 6.dp, vertical = 2.dp),
                        modifier = Modifier.height(36.dp)
                    ) {
                        Icon(
                            imageVector = Icons.AutoMirrored.Default.KeyboardTab,
                            contentDescription = null,
                            modifier = Modifier.size(18.dp)
                        )
                        Spacer(Modifier.width(2.dp))
                        Text(
                            text = voiceLabels.getOrElse(currentVoiceIndex) { "S" },
                            fontSize = 11.sp,
                            fontWeight = FontWeight.Bold
                        )
                    }

                    BasicTextField(
                        value = currentValue,
                        onValueChange = {},
                        readOnly = true,
                        textStyle = TextStyle(
                            color = Color.White,
                            fontSize = 13.sp,
                            fontWeight = FontWeight.Medium
                        ),
                        modifier = Modifier
                            .weight(1.5f)
                            .height(36.dp)
                            .background(Color.Black.copy(alpha = 0.4f), RoundedCornerShape(4.dp))
                            .padding(horizontal = 8.dp, vertical = 8.dp)
                    )

                    OutlinedButton(
                        onClick = {
                            onNoteClick(",")
                        },
                        colors = ButtonDefaults.buttonColors(
                            containerColor = Color(0xFF383838)
                        ),
                        modifier = Modifier.height(36.dp).weight(0.7f)
                    ) {
                        Text(",", fontSize = 14.sp, fontWeight = FontWeight.Bold)
                    }
                    OutlinedButton(
                        onClick = {
                            onNoteClick("'")
                        },
                        colors = ButtonDefaults.buttonColors(
                            containerColor = Color(0xFF383838)
                        ),
                        modifier = Modifier.height(36.dp)
                    ) {
                        Text("'", fontSize = 14.sp, fontWeight = FontWeight.Bold)
                    }
                }

                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(4.dp)
                ) {
                    Spacer(modifier = Modifier.weight(0.5f))
                    KeyButton("di", Modifier.weight(1f)) { onNoteClick("di") }
                    KeyButton("ri", Modifier.weight(1f)) { onNoteClick("ri") }
                    Spacer(modifier = Modifier.weight(1.3f))
                    KeyButton("fi", Modifier.weight(1f)) { onNoteClick("fi") }
                    KeyButton("si", Modifier.weight(1f)) { onNoteClick("si") }
                    KeyButton("ta", Modifier.weight(1f)) { onNoteClick("ta") }
                    Spacer(modifier = Modifier.weight(0.5f))
                }

                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(4.dp)
                ) {
                    val diatonicNotes = listOf("d", "r", "m", "f", "s", "l", "t")
                    for (note in diatonicNotes) {
                        KeyButton(note, Modifier.weight(1f)) { onNoteClick(note) }
                    }
                }

                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(4.dp)
                ) {
                    KeyButton("―", Modifier.weight(1f)) { onCustomSymbolClick("-") }
                    KeyButton("• ，", Modifier.weight(1f)) { onCustomSymbolClick(";") }
                    KeyButton("•", Modifier.weight(0.5f)) { onCustomSymbolClick(".") }
                    KeyButton("，", Modifier.weight(0.5f)) { onCustomSymbolClick(" ,") }
                    KeyButton("Espace", Modifier.weight(1.6f)) { onCustomSymbolClick(" ") }
                    KeyButton("(", Modifier.weight(0.6f)) { onCustomSymbolClick("(") }
                    KeyButton(")", Modifier.weight(0.6f)) { onCustomSymbolClick(")") }
                    KeyButton("<", Modifier.weight(0.5f)) { onCustomSymbolClick("<") }
                    KeyButton(">", Modifier.weight(0.5f)) { onCustomSymbolClick(">") }
                    KeyButton("z", Modifier.weight(1f)) { onNoteClick("z") }
                }
            }

            Column(
                modifier = Modifier
                    .width(48.dp),
                verticalArrangement = Arrangement.spacedBy(4.dp)
            ) {
                Button(
                    onClick = onCloseClick,
                    modifier = Modifier
                        .fillMaxWidth()
                        .weight(1f),
                    shape = RoundedCornerShape(4.dp),
                    colors = ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.errorContainer),
                    contentPadding = PaddingValues(0.dp)
                ) {
                    Icon(
                        imageVector = Icons.Default.Close,
                        contentDescription = null,
                        tint = MaterialTheme.colorScheme.onErrorContainer
                    )
                }

                Button(
                    onClick = onBackspaceClick,
                    modifier = Modifier
                        .fillMaxWidth()
                        .weight(1f),
                    shape = RoundedCornerShape(4.dp),
                    colors = ButtonDefaults.buttonColors(containerColor = Color(0xFF4A4A4A)),
                    contentPadding = PaddingValues(0.dp)
                ) {
                    Icon(
                        imageVector = Icons.AutoMirrored.Default.KeyboardBackspace,
                        contentDescription = null,
                        tint = Color.White
                    )
                }

                Button(
                    onClick = onBuildClick,
                    modifier = Modifier
                        .fillMaxWidth()
                        .weight(1.2f),
                    shape = RoundedCornerShape(4.dp),
                    colors = ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.primary),
                    contentPadding = PaddingValues(0.dp)
                ) {
                    Icon(
                        imageVector = Icons.Default.Save,
                        contentDescription = null,
                        tint = Color.White
                    )
                }
            }
        }
    }
}

@Composable
private fun KeyButton(
    text: String,
    modifier: Modifier = Modifier,
    containerColor: Color = Color(0xFF383838),
    onClick: () -> Unit
) {
    Button(
        onClick = onClick,
        modifier = modifier.height(49.dp),
        shape = RoundedCornerShape(4.dp),
        colors = ButtonDefaults.buttonColors(containerColor = containerColor),
        contentPadding = PaddingValues(0.dp)
    ) {
        Text(
            text = text,
            color = Color.White,
            fontSize = 14.sp,
            fontWeight = FontWeight.Bold
        )
    }
}

class SolfaKeyboardState {
    var isVisible by mutableStateOf(false)
        private set

    var isDialogActive by mutableStateOf(false)
    var activeVoiceIndex by mutableStateOf(0)
        private set

    var currentText by mutableStateOf("")
    var onNoteInput: ((String) -> Unit)? = null
    var onBackspace: (() -> Unit)? = null
    var onCloseDialog: (() -> Unit)? = null
    var onBuildEdit: (() -> Unit)? = null
    var onCustomSymbol: ((String) -> Unit)? = null
    var onTabNextVoice: (() -> Unit)? = null
    var onMarker: (() -> Unit)? = null

    fun show(
        initialVoice: Int = 0,
        initialValue: String = "",
        onNote: (String) -> Unit,
        onDelete: () -> Unit,
        onSymbol: (String) -> Unit,
        onBuild: () -> Unit,
        onClose: () -> Unit,
        onTab: () -> Unit
    ) {
        if (!isDialogActive) return
        activeVoiceIndex = initialVoice
        onNoteInput = onNote
        onBackspace = onDelete
        onCustomSymbol = onSymbol
        onCloseDialog = onClose
        onBuildEdit = onBuild
        onTabNextVoice = onTab
        isVisible = true
    }

    fun hide() {
        isVisible = false
    }
}

@Composable
fun rememberSolfaKeyboardState() = remember { SolfaKeyboardState() }

val LocalSolfaKeyboardState = staticCompositionLocalOf <SolfaKeyboardState> {
    error("Aucun SolfaKeyboardState fourni")
}