package mg.dot.feufaro.ui


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.filled.Close
import androidx.compose.material.icons.filled.PictureAsPdf
import androidx.compose.material.icons.filled.RestartAlt
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.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.graphics.vector.PathParser
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import mg.dot.feufaro.pdf.PageOrientation
import mg.dot.feufaro.pdf.PageSize
import mg.dot.feufaro.pdf.PrintSettings
import mg.dot.feufaro.pdf.defaultPrintSettings
import kotlin.math.roundToInt


@Composable
fun PrintSettingsDialog(
    initialSettings: PrintSettings = defaultPrintSettings(),
    onDismiss: () -> Unit,
    onConfirm: (PrintSettings) -> Unit,
) {
    // ── État local (copie mutable des paramètres) ─────────────────────────────
    var pageSize        by remember { mutableStateOf(initialSettings.pageSize) }
    var orientation     by remember { mutableStateOf(initialSettings.orientation) }
    var noteFontSize    by remember { mutableStateOf(initialSettings.noteFontSize) }
    var lyricFontSize   by remember { mutableStateOf(initialSettings.lyricFontSize) }
    var markerHeight    by remember { mutableStateOf(initialSettings.markerHeight) }
    var noteLineH       by remember { mutableStateOf(initialSettings.noteLineH) }
    var lyricLineH      by remember { mutableStateOf(initialSettings.lyricLineH) }
    var extraSylLineH   by remember { mutableStateOf(initialSettings.extraSylLineH) }
    var adjustedMargin  by remember { mutableStateOf(initialSettings.adjustedMargin) }
    var interRowGap     by remember { mutableStateOf(initialSettings.interRowGap) }
    var marginX         by remember { mutableStateOf(initialSettings.marginX) }
    var marginY         by remember { mutableStateOf(initialSettings.marginY) }
    var headerH         by remember { mutableStateOf(initialSettings.headerH) }
    var nbGridOnMeasure by remember { mutableStateOf(initialSettings.nbGridOnMeasure) }

    Dialog(onDismissRequest = onDismiss) {
        Surface(
            modifier = Modifier
                .fillMaxWidth(0.92f)
                .fillMaxHeight(0.92f),
            shape = RoundedCornerShape(16.dp),
            tonalElevation = 8.dp,
            color = MaterialTheme.colorScheme.surface
        ) {
            Column(modifier = Modifier.fillMaxSize()) {

                // ── Barre de titre ────────────────────────────────────────────
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .background(MaterialTheme.colorScheme.primary)
                        .padding(horizontal = 20.dp, vertical = 14.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(
                        text = "Paramètres d'impression",
                        color = MaterialTheme.colorScheme.onPrimary,
                        fontSize = 18.sp,
                        fontWeight = FontWeight.Bold,
                        modifier = Modifier.weight(1f)
                    )
                    IconButton(onClick = onDismiss) {
                        Icon(
                            Icons.Filled.Close,
                            contentDescription = "Fermer",
                            tint = MaterialTheme.colorScheme.onPrimary
                        )
                    }
                }

                // ── Corps scrollable en deux colonnes ─────────────────────────
                Row(
                    modifier = Modifier
                        .weight(1f)
                        .fillMaxWidth()
                        .padding(16.dp),
                    horizontalArrangement = Arrangement.spacedBy(24.dp)
                ) {
                    // ── Colonne gauche : Format papier + Preview ──────────────
                    Column(
                        modifier = Modifier
                            .weight(1f)
                            .verticalScroll(rememberScrollState()),
                        verticalArrangement = Arrangement.spacedBy(16.dp)
                    ) {
                        SectionTitle("Format de page")

                        Row{
                            Column(
                                modifier = Modifier.fillMaxWidth(0.7f)
                            ) {
                                LabelRow("Nombre de colonne d'une portée")
                            }
                            Column {
                                TextField(
                                    value = if (nbGridOnMeasure == 0) "" else nbGridOnMeasure.toString(),
                                    onValueChange = { newValue ->
                                        val number = newValue.toIntOrNull()?.coerceAtMost(25)
                                        if (number != null) {
                                            nbGridOnMeasure = number
                                        } else if (newValue.isEmpty()) {
                                            nbGridOnMeasure = 0
                                        }
                                    },
                                    modifier = Modifier.height(50.dp)
                                )
                            }
                        }

                        Spacer(Modifier.height(4.dp))

                        // Taille papier
                        LabelRow("Taille du papier")
                        SegmentedRow(
                            options = PageSize.entries.map { it.label },
                            selected = pageSize.ordinal,
                            onSelect = { pageSize = PageSize.entries[it] }
                        )

                        Spacer(Modifier.height(4.dp))

                        // Orientation
                        LabelRow("Orientation")
                        SegmentedRow(
                            options = PageOrientation.entries.map { it.label },
                            selected = orientation.ordinal,
                            onSelect = { orientation = PageOrientation.entries[it] }
                        )

                        Spacer(Modifier.height(8.dp))

                        // ── Preview miniature de la page ──────────────────────
                        SectionTitle("Aperçu")
                        val currentSettings = PrintSettings(
                            pageSize = pageSize,
                            orientation = orientation,
                            noteFontSize = noteFontSize,
                            lyricFontSize = lyricFontSize,
                            markerHeight = markerHeight,
                            noteLineH = noteLineH,
                            lyricLineH = lyricLineH,
                            extraSylLineH = extraSylLineH,
                            adjustedMargin = adjustedMargin,
                            interRowGap = interRowGap,
                            marginX = marginX,
                            marginY = marginY,
                            headerH = headerH,
                            nbGridOnMeasure =  nbGridOnMeasure
                        )

                        Box(
                            modifier = Modifier.fillMaxWidth(),
                            contentAlignment = Alignment.Center
                        ) {
                            PagePreview(
                                settings = currentSettings,
                                modifier = Modifier
                                    .height(250.dp) // Hauteur fixe demandée
                                    .padding(vertical = 8.dp)
                            )
                        }
                    }

                    // ── Colonne droite : Paramètres typographiques / marges ───
                    Column(
                        modifier = Modifier
                            .weight(1f)
                            .verticalScroll(rememberScrollState()),
                        verticalArrangement = Arrangement.spacedBy(8.dp)
                    ) {
                        SectionTitle("Typographie")
                        FloatSlider(
                            label = "Taille fonte notes",
                            value = noteFontSize,
                            range = 8f..18f,
                            unit = "pt"
                        ) { noteFontSize = it }

                        FloatSlider(
                            label = "Taille fonte paroles",
                            value = lyricFontSize,
                            range = 8f..18f,
                            unit = "pt"
                        ) { lyricFontSize = it }

                        Spacer(Modifier.height(4.dp))
                        SectionTitle("Espacements")

                        FloatSlider(
                            label = "Hauteur zone marqueurs",
                            value = markerHeight,
                            range = 8f..32f,
                            unit = "mm"
                        ) { markerHeight = it }

                        FloatSlider(
                            label = "Espace entre voix",
                            value = noteLineH,
                            range = 10f..34f,
                            unit = "mm"
                        ) { noteLineH = it }

                        FloatSlider(
                            label = "Espace lignes paroles restantes",
                            value = lyricLineH,
                            range = 10f..30f,
                            unit = "mm"
                        ) { lyricLineH = it }

                        FloatSlider(
                            label = "Espace syl0 / syl1+",
                            value = extraSylLineH,
                            range = 8f..30f,
                            unit = "mm"
                        ) { extraSylLineH = it }

                        FloatSlider(
                            label = "Marge ajustée syl0",
                            value = adjustedMargin,
                            range = 4f..30f,
                            unit = "mm"
                        ) { adjustedMargin = it }

                        FloatSlider(
                            label = "Écart entre portées",
                            value = interRowGap,
                            range = 10f..60f,
                            unit = "mm"
                        ) { interRowGap = it }

                        Spacer(Modifier.height(4.dp))
                        SectionTitle("Marges")

                        FloatSlider(
                            label = "Marge gauche/droite",
                            value = marginX,
                            range = 15f..80f,
                            unit = "mm"
                        ) { marginX = it }

                        FloatSlider(
                            label = "Marge haut/bas",
                            value = marginY,
                            range = 15f..80f,
                            unit = "mm"
                        ) { marginY = it }

                        FloatSlider(
                            label = "Hauteur en-tête",
                            value = headerH,
                            range = 49f..90f,
                            unit = "mm"
                        ) { headerH = it }
                    }
                }

                // ── Boutons bas ───────────────────────────────────────────────
                HorizontalDivider()
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = 24.dp, vertical = 14.dp),
                    horizontalArrangement = Arrangement.spacedBy(12.dp, Alignment.End),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    // Réinitialiser
                    TextButton(onClick = {
                        val def = defaultPrintSettings()
                        pageSize       = def.pageSize
                        orientation    = def.orientation
                        noteFontSize   = def.noteFontSize
                        lyricFontSize  = def.lyricFontSize
                        markerHeight   = def.markerHeight
                        noteLineH      = def.noteLineH
                        lyricLineH     = def.lyricLineH
                        extraSylLineH  = def.extraSylLineH
                        adjustedMargin = def.adjustedMargin
                        interRowGap    = def.interRowGap
                        marginX        = def.marginX
                        marginY        = def.marginY
                        headerH        = def.headerH
                    }) {
                        Icon(
                            imageVector = Icons.Default.RestartAlt,
                            contentDescription = null,
                            modifier = Modifier.size(18.dp)
                        )
                    }

//                    Spacer(Modifier.weight(1f))

                    OutlinedButton(onClick = onDismiss) {
                        Icon(
                            imageVector = Icons.Default.Close,
                            contentDescription = null,
                            modifier = Modifier.size(18.dp)
                        )
                    }

                    Button(onClick = {
                        onConfirm(
                            PrintSettings(
                                pageSize       = pageSize,
                                orientation    = orientation,
                                noteFontSize   = noteFontSize,
                                lyricFontSize  = lyricFontSize,
                                markerHeight   = markerHeight,
                                noteLineH      = noteLineH,
                                lyricLineH     = lyricLineH,
                                extraSylLineH  = extraSylLineH,
                                adjustedMargin = adjustedMargin,
                                interRowGap    = interRowGap,
                                marginX        = marginX,
                                marginY        = marginY,
                                headerH        = headerH,
                                nbGridOnMeasure = nbGridOnMeasure
                            )
                        )
                    }) {
                        Icon(
                            imageVector = Icons.Default.PictureAsPdf,
                            contentDescription = null,
                            modifier = Modifier.size(18.dp)
                        )
                    }
                }
            }
        }
    }
}

// ── Composants internes ───────────────────────────────────────────────────────

@Composable
private fun SectionTitle(text: String) {
    Text(
        text = text,
        fontWeight = FontWeight.SemiBold,
        fontSize = 13.sp,
        color = MaterialTheme.colorScheme.primary,
        modifier = Modifier.padding(top = 4.dp)
    )
    HorizontalDivider(
        modifier = Modifier.padding(bottom = 4.dp),
        color = MaterialTheme.colorScheme.primary.copy(alpha = 0.3f)
    )
}

@Composable
private fun LabelRow(text: String) {
    Text(
        text = text,
        fontSize = 12.sp,
        color = MaterialTheme.colorScheme.onSurfaceVariant
    )
}

@Composable
private fun SegmentedRow(
    options: List<String>,
    selected: Int,
    onSelect: (Int) -> Unit
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .clip(RoundedCornerShape(8.dp))
            .border(
                width = 1.dp,
                color = MaterialTheme.colorScheme.outline,
                shape = RoundedCornerShape(8.dp)
            )
    ) {
        options.forEachIndexed { index, label ->
            val isSelected = index == selected
            Box(
                contentAlignment = Alignment.Center,
                modifier = Modifier
                    .weight(1f)
                    .background(
                        if (isSelected) MaterialTheme.colorScheme.primary
                        else Color.Transparent
                    )
                    .clickable { onSelect(index) }
                    .padding(vertical = 8.dp)
            ) {
                Text(
                    text = label,
                    fontSize = 13.sp,
                    fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Normal,
                    color = if (isSelected) MaterialTheme.colorScheme.onPrimary
                    else MaterialTheme.colorScheme.onSurface
                )
            }
        }
    }
}

/**
 * Slider flottant avec label + valeur affichée.
 */
fun Float.toMm(): Float {
    return this * 0.3528f
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun FloatSlider(
    label: String,
    value: Float,
    range: ClosedFloatingPointRange<Float>,
    unit: String,
    onValueChange: (Float) -> Unit
) {
    val displayValue = if (unit == "mm") value.toMm() else value
    val roundedDisplayValue = (displayValue * 2).roundToInt() / 2f
    val primaryTeal = Color(0xFF009688)
    val lightTeal = Color(0xFFB2DFDB)

    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 8.dp)
    ) {
        // 1. Label de description fixe à gauche
        Text(
            text = label,
            fontSize = 12.sp,
            fontWeight = FontWeight.Medium,
            color = MaterialTheme.colorScheme.onSurfaceVariant
        )

        // 2. Zone du Slider avec la valeur flottante au-dessus
        BoxWithConstraints(modifier = Modifier.fillMaxWidth()) {
            val widthPx = constraints.maxWidth.toFloat()

            // Calcul de la position X du texte pour suivre le thumb
            // On normalise la valeur entre 0.0 et 1.0
            val fraction = (value - range.start) / (range.endInclusive - range.start)
            val textOffset = (widthPx * fraction)

            // Affichage de la valeur qui "flotte" au-dessus du thumb
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(20.dp) // Espace pour le texte
            ) {
                Text(
                    text = "$roundedDisplayValue $unit",
                    fontSize = 11.sp,
                    fontWeight = FontWeight.Bold,
                    color = primaryTeal,
                    modifier = Modifier.graphicsLayer() {
                        translationX = textOffset - (30.dp.toPx()) // Ajustement pour centrer le texte
                    }
                )
            }
            Slider(
                value = value,
                onValueChange = { onValueChange((it * 2).roundToInt() / 2f) },
                valueRange = range,
                steps = (((range.endInclusive - range.start) / 0.5f).toInt() - 1).coerceAtLeast(0),
                modifier = Modifier.fillMaxWidth().padding(top = 15.dp), // Décale le slider sous le texte
                thumb = {
                    Box(
                        modifier = Modifier
                            .size(15.dp)
                            .background(primaryTeal, CircleShape)
                    )
                },
                track = { sliderState ->
                    SliderDefaults.Track(
                        sliderState = sliderState,
                        modifier = Modifier.height(8.dp),
                        colors = SliderDefaults.colors(
                            activeTrackColor = primaryTeal,
                            inactiveTrackColor = lightTeal
                        ),
                        drawStopIndicator = null
                    )
                }
            )
        }
    }
}
/**
 * Mini preview de la page
 */
@Composable
private fun PagePreview(
    settings: PrintSettings,
    modifier: Modifier = Modifier
) {
    val isLandscape = settings.orientation == PageOrientation.LANDSCAPE
    val ratio = if (isLandscape) 1.414f else 0.707f
    val baseScale = 200f / 595f // Échelle pour l'affichage

    Box(
        modifier = modifier
            .aspectRatio(ratio)
            .clip(RoundedCornerShape(4.dp))
            .background(Color.White)
            .border(1.dp, Color.Gray.copy(alpha = 0.3f), RoundedCornerShape(4.dp)),
        contentAlignment = Alignment.TopStart
    ) {
        // Conversion des unités en DP
        val mx = (settings.marginX * baseScale).dp
        val my = (settings.marginY * baseScale).dp
        val hH = (settings.headerH * baseScale).dp
        val nH = (settings.noteLineH * baseScale).dp // Espace entre 2 voix
        val iG = (settings.interRowGap * baseScale).dp // Entre portées
        val mH = (settings.markerHeight * baseScale).dp // Zone orange
        val aM = (settings.adjustedMargin * baseScale).dp // Marge syl0
        val eS = (settings.extraSylLineH * baseScale).dp // Espace syl0/syl1
        val pR = (settings.lyricLineH * baseScale).dp // Espace syl0/syl1

        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(horizontal = mx, vertical = my)
        ) {
            // 1. HEADER
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(hH)
                    .border(0.5.dp, Color.Red.copy(alpha = 0.5f))
                    .background(Color.Red.copy(alpha = 0.05f))
            )

            Spacer(modifier = Modifier.height(iG / 2))

            // 2. PORTÉES
            val repeatedPort = if(settings.orientation == PageOrientation.LANDSCAPE) 2 else 3
            repeat(repeatedPort) {
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .border(0.5.dp, Color(0xFF2ECC71).copy(alpha = 0.4f)) // Cadre Vert
                        .padding(2.dp)
                ) {
                    // Ligne des Marqueurs
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(mH / 2)
                            .border(0.5.dp, Color(0xFFE67E22)) // Orange
                            .background(Color(0xFFE67E22).copy(alpha = 0.1f))
                    )

                    // Lignes des Notes par voix
                    Row(verticalAlignment = Alignment.CenterVertically) {
                        AccoladeShape(modifier = Modifier.width(6.dp).height(nH * 2.5f))

                        Column(modifier = Modifier.weight(1f).padding(start = 2.dp)) {
                            repeat(4) {
                                Box(
                                    modifier = Modifier
                                        .fillMaxWidth(0.9f)
                                        .height(nH / 3)
                                        .border(0.3.dp, Color(0xFF00BCD4)) // Bleu Ciel
                                        .background(Color(0xFF00BCD4).copy(alpha = 0.1f))
                                )
                                Spacer(modifier = Modifier.height(nH / 6))
                            }
                        }
                    }

                    // Paroles Syl0 et Syl1
                    Spacer(modifier = Modifier.height(aM / 2))
                    Column(
                        modifier = Modifier
                            .fillMaxWidth(0.85f)
                            .border(0.5.dp, Color(0xFF9B59B6)) // Violet
                            .padding(1.dp)
                    ) {
                        // Syl0
                        Box(modifier = Modifier.fillMaxWidth().height(2.dp).background(Color(0xFF9B59B6).copy(alpha = 0.3f)))
                        Spacer(modifier = Modifier.height(eS / 4))
                        // Syl1
                        Box(modifier = Modifier.fillMaxWidth(0.9f).height(2.dp).background(Color(0xFF9B59B6).copy(alpha = 0.3f)))
                    }
                }
                Spacer(modifier = Modifier.height(iG))
            }

            // 3. PAROLES RESTANTES
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .border(0.5.dp, Color.Red.copy(alpha = 0.5f))
                    .background(Color.Red.copy(alpha = 0.05f))
                    .padding(4.dp),
                verticalArrangement = Arrangement.spacedBy(2.dp)
            ) {
                repeat(4) { index ->
                    Box(
                        modifier = Modifier
                            .fillMaxWidth(if (index % 2 == 0) 0.95f else 0.85f)
                            .height(2.dp)
                            .background(Color.Red.copy(alpha = 0.2f))
                    )
                    Spacer(modifier = Modifier.height(pR / 4))
                }
            }
        }
    }
}

@Composable
private fun AccoladeShape(modifier: Modifier) {
    Canvas(modifier = modifier) {
        // Le path que tu as fourni (normalisé sur une grille de 24x24 environ)
        val pathData = "M14 21C12.8954 21 12 20.1046 12 19V15.3255C12 14.8363 12 14.5917 11.9447 14.3615C11.8957 14.1575 11.8149 13.9624 11.7053 13.7834C11.5816 13.5816 11.4086 13.4086 11.0627 13.0627L10 12L11.0627 10.9373C11.4086 10.5914 11.5816 10.4184 11.7053 10.2166C11.8149 10.0376 11.8957 9.84254 11.9447 9.63846C12 9.40829 12 9.1637 12 8.67452V5C12 3.89543 12.8954 3 14 3"

        val path = PathParser().parsePathString(pathData).toPath()
        val pathBounds = path.getBounds()
        val scaleX = size.width / pathBounds.width
        val scaleY = size.height / pathBounds.height

        drawContext.canvas.save()
        drawContext.canvas.scale(scaleX, scaleY)
        drawContext.canvas.translate(-pathBounds.left, -pathBounds.top)

        drawPath(
            path = path,
            color = Color.Black,
            style = androidx.compose.ui.graphics.drawscope.Stroke(
                width = 0.552f,
                cap = androidx.compose.ui.graphics.StrokeCap.Round,
                join = androidx.compose.ui.graphics.StrokeJoin.Round
            )
        )
        drawContext.canvas.restore()
    }
}