package mg.dot.feufaro.ui

import SharedScreenModel
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.*
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.Undo
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.DarkMode
import androidx.compose.material.icons.filled.KeyboardArrowDown
import androidx.compose.material.icons.filled.LightMode
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.DialogProperties
import com.russhwolf.settings.Settings
import feufaro.composeapp.generated.resources.Emmentaler
import feufaro.composeapp.generated.resources.Res
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import mg.dot.feufaro.DisplayConfigManager
import mg.dot.feufaro.getPlatform
import mg.dot.feufaro.midi.Dynamic
import mg.dot.feufaro.midi.MidiInstrument
import mg.dot.feufaro.provideSettings
import org.jetbrains.compose.resources.Font
import org.koin.compose.koinInject

@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class)
@Composable
fun Settings(
    sharedScreenModel: SharedScreenModel,
    onDismissRequest: () -> Unit,
    expandedDropdownN: Boolean,
    isAndroid: Boolean
) {
    val prefs: Settings = provideSettings()
    var hasCountIn by remember { mutableStateOf(prefs.getBoolean("isCountIn", true)) }
    var isDynamicEnabled by remember { mutableStateOf(Dynamic.isGloballyEnabled) }
    var refreshTrigger by remember { mutableStateOf(0) }
    val isFullScreenEnabled by sharedScreenModel.isFullScreen.collectAsState()
    val platform = getPlatform()
    val isAndroid = platform.name.startsWith("Android")

    // Load Configurations
    val displayConfigManager = koinInject<DisplayConfigManager>()
    val currentDisplayConfig by displayConfigManager.displayConfig.collectAsState()

    val currentTheme = currentDisplayConfig.themeMode
    val isDarkModeActive = currentTheme == "DARK"
    val configScope = CoroutineScope(Dispatchers.Default)

    var tempDarkMode by remember(currentDisplayConfig.themeMode) {
        mutableStateOf(currentDisplayConfig.themeMode == "DARK")
    }
    var tempFontSize by remember(currentDisplayConfig.fontSize) {
        mutableStateOf(currentDisplayConfig.fontSize)
    }

    var emmentaler = FontFamily(Font(Res.font.Emmentaler))
    val player = sharedScreenModel.mediaPlayer
    var expandedAudio by remember { mutableStateOf(player?.getCurrentPosition() != 0L) }
    var expandedGeneral by remember { mutableStateOf(true) }

    fun openExclusive(target: String) {
        expandedGeneral = (target == "General")
        expandedAudio = (target == "Audio")
    }

    val instruments = remember { player?.getAvalaibleInstruments() ?: emptyList() }
    var globalInstrumentProgram by remember {
        mutableStateOf(player?.getVoiceInstrument() ?: 1)
    }
    val selectedInstrument = instruments.find { it.program == globalInstrumentProgram }
        ?: MidiInstrument(program = globalInstrumentProgram, name = "Instrument $globalInstrumentProgram")

    val menuScrollState = rememberScrollState()
    var expandedDropdown by remember { mutableStateOf(false) }

    LaunchedEffect(expandedDropdown, globalInstrumentProgram) {
        if (expandedDropdown) {
            val selectedIndex = instruments.indexOfFirst { it.program == globalInstrumentProgram }
            if (selectedIndex != -1) {
                val itemHeightPx = 16 * 3

                kotlinx.coroutines.yield()
                menuScrollState.scrollTo(selectedIndex * itemHeightPx)
            }
        }
    }

    AlertDialog(
        properties = DialogProperties(
            usePlatformDefaultWidth = false
        ),
        modifier = Modifier
            .fillMaxWidth(if(isAndroid) 0.9f else 0.55f),
        onDismissRequest = onDismissRequest,
        title = {
            Text(
                text = "Paramètres",
                fontWeight = FontWeight.Black,
                fontSize = 22.sp
            )
        },
        text = {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .verticalScroll(rememberScrollState()),
                verticalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant)

                SettingsAccordion(
                    title = "Paramètres Général",
                    isExpanded = expandedGeneral,
                    onToggle = {
                        openExclusive("General")
                    }
                ) {
                    Column(
                        modifier = Modifier.padding(16.dp),
                        verticalArrangement = Arrangement.spacedBy(8.dp)
                    ) {
                        if(isAndroid) {
                            Row(
                                modifier = Modifier.fillMaxWidth(),
                                horizontalArrangement = Arrangement.SpaceBetween,
                                verticalAlignment = Alignment.CenterVertically
                            ) {
                                Text(
                                    text = "Mode Plein Écran",
                                    style = MaterialTheme.typography.bodyMedium,
                                    color = MaterialTheme.colorScheme.onSurface
                                )
                                Switch(
                                    checked = isFullScreenEnabled,
                                    onCheckedChange = { isChecked ->
                                        sharedScreenModel.toggleFullScreen(isChecked)
                                    }
                                )
                            }
                        }

                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(vertical = 4.dp),
                            horizontalArrangement = Arrangement.SpaceBetween,
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Text(
                                text = "Thème Sombre",
                                style = MaterialTheme.typography.bodyMedium,
                                color = MaterialTheme.colorScheme.onSurface
                            )

                            Switch(
                                checked = tempDarkMode,
                                onCheckedChange = { checked ->
                                    val newMode = if (checked) "DARK" else "LIGHT"
                                    displayConfigManager.updateThemeMode(newMode)
                                },
                                thumbContent = {
                                    Icon(
                                        imageVector = if (tempDarkMode) Icons.Default.DarkMode else Icons.Default.LightMode,
                                        contentDescription = null,
                                        tint = MaterialTheme.colorScheme.onSecondary
                                    )
                                },
                                colors = SwitchDefaults.colors(
                                    checkedThumbColor = MaterialTheme.colorScheme.primary,
                                    checkedTrackColor = MaterialTheme.colorScheme.primary.copy(alpha = 0.4f),
                                    uncheckedThumbColor = MaterialTheme.colorScheme.error,
                                    uncheckedTrackColor = MaterialTheme.colorScheme.error.copy(alpha = 0.2f),
                                    checkedBorderColor = Color.Transparent,
                                    uncheckedBorderColor = Color.Transparent,
                                    checkedIconColor = Color.White,
                                    uncheckedIconColor = MaterialTheme.colorScheme.onTertiary,
                                )
                            )
                        }

                        HorizontalDivider(color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f))

                        Column(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(vertical = 8.dp),
                            verticalArrangement = Arrangement.spacedBy(8.dp)
                        ) {
                            Text(
                                text = "Taille de la police",
                                style = MaterialTheme.typography.bodyMedium,
                                color = MaterialTheme.colorScheme.onSurface
                            )

                            Row(
                                modifier = Modifier.fillMaxWidth(),
                                verticalAlignment = Alignment.CenterVertically,
                                horizontalArrangement = Arrangement.Center
                            ) {
                                IconButton(
                                    onClick = {
                                        if (currentDisplayConfig.fontSize > 8f) {
                                            displayConfigManager.updateFontSize(currentDisplayConfig.fontSize - 0.5f)
                                        }
                                    },
                                    modifier = Modifier.size(32.dp).background(MaterialTheme.colorScheme.primary, CircleShape)
                                ) {
                                    Text("-", fontWeight = FontWeight.Bold, style = MaterialTheme.typography.titleLarge, color = Color.White)
                                }

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

                                OutlinedTextField(
                                    value = tempFontSize.toString(),
                                    onValueChange = {},
                                    readOnly = true,
                                    textStyle = MaterialTheme.typography.titleMedium.copy(textAlign = TextAlign.Center),
                                    modifier = Modifier.width(80.dp),
                                    shape = RoundedCornerShape(12.dp)
                                )

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

                                IconButton(
                                    onClick = {
                                        if (currentDisplayConfig.fontSize < 30f) {
                                            displayConfigManager.updateFontSize(currentDisplayConfig.fontSize + 0.5f)
                                        }
                                    },
                                    modifier = Modifier.size(32.dp).background(MaterialTheme.colorScheme.primary, CircleShape)
                                ) {
                                    Text("+", fontWeight = FontWeight.Bold, style = MaterialTheme.typography.titleLarge, color = Color.White)
                                }
                            }
                        }

                        HorizontalDivider(color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f))

                        Column(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(vertical = 8.dp),
                            verticalArrangement = Arrangement.spacedBy(12.dp)
                        ) {
                            Text(
                                text = "Personnalisation des couleurs",
                                style = MaterialTheme.typography.bodyLarge,
                                color = MaterialTheme.colorScheme.onSurface,
                                fontWeight = FontWeight.Bold
                            )

                            val colorPickers = listOf(
                                Triple("Couleur Primaire", "primaryBlueHex", currentDisplayConfig.primaryBlueHex),
                                Triple("Couleur Secondaire", "accentGreenHex", currentDisplayConfig.accentGreenHex),
                                Triple("Couleur Tertiaire", "accentYellowHex", currentDisplayConfig.accentYellowHex),
                                Triple("Autre couleur", "accentPinkHex", currentDisplayConfig.accentPinkHex)
                            )

                            val availableColors = ThemeDefaults.availableColors

                            colorPickers.forEach { (label, configKey, currentHex) ->
                                var showLocalPicker by remember { mutableStateOf(false) }

                                Column(modifier = Modifier.fillMaxWidth()) {
                                    Row(
                                        modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp),
                                        horizontalArrangement = Arrangement.SpaceBetween,
                                        verticalAlignment = Alignment.CenterVertically
                                    ) {
                                        Text(label, style = MaterialTheme.typography.bodyMedium)

                                        Box(
                                            modifier = Modifier
                                                .size(36.dp)
                                                .clip(CircleShape)
                                                .background(currentHex.toColorOrDefault(Color.Gray))
                                                .border(2.dp, MaterialTheme.colorScheme.outline, CircleShape)
                                                .clickable { showLocalPicker = !showLocalPicker }
                                        )
                                    }

                                    AnimatedVisibility(visible = showLocalPicker) {
                                        FlowRow(
                                            modifier = Modifier
                                                .fillMaxWidth()
                                                .background(MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.3f), RoundedCornerShape(8.dp))
                                                .padding(12.dp),
                                            horizontalArrangement = Arrangement.spacedBy(10.dp),
                                            verticalArrangement = Arrangement.spacedBy(10.dp)
                                        ) {
                                            availableColors.forEach { colorHex ->
                                                Box(
                                                    modifier = Modifier
                                                        .size(32.dp)
                                                        .clip(CircleShape)
                                                        .background(colorHex.toColorOrDefault(Color.Gray))
                                                        .border(
                                                            width = if (currentHex.uppercase() == colorHex.uppercase()) 2.5.dp else 0.dp,
                                                            color = MaterialTheme.colorScheme.onSurface,
                                                            shape = CircleShape
                                                        )
                                                        .clickable {
                                                            displayConfigManager.updateCustomColor(configKey, colorHex)
                                                        }
                                                )
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        Spacer(modifier = Modifier.weight(1f))
                        OutlinedButton(
                            onClick = { displayConfigManager.resetToDefault() },
                            modifier = Modifier.fillMaxWidth(),
                            shape = RoundedCornerShape(12.dp),
                            colors = ButtonDefaults.outlinedButtonColors(
                                contentColor = MaterialTheme.colorScheme.error
                            )
                        ) {
                            Text("Réinitialiser", style = MaterialTheme.typography.labelLarge)
                        }
                    }
                }

                SettingsAccordion(
                    title = "Paramètres Audio & Nuances",
                    isExpanded = expandedAudio,
                    onToggle = {
                        openExclusive("Audio")
                    }
                ) {
                    Column(modifier = Modifier.padding(top = 8.dp),
                        verticalArrangement = Arrangement.spacedBy(2.dp)
                    ) {
                        Text(
                            text = "Réglage de la nuance",
                            style = MaterialTheme.typography.titleMedium,
                            fontWeight = FontWeight.Bold,
                            color = MaterialTheme.colorScheme.onSurface
                        )
                        Surface(
                            shape = RoundedCornerShape(12.dp),
                            color = MaterialTheme.colorScheme.surfaceContainerLow,
                            modifier = Modifier.fillMaxWidth()
                        ) {
                            Row(
                                modifier = Modifier.fillMaxWidth()
                                    .padding(horizontal = 16.dp, vertical = 8.dp),
                                horizontalArrangement = Arrangement.SpaceBetween,
                                verticalAlignment = Alignment.CenterVertically
                            ) {
                                Row(
                                    verticalAlignment = Alignment.CenterVertically,
                                    horizontalArrangement = Arrangement.spacedBy(5.dp)
                                ) {
                                    Switch(
                                        checked = isDynamicEnabled,
                                        onCheckedChange = { enabled ->
                                            isDynamicEnabled = enabled
                                            Dynamic.isGloballyEnabled = enabled
                                            refreshTrigger++
                                        }
                                    )
                                    Text(
                                        text = if (isDynamicEnabled) "Désactiver" else "Activer",
                                        style = MaterialTheme.typography.bodyMedium,
                                        color = MaterialTheme.colorScheme.onSurface
                                    )
                                }

                                OutlinedButton(
                                    onClick = {
                                        Dynamic.resetToDefaults()
                                        isDynamicEnabled = true
                                        refreshTrigger++
                                    },
                                    shape = RoundedCornerShape(8.dp),
                                    colors = ButtonDefaults.outlinedButtonColors(
                                        contentColor = MaterialTheme.colorScheme.error
                                    ),
                                    contentPadding = PaddingValues(horizontal = 16.dp, vertical = 8.dp)
                                ) {
                                    Icon(
                                        imageVector = Icons.AutoMirrored.Default.Undo,
                                        contentDescription = null,
                                        tint = MaterialTheme.colorScheme.error
                                    )
                                }
                            }
                        }


                        key(refreshTrigger) {
                            val dynamicEntries = Dynamic.entries
                            val minF = 0.22f
                            val maxF = 2.33f
                            val step = 0.05f

                            Box(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .background(Color(0xFF121212).copy(alpha = 0.6f), RoundedCornerShape(16.dp))
                                    .padding(8.dp),
                                contentAlignment = Alignment.Center
                            ) {
                                Column(
                                    horizontalAlignment = Alignment.CenterHorizontally,
                                    modifier = Modifier.fillMaxWidth(),
                                    verticalArrangement = Arrangement.spacedBy(0.dp)
                                ) {
                                    dynamicEntries.forEachIndexed { index, dynamicItem ->
                                        Row(
                                            verticalAlignment = Alignment.CenterVertically,
                                            horizontalArrangement = Arrangement.spacedBy(1.dp),
                                            modifier = Modifier.padding(vertical = 0.dp)
                                        ) {
                                            // (-)
                                            if(index == 0) {
                                                FilledIconButton(
                                                    onClick = {
                                                        if (isDynamicEnabled) {
                                                            val delta = - step
                                                            var insideBounds = true
                                                            dynamicEntries.forEach { item ->
                                                                val projectedValue = item.savedFactor + delta
                                                                if (projectedValue < minF || projectedValue > maxF) {
                                                                    insideBounds = false
                                                                }
                                                            }
                                                            if (insideBounds) {
                                                                dynamicEntries.forEach { item ->
                                                                    item.savedFactor = (item.savedFactor + delta).coerceIn(minF, maxF)
                                                                }
                                                                refreshTrigger++
                                                            }
                                                        }
                                                    },
                                                    enabled = isDynamicEnabled,
                                                    colors = IconButtonDefaults.filledIconButtonColors(
                                                        containerColor = Color(0xFF2C2C2C),
                                                        contentColor = Color.White
                                                    ),
                                                    modifier = Modifier.size(32.dp)
                                                ) {
                                                    Text("-", fontWeight = FontWeight.Bold, fontSize = 16.sp)
                                                }
                                            } else {
                                                Spacer(modifier = Modifier.width(32.dp))
                                            }
                                            Text(
                                                text = dynamicItem.label.lowercase(),
                                                style = MaterialTheme.typography.displaySmall.copy(
                                                    fontFamily = emmentaler
                                                ),
                                                fontWeight = FontWeight.Bold,
                                                color = if (isDynamicEnabled) MaterialTheme.colorScheme.onSecondary else Color.Gray,
                                                textAlign = TextAlign.Center,
                                                modifier = Modifier.width(30.dp)
                                            )

                                            Slider(
                                                value = dynamicItem.savedFactor,
                                                onValueChange = { newValue ->
                                                    if (isDynamicEnabled) {
                                                        val oldValue = dynamicItem.savedFactor
                                                        val delta = newValue - oldValue
                                                        var insideBounds = true

                                                        dynamicEntries.forEach { item ->
                                                            val projectedValue = item.savedFactor + delta
                                                            if (projectedValue < minF || projectedValue > maxF) {
                                                                insideBounds = false
                                                            }
                                                        }

                                                        if (insideBounds) {
                                                            dynamicEntries.forEach { item ->
                                                                item.savedFactor = (item.savedFactor + delta).coerceIn(minF, maxF)
                                                            }
                                                            refreshTrigger++
                                                        }
                                                    }
                                                },
                                                valueRange = minF..maxF,
                                                enabled = isDynamicEnabled,
                                                track = { sliderState ->
                                                    SliderDefaults.Track(
                                                        sliderState = sliderState,
                                                        enabled = isDynamicEnabled,
                                                        colors = SliderDefaults.colors(
                                                            activeTrackColor = if (isDynamicEnabled) Color.Blue else Color.Gray,
                                                            inactiveTrackColor = Color.LightGray
                                                        ),
                                                        modifier = Modifier.height(6.dp)
                                                    )
                                                },
                                                thumb = {
                                                    SliderDefaults.Thumb(
                                                        interactionSource = remember { MutableInteractionSource() },
                                                        colors = SliderDefaults.colors(thumbColor = if(isDynamicEnabled) Color(0xFFFF4081) else Color.LightGray),
                                                        modifier = Modifier.size(12.dp),
                                                    )
                                                },
                                                colors = SliderDefaults.colors(
                                                    activeTrackColor = Color(0xFF7C4DFF),
                                                    inactiveTrackColor = Color(0xFF2C2C2C)
                                                ),
                                                modifier = Modifier
                                                    .weight(1f)
                                                    .padding(horizontal = 8.dp)
                                                    .height(16.dp)
                                            )

                                            Text(
                                                text = String.format("%.2f", if (isDynamicEnabled) dynamicItem.savedFactor else 1.00f),
                                                fontSize = 11.sp,
                                                fontWeight = FontWeight.Bold,
                                                color = if (isDynamicEnabled) Color(0xFFDEFF9A) else Color.DarkGray,
                                                textAlign = TextAlign.Center,
                                                modifier = Modifier.width(30.dp)
                                            )

                                            //  (+)
                                            if(index == 0) {
                                                FilledIconButton(
                                                    onClick = {
                                                        if (isDynamicEnabled) {
                                                            val delta = step
                                                            var insideBounds = true
                                                            dynamicEntries.forEach { item ->
                                                                val projectedValue = item.savedFactor + delta
                                                                if (projectedValue < minF || projectedValue > maxF) {
                                                                    insideBounds = false
                                                                }
                                                            }
                                                            if (insideBounds) {
                                                                dynamicEntries.forEach { item ->
                                                                    item.savedFactor =
                                                                        (item.savedFactor + delta).coerceIn(minF, maxF)
                                                                }
                                                                refreshTrigger++
                                                            }
                                                        }
                                                    },
                                                    enabled = isDynamicEnabled,
                                                    colors = IconButtonDefaults.filledIconButtonColors(
                                                        containerColor = Color(0xFF2C2C2C),
                                                        contentColor = Color.White
                                                    ),
                                                    modifier = Modifier.size(32.dp)
                                                ) {
                                                    Text("+", fontWeight = FontWeight.Bold, fontSize = 16.sp)
                                                }
                                            } else {
                                                Spacer(modifier = Modifier.width(32.dp))
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        HorizontalDivider(
                            color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.2f),
                            modifier = Modifier.padding(vertical = 12.dp)
                        )

                        Text(
                            text = "Règlage des Instruments",
                            style = MaterialTheme.typography.bodyLarge,
                            fontWeight = FontWeight.Bold,
                            color = MaterialTheme.colorScheme.onSurface,
                            modifier = Modifier.padding(bottom = 8.dp)
                        )
                        val currentProgram = 0
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(vertical = 4.dp),
                            horizontalArrangement = Arrangement.SpaceBetween,
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            ExposedDropdownMenuBox(
                                expanded = expandedDropdown,
                                onExpandedChange = { expandedDropdown = !expandedDropdown },
                                modifier = Modifier.weight(1f)
                            ) {
                                OutlinedTextField(
                                    value = "${selectedInstrument.icon} - ${selectedInstrument.name}",
                                    onValueChange = {},
                                    readOnly = true,
                                    trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = expandedDropdown) },
                                    colors = ExposedDropdownMenuDefaults.outlinedTextFieldColors(),
                                    modifier = Modifier.menuAnchor(type = MenuAnchorType.PrimaryEditable, true).fillMaxWidth(),
                                    textStyle = MaterialTheme.typography.bodyMedium,
                                    shape = RoundedCornerShape(8.dp)
                                )

                                DropdownMenu(
                                    expanded = expandedDropdown,
                                    onDismissRequest = { expandedDropdown = false },
                                    modifier = Modifier
                                        .width(400.dp)
                                        .heightIn(max = 250.dp)
                                ) {
                                    Column(
                                        modifier = Modifier
                                            .fillMaxWidth()
                                            .heightIn(max = 250.dp)
                                            .verticalScroll(menuScrollState)
                                    ) {
                                        instruments.forEach { instrument ->
                                            val isSelected = selectedInstrument.program == instrument.program
                                            DropdownMenuItem(
                                                modifier = Modifier.fillMaxWidth(),
                                                text = {
                                                    Text(
                                                        "${instrument.program} - ${instrument.name}",
                                                        fontWeight = if(isSelected) FontWeight.Bold else FontWeight.Normal,
                                                        style = MaterialTheme.typography.bodyMedium
                                                    )
                                                   },
                                                onClick = {
                                                    globalInstrumentProgram = instrument.program
                                                    sharedScreenModel.saveVoiceInstrument(instrument.program)
                                                    expandedDropdown = false
                                                },
                                                leadingIcon = {
                                                    Text(instrument.icon)
                                                },
                                                trailingIcon = {
                                                    if (isSelected) {
                                                        Icon(
                                                            imageVector = Icons.Default.Check,
                                                            contentDescription = null,
                                                            tint = MaterialTheme.colorScheme.primary,
                                                            modifier = Modifier.size(18.dp)
                                                        )
                                                    }
                                                },
                                                colors = MenuDefaults.itemColors(
                                                    textColor = if (isSelected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurface,
                                                    leadingIconColor = MaterialTheme.colorScheme.primary,
                                                    trailingIconColor = MaterialTheme.colorScheme.primary
                                                ),
                                                contentPadding = PaddingValues(horizontal = 16.dp, vertical = 8.dp)
                                            )
                                        }
                                    }
                                }
                            }
                        }

                        HorizontalDivider(
                            color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.2f),
                            modifier = Modifier.padding(vertical = 12.dp)
                        )

                        Text(
                            text = "Règlage du lecteur",
                            style = MaterialTheme.typography.bodyLarge,
                            fontWeight = FontWeight.Bold,
                            color = MaterialTheme.colorScheme.onSurface,
                            modifier = Modifier.padding(bottom = 8.dp)
                        )

                        Surface(
                            shape = RoundedCornerShape(12.dp),
                            color = MaterialTheme.colorScheme.surfaceContainerLow,
                            modifier = Modifier.fillMaxWidth()
                        ) {
                            Row(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(horizontal = 16.dp, vertical = 8.dp),
                                horizontalArrangement = Arrangement.SpaceBetween,
                                verticalAlignment = Alignment.CenterVertically
                            ) {
                                Text(
                                    text = "Décompte avant la lecture ",
                                    style = MaterialTheme.typography.bodyMedium,
                                    fontWeight = FontWeight.Normal,
                                    color = MaterialTheme.colorScheme.onSurface,
                                    modifier = Modifier.padding(bottom = 8.dp)
                                )
                                Row(
                                    verticalAlignment = Alignment.CenterVertically,
                                    horizontalArrangement = Arrangement.spacedBy(10.dp)
                                ) {
                                    if(!isAndroid) {
                                        val countInStat = if (hasCountIn) "Désactiver" else "Activer"
                                        Text(
                                            text = countInStat,
                                            style = MaterialTheme.typography.bodyMedium
                                        )
                                    }
                                    Switch(
                                        checked = hasCountIn,
                                        onCheckedChange = { enabled ->
                                            hasCountIn = enabled
                                            prefs.putBoolean("isCountIn", enabled)
                                        },
                                        colors = SwitchDefaults.colors(
                                            checkedThumbColor = MaterialTheme.colorScheme.onPrimary,
                                            checkedTrackColor = MaterialTheme.colorScheme.primary,
                                            uncheckedThumbColor = MaterialTheme.colorScheme.outline,
                                            uncheckedTrackColor = MaterialTheme.colorScheme.surfaceContainerHighest,
                                            uncheckedBorderColor = MaterialTheme.colorScheme.outline
                                        ),
                                        modifier = Modifier.size(45.dp)
                                    )
                                }
                            }
                        }
                    }
                }
            }
        },
        confirmButton = {
            TextButton(onClick = onDismissRequest) {
                Text("Enregistrer", fontWeight = FontWeight.Bold)
            }
        },
        dismissButton = {
            TextButton(onClick = onDismissRequest) {
                Text("Annuler")
            }
        },
        containerColor = MaterialTheme.colorScheme.surface,
        shape = RoundedCornerShape(16.dp)
    )
}

@Composable
fun SettingsAccordion(
    title: String,
    isExpanded: Boolean,
    onToggle: () -> Unit,
    content: @Composable ColumnScope.() -> Unit
) {
    val arrowRotationDegree by animateFloatAsState(
        targetValue = if (isExpanded) 180f else 0f,
        animationSpec = tween(durationMillis = 250),
        label = "ArrowRotation"
    )

    Card(
        modifier = Modifier
            .fillMaxWidth()
            .clip(RoundedCornerShape(16.dp)),
        colors = CardDefaults.cardColors(
            containerColor = if (isExpanded) {
                MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f)
            } else {
                MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.25f)
            }
        ),
        border = BorderStroke(
            width = 1.dp,
            color = if (isExpanded) MaterialTheme.colorScheme.primary.copy(alpha = 0.3f) else Color.Transparent
        ),
        shape = RoundedCornerShape(16.dp)
    ) {
        Column(modifier = Modifier.fillMaxWidth()) {

            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .clickable { onToggle() }
                    .padding(horizontal = 16.dp, vertical = 14.dp),
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.SpaceBetween
            ) {
                Text(
                    text = title,
                    fontWeight = if (isExpanded) FontWeight.ExtraBold else FontWeight.SemiBold,
                    fontSize = 15.sp,
                    color = if (isExpanded) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurface
                )

                Icon(
                    imageVector = Icons.Default.KeyboardArrowDown,
                    contentDescription = null,
                    tint = if (isExpanded) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant,
                    modifier = Modifier.rotate(arrowRotationDegree)
                )
            }

            AnimatedVisibility(visible = isExpanded) {
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(start = 16.dp, end = 16.dp, bottom = 16.dp)
                ) {
                    HorizontalDivider(
                        color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.1f),
                        modifier = Modifier.padding(bottom = 12.dp)
                    )
                    content()
                }
            }
        }
    }
}