package mg.dot.feufaro.ui

import SharedScreenModel
import androidx.compose.animation.*
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.foundation.*
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowLeft
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight
import androidx.compose.material.icons.automirrored.filled.Undo
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.input.pointer.PointerEventType
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import mg.dot.feufaro.getPlatform
import mg.dot.feufaro.pdf.PrintSettings
import mg.dot.feufaro.pdf.defaultPrintSettings
import mg.dot.feufaro.pdf.rememberPdfExportAction
import mg.dot.feufaro.solfa.Solfa
import mg.dot.feufaro.solfa.Transpose
import mg.dot.feufaro.viewmodel.SolfaScreenModel
import java.io.File

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun MainScreenWithDrawer(
    solfaScreenModel: SolfaScreenModel,
    sharedScreenModel: SharedScreenModel,
    qrCodeResult: String,
    onScannerButtonClick: () -> Unit,
    solfaScrollState: ScrollState,
    content: @Composable (PaddingValues) -> Unit,
) {
    val drawerState = rememberDrawerState(initialValue = DrawerValue.Closed)
    var showSettingsDialog by remember { mutableStateOf(false) }
    var showAboutDialog by remember { mutableStateOf(false) }
    val scope = rememberCoroutineScope()

    val items by sharedScreenModel.drawerItems.collectAsState()

    val songTitle = sharedScreenModel.songTitle.collectAsState().value
    val filteredSongs by sharedScreenModel.filteredSongs.collectAsState()
    val songKey = sharedScreenModel.songKey.collectAsState().value
    val measure = sharedScreenModel.measure.collectAsState().value
    val stanza = sharedScreenModel.stanza.collectAsState().value
    val nbStanzas = sharedScreenModel.nbStanzas.collectAsState().value
    val songAuthor = sharedScreenModel.songAuthor.collectAsState().value
    val songComposer = sharedScreenModel.songComposer.collectAsState().value
    val songRhythm = sharedScreenModel.songRhythm.collectAsState().value

    val scrollState = rememberScrollState()
    val currentActivePath = Solfa.currentFile
    var textInput = sharedScreenModel.searchTitle.collectAsState().value

    val isSearchActive by sharedScreenModel.showSearchMenu.collectAsState()
    val focusRequester = remember { FocusRequester() }

    val isExpanded by sharedScreenModel.expandedFAB.collectAsState()
    val showMidiCtrl by sharedScreenModel.showMidiCtrl.collectAsState()
    var isShareExpanded by remember { mutableStateOf(false) }

    val isPlay by sharedScreenModel.isPlay.collectAsState()
    val isPos by sharedScreenModel.isPos.collectAsState()
    var isDragging = sharedScreenModel.isDragging
    val currentPos by sharedScreenModel.currentPos.collectAsState()
    val duration by sharedScreenModel.duration.collectAsState()
    val midiFile = "whawyd3.mid" //What do we gain by all our hard work?
    var refreshTrigeer by remember { mutableStateOf(0)}

    val volumelevel by sharedScreenModel.volumeLevel.collectAsState()

    val player = sharedScreenModel.mediaPlayer
    LaunchedEffect(isPlay, isPos) {
        if (isPlay && !isPos) {
            while (true) {
                sharedScreenModel.updateProgress()
                delay(100)
            }
        }
    }

    val isFullScreenEnabled by sharedScreenModel.isFullScreen.collectAsState()
    val fullscreenController = LocalFullscreenController.current

    LaunchedEffect(isFullScreenEnabled, isSearchActive) {
        fullscreenController(isFullScreenEnabled)
    }
    val isImeVisible = WindowInsets.ime.asPaddingValues().calculateBottomPadding() > 0.dp
    LaunchedEffect(isImeVisible) {
        if (!isImeVisible && isFullScreenEnabled) {
            fullscreenController(true)
        }
    }

    val fileContent = sharedScreenModel.fileContent.value ?: ""
    LaunchedEffect(Unit) {
        if(fileContent == "") {
            sharedScreenModel.loadNewSong("$midiFile")
        }
    }
    val isEditMode by sharedScreenModel.modeEditor.collectAsState()
    val createMode by sharedScreenModel.createMode.collectAsState()
    LaunchedEffect(isEditMode || createMode) {
        if(isEditMode || createMode) {
            drawerState.close()
        }
    }
    val currentActiveFilePath = sharedScreenModel.activeFilePath.value
    val fileName = currentActiveFilePath.substringAfterLast('/')

    var sourceTitle = sharedScreenModel.songTitle.value
    val originalPath = remember(sourceTitle) {
        if (!currentActiveFilePath.contains("_tmp") && !currentActiveFilePath.contains("/tmp/")) {
            currentActiveFilePath
        } else {
            currentActiveFilePath
        }
    }

    var sourceContent = sharedScreenModel.fileContent.value ?: ""
    var codeContent by remember { mutableStateOf(sourceContent?: "") }
    LaunchedEffect(sourceContent) {
        codeContent = sourceContent
    }
    val saveLauncher = rememberFileSaveLauncher { chosenPath ->
        if (chosenPath != null) {
            scope.launch(Dispatchers.IO) {
                try {
                    delay(500)
                    val tempDir = System.getProperty("java.io.tmpdir")

                    val sourceFileName = File(currentActiveFilePath).name
                    val sourceFile = File(tempDir, sourceFileName)

                    if (sourceFile.exists() && sourceFile.isFile) {
                        val data = sourceFile.readBytes()

                        if (data.isNotEmpty()) {
                            solfaScreenModel.fileRepository.saveLocalFile(chosenPath, data)

                            withContext(Dispatchers.Main) {
                                println("Succès : ${data.size} octets copiés vers $chosenPath")
                                solfaScreenModel.loadExternalFile(chosenPath)
                            }
                        } else {
                            println("Erreur : Le fichier source dans /tmp est vide.")
                        }
                    } else {
                        println("Erreur : Fichier source introuvable à l'adresse ${sourceFile.path} ${sourceFile.absolutePath}")
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        }
    }

    val isQrVisible = sharedScreenModel.isQRCodeVisible.value

    val sharedInteractionSource = remember { MutableInteractionSource() }

    LaunchedEffect(drawerState.isOpen) {
        if (drawerState.isOpen) {
            sharedScreenModel.loadItems()
        }
    }
    val density = LocalDensity.current
    var keyboardHeightDp by remember { mutableStateOf(0.dp) }

    ModalNavigationDrawer(drawerState = drawerState, drawerContent = {
        SimpleDrawerContent(
            items,
            solfaScreenModel,
            sharedScreenModel,
            currentActivePath,
            drawerState,
            scope,
            onScannerButtonClick = {
                scope.launch { drawerState.close() }
                onScannerButtonClick()
            },
            onSongSelected = { newSong ->
                sharedScreenModel.loadNewSong("$midiFile")
            },
            onSettingsCheck = {
                showSettingsDialog = true
            },
            onAboutCheck = {
                showAboutDialog = true
            }
        )
    }, content = {
        val scope = rememberCoroutineScope()
        var showPrintSettings by remember { mutableStateOf(false) }
        var pendingPrintSettings by remember { mutableStateOf<PrintSettings?>(null) }

        val pdfExportAction: (PrintSettings) -> Unit = rememberPdfExportAction(
            scope = scope,
            fileRepository = solfaScreenModel.fileRepository,
            gridData = sharedScreenModel.currentGridData,
            songTitle = songTitle,
            measure = measure,
            stanza = stanza,
            nbStanza = nbStanzas,
            songKey = songKey,
            songAut = songAuthor,
            songComp = songComposer,
            songRythm = songRhythm
        )
        val platform = getPlatform()
        val isAndroid = platform.name.startsWith("Android")

        if (showPrintSettings) {
            PrintSettingsDialog(
                initialSettings = defaultPrintSettings(),
//                nbStanza = nbStanzas,
                onDismiss = { showPrintSettings = false },
                onConfirm = { settings ->
                    showPrintSettings = false
                    pdfExportAction(settings)
                },
                isAndroid
            )
        }

        var expandedDropdown by remember { mutableStateOf(false) }
        if (showSettingsDialog) {
            Settings(
                sharedScreenModel = sharedScreenModel,
                onDismissRequest = {
                    showSettingsDialog = false
                },
                expandedDropdown,
                isAndroid
            )
        }
        if (showAboutDialog) {
            AboutDialog(onDismiss = { showAboutDialog = false })
        }
        val favoritePaths by sharedScreenModel.playlistItems.collectAsState()

        val keyboardController = LocalSoftwareKeyboardController.current
        var isNumericKeyboard by remember { mutableStateOf(true) }
        LaunchedEffect(isNumericKeyboard, isSearchActive) {
            if (isSearchActive) {
                if (isAndroid && isNumericKeyboard) {
                    keyboardController?.hide()
                } else {
                    keyboardController?.show()
                }
            }
        }
        val solfaKeyboardState = remember { SolfaKeyboardState() }

        CompositionLocalProvider(LocalSolfaKeyboardState provides solfaKeyboardState) {

        BoxWithConstraints(modifier = Modifier.fillMaxSize()) {
            val isLandscape = maxWidth > maxHeight
            val topAppBarHeight = if (isAndroid) {
                if(isLandscape) {
                    55.dp
                } else {
                    if (isFullScreenEnabled) 70.dp else 80.dp
                }
            } else {
                50.dp
            }

            CompositionLocalProvider(LocalSolfaKeyboardState provides solfaKeyboardState) {
                Scaffold(
                    contentWindowInsets = if (isFullScreenEnabled) {
                        WindowInsets(0, 0, 0, 0)
                    } else {
                        if (!isLandscape) {
                            WindowInsets.safeDrawing
                        } else {
                            WindowInsets(0, 0, 0, 0)
                        }
                    },
                    topBar = {
                        TopAppBar(
                            modifier = Modifier.height(topAppBarHeight),
                            windowInsets = if (!isLandscape) {
                                WindowInsets.safeDrawing.only(
                                    WindowInsetsSides.Horizontal + WindowInsetsSides.Top
                                )
                            } else {
                                WindowInsets(0, 0, 0, 0)
                            },
                            title = {
                                AnimatedContent(
                                    targetState = isSearchActive,
                                    label = "SearchTransition"
                                ) { searchActive ->
                                    if (searchActive) {
                                        Box(
                                            modifier = Modifier.fillMaxHeight(),
                                            contentAlignment = Alignment.Center
                                        ) {
                                            BasicTextField(
                                                value = textInput,
                                                onValueChange = { newValue ->
                                                    textInput = newValue
                                                    sharedScreenModel.updateSearchTxt(newValue)
                                                },
                                                readOnly = isAndroid && isNumericKeyboard,
                                                textStyle = LocalTextStyle.current.copy(
                                                    color = Color.White,
                                                    fontSize = 16.sp
                                                ),
                                                singleLine = true,
                                                cursorBrush = SolidColor(Color.White),
                                                keyboardOptions = KeyboardOptions(
                                                    keyboardType = if (isAndroid && isNumericKeyboard) KeyboardType.Text else KeyboardType.Number
                                                ),
                                                modifier = Modifier
                                                    .fillMaxWidth()
                                                    .height(38.dp)
                                                    .focusRequester(focusRequester)
                                                    .background(
                                                        color = Color.White.copy(alpha = 0.15f),
                                                        shape = RoundedCornerShape(20.dp)
                                                    ),
                                                decorationBox = { innerTextField ->
                                                    TextFieldDefaults.DecorationBox(
                                                        value = textInput,
                                                        innerTextField = innerTextField,
                                                        enabled = true,
                                                        singleLine = true,
                                                        visualTransformation = VisualTransformation.None,
                                                        interactionSource = sharedInteractionSource,
                                                        placeholder = {
                                                            Text(
                                                                text = "FFPM 1 Andriananahary ...",
                                                                color = Color.White.copy(alpha = 0.5f),
                                                                fontSize = 16.sp
                                                            )
                                                        },
                                                        leadingIcon = {
                                                            Icon(
                                                                imageVector = Icons.Default.Search,
                                                                contentDescription = null,
                                                                tint = Color.White.copy(alpha = 0.8f),
                                                                modifier = Modifier.size(20.dp)
                                                            )
                                                        },
                                                        trailingIcon = {
                                                            Row(
                                                                verticalAlignment = Alignment.CenterVertically,
                                                                horizontalArrangement = Arrangement.spacedBy(2.dp)
                                                            ) {
                                                                if (isAndroid) {
                                                                    IconButton(
                                                                        onClick = {
                                                                            isNumericKeyboard = !isNumericKeyboard
                                                                        },
                                                                        modifier = Modifier.size(32.dp)
                                                                    ) {
                                                                        Icon(
                                                                            imageVector = if (isNumericKeyboard) Icons.Default.Abc else Icons.Filled._123,
                                                                            contentDescription = null,
                                                                            tint = MaterialTheme.colorScheme.tertiary,
                                                                            modifier = Modifier.size(22.dp)
                                                                        )
                                                                    }
                                                                }

                                                                IconButton(
                                                                    onClick = {
                                                                        textInput = ""
                                                                        sharedScreenModel.updateSearchTxt("")
                                                                    },
                                                                    modifier = Modifier.size(32.dp)
                                                                ) {
                                                                    Icon(
                                                                        imageVector = Icons.Default.Clear,
                                                                        contentDescription = null,
                                                                        tint = Color.White.copy(alpha = 0.8f),
                                                                        modifier = Modifier.size(18.dp)
                                                                    )
                                                                }
                                                            }
                                                        },
                                                        contentPadding = PaddingValues(
                                                            horizontal = 10.dp,
                                                            vertical = 0.dp
                                                        ),
                                                        colors = TextFieldDefaults.colors(
                                                            focusedContainerColor = Color.Transparent,
                                                            unfocusedContainerColor = Color.Transparent,
                                                            focusedIndicatorColor = Color.Transparent,
                                                            unfocusedIndicatorColor = Color.Transparent
                                                        )
                                                    )
                                                }
                                            )
                                        }
                                    } else {
                                        Column(
                                            modifier = Modifier.fillMaxSize().verticalScroll(scrollState),
                                            verticalArrangement = Arrangement.Center
                                        ) {
                                            Row {
                                                Text(
                                                    songTitle,
                                                    modifier = Modifier.weight(1f, fill = true),
                                                    maxLines = 1,
                                                    softWrap = false,
                                                    overflow = TextOverflow.Ellipsis,
                                                    style = MaterialTheme.typography.headlineLarge
                                                )
                                            }
                                        }
                                    }
                                }
                            }, navigationIcon = {
                                if (!isQrVisible) {
                                    IconButton(onClick = {
                                        scope.launch { drawerState.open() }
                                    }) {
                                        Icon(Icons.Filled.Menu, contentDescription = "Ouvrir Menu")
                                    }
                                }
                            }, actions = {
                                var tempInterval by remember(fileContent) { mutableStateOf(0) }
                                var isEyeVisible by remember { mutableStateOf(false) }
                                val isMinor = songKey.endsWith("m", ignoreCase = true)
                                val cleanSongKey = if (isMinor) songKey.dropLast(1) else songKey
                                val keysOrder = Transpose.keyToNumber
                                val songKeyIndex = keysOrder.indexOf(cleanSongKey).takeIf { it != -1 } ?: 0
                                val rawKeyIndex = (songKeyIndex + tempInterval) % 12
                                val tempUiKey = keysOrder[if (rawKeyIndex < 0) rawKeyIndex + 12 else rawKeyIndex]
                                val appliedInterval by sharedScreenModel.transpositionInterval.collectAsState()
                                val isPendingChange = tempInterval != appliedInterval
                                val isCurrentlyTransposed = appliedInterval != 0

                                Box(
                                    modifier = Modifier.padding(end = 16.dp),
                                    contentAlignment = Alignment.TopCenter
                                ) {
                                    Row(
                                        modifier = Modifier.fillMaxHeight(),
                                        verticalAlignment = Alignment.CenterVertically
                                    ) {
                                        Text(
                                            text = if(isMinor) "${tempUiKey}m" else tempUiKey,
                                            style = MaterialTheme.typography.displaySmall,
                                            fontWeight = FontWeight.Black,
                                            textAlign = TextAlign.Center,
                                            color = if (isCurrentlyTransposed && !isPendingChange) Color(0xFFFFD700) else Color.White,
                                            modifier = Modifier
                                                .clickable(
                                                    interactionSource = sharedInteractionSource,
                                                    indication = null
                                                ) {
                                                    isEyeVisible = !isEyeVisible
                                                }
                                                .width(65.dp)
                                        )
                                    }

                                    DropdownMenu(
                                        expanded = isEyeVisible,
                                        onDismissRequest = { isEyeVisible = false },
                                        containerColor = Color(0xFF2C3135).copy(alpha = 0.75f),
                                        shape = RoundedCornerShape(16.dp),
                                        modifier = Modifier.padding(12.dp)
                                    ) {
                                        Column(
                                            horizontalAlignment = Alignment.CenterHorizontally,
                                            verticalArrangement = Arrangement.spacedBy(8.dp)
                                        ) {
                                            /* < = > */
                                            Row(
                                                verticalAlignment = Alignment.CenterVertically,
                                                horizontalArrangement = Arrangement.SpaceEvenly,
                                                modifier = Modifier.padding(horizontal = 4.dp)
                                            ) {
                                                /* < */
                                                val currentIndex = keysOrder.indexOf(tempUiKey).takeIf { it != -1 } ?: 0
                                                val targetKeyLeft = keysOrder[(currentIndex - 1 + 12) % 12]

                                                TooltipBox(
                                                    positionProvider = TooltipDefaults.rememberPlainTooltipPositionProvider(),
                                                    tooltip = {
                                                        PlainTooltip(
                                                            containerColor = Color.DarkGray,
                                                            contentColor = Color.White
                                                        ) { Text(targetKeyLeft, fontSize = 12.sp) }
                                                    },
                                                    state = rememberTooltipState()
                                                ) {
                                                    IconButton(
                                                        modifier = Modifier.size(36.dp),
                                                        onClick = { tempInterval-- }
                                                    ) {
                                                        Icon(
                                                            imageVector = Icons.AutoMirrored.Filled.KeyboardArrowLeft,
                                                            contentDescription = null,
                                                            tint = Color.White
                                                        )
                                                    }
                                                }

                                                val centralIcon =
                                                    if (isPendingChange) Icons.Filled.Check else Icons.Filled.SwapHoriz
                                                val centralTint =
                                                    if (isPendingChange) MaterialTheme.colorScheme.tertiary else Color.White
                                                val tooltipText =
                                                    if (isPendingChange) "Transposer en $tempUiKey" else if (isCurrentlyTransposed) "Revenir en $songKey" else "Transposer"

                                                TooltipBox(
                                                    positionProvider = TooltipDefaults.rememberPlainTooltipPositionProvider(),
                                                    tooltip = {
                                                        PlainTooltip(
                                                            containerColor = Color.DarkGray,
                                                            contentColor = Color.White
                                                        ) { Text(text = tooltipText, fontSize = 12.sp) }
                                                    },
                                                    state = rememberTooltipState()
                                                ) {
                                                    IconButton(
                                                        modifier = Modifier.size(36.dp),
                                                        onClick = {
                                                            if (!isPendingChange && isCurrentlyTransposed) {
                                                                tempInterval = 0
                                                                sharedScreenModel.setTranspositionInterval(0)
                                                            } else {
                                                                sharedScreenModel.setTranspositionInterval(tempInterval)
                                                            }
                                                            solfaScreenModel.loadFromFile(sharedScreenModel.activeFilePath.value)
                                                            isEyeVisible = false
                                                        }
                                                    ) {
                                                        Icon(
                                                            imageVector = centralIcon,
                                                            contentDescription = null,
                                                            tint = centralTint
                                                        )
                                                    }
                                                }

                                                /* > */
                                                val targetKeyRight = keysOrder[(currentIndex + 1) % 12]
                                                TooltipBox(
                                                    positionProvider = TooltipDefaults.rememberPlainTooltipPositionProvider(),
                                                    tooltip = {
                                                        PlainTooltip(
                                                            containerColor = Color.DarkGray,
                                                            contentColor = Color.White
                                                        ) { Text(targetKeyRight, fontSize = 12.sp) }
                                                    },
                                                    state = rememberTooltipState()
                                                ) {
                                                    IconButton(
                                                        modifier = Modifier.size(36.dp),
                                                        onClick = { tempInterval++ }
                                                    ) {
                                                        Icon(
                                                            imageVector = Icons.AutoMirrored.Filled.KeyboardArrowRight,
                                                            contentDescription = null,
                                                            tint = Color.White
                                                        )
                                                    }
                                                }
                                            }

                                            val cIndex = keysOrder.indexOf("C")
                                            val intervalToC = if (cIndex != -1) cIndex - songKeyIndex else 0

                                            TooltipBox(
                                                positionProvider = TooltipDefaults.rememberPlainTooltipPositionProvider(),
                                                tooltip = {
                                                    PlainTooltip(
                                                        containerColor = Color.DarkGray,
                                                        contentColor = Color.White
                                                    ) { Text(text = "Transposer en Do (C)", fontSize = 12.sp) }
                                                },
                                                state = rememberTooltipState()
                                            ) {
                                                OutlinedButton(
                                                    onClick = {
                                                        tempInterval = intervalToC
                                                        sharedScreenModel.setTranspositionInterval(intervalToC)
                                                        solfaScreenModel.loadFromFile(sharedScreenModel.activeFilePath.value)
                                                        isEyeVisible = false
                                                    },
                                                    modifier = Modifier.fillMaxWidth().height(36.dp),
                                                    shape = RoundedCornerShape(8.dp),
                                                    border = BorderStroke(
                                                        1.dp,
                                                        MaterialTheme.colorScheme.tertiary.copy(alpha = 0.5f)
                                                    ),
                                                    colors = ButtonDefaults.outlinedButtonColors(
                                                        contentColor = MaterialTheme.colorScheme.tertiary
                                                    )
                                                ) {
                                                    Text(
                                                        text = "Transposer en C",
                                                        fontSize = 12.sp,
                                                        fontWeight = FontWeight.Bold
                                                    )
                                                }
                                            }
                                        }
                                    }
                                }
                            }, colors = TopAppBarColors(
                                containerColor = MaterialTheme.colorScheme.primary,
                                titleContentColor = MaterialTheme.colorScheme.onPrimary,
                                actionIconContentColor = MaterialTheme.colorScheme.onPrimary,
                                navigationIconContentColor = MaterialTheme.colorScheme.onPrimary,
                                scrolledContainerColor = MaterialTheme.colorScheme.onPrimary,
                            )
                        )
                    }, floatingActionButton = {
                        Row(
                            modifier = Modifier.fillMaxWidth()
                        ) {
                            if (!solfaKeyboardState.isVisible) {
                                Column(
                                    modifier = Modifier.fillMaxWidth().padding(5.dp),
                                    horizontalAlignment = Alignment.End,
                                    verticalArrangement = Arrangement.spacedBy(7.dp)
                                ) {
                                    if (isEditMode) {
                                        AnimatedVisibility(
                                            visible = true,
                                            enter = fadeIn() + scaleIn() + slideInVertically { it / 2 },
                                            exit = fadeOut() + scaleOut() + slideOutVertically { it / 2 }
                                        ) {
                                            MyFAB(
                                                onClick = {
                                                    scope.launch {
                                                        codeContent = sourceContent

                                                        withContext(Dispatchers.Main) {
                                                            solfaScreenModel.loadExternalFile(originalPath)
                                                        }
                                                    }
                                                },
                                                icon = Icons.AutoMirrored.Default.Undo
                                            )
                                        }

                                        AnimatedVisibility(
                                            visible = true,
                                            enter = fadeIn() + scaleIn() + slideInVertically { it / 2 },
                                            exit = fadeOut() + scaleOut() + slideOutVertically { it / 2 }
                                        ) {
                                            MyFAB(
                                                onClick = {
                                                    scope.launch {
                                                        try {
                                                            val initialDir =
                                                                solfaScreenModel.fileRepository.getAppPublicFolder().absolutePath
                                                            saveLauncher.launch(fileName, initialDir)
                                                        } catch (e: Exception) {
                                                            e.printStackTrace()
                                                        }
                                                    }
                                                },
                                                icon = Icons.Filled.SaveAs
                                            )
                                        }

                                        AnimatedVisibility(
                                            visible = true,
                                            enter = fadeIn() + scaleIn() + slideInVertically { it / 2 },
                                            exit = fadeOut() + scaleOut() + slideOutVertically { it / 2 }
                                        ) {
                                            MyFAB(
                                                onClick = {
                                                    sharedScreenModel.toggleEditorMode(false)
                                                },
                                                icon = Icons.Default.Close
                                            )
                                        }
                                    } else if (!isQrVisible) {
                                        AnimatedVisibility(
                                            visible = isExpanded and !showMidiCtrl,
                                            enter = fadeIn() + scaleIn() + slideInVertically { it / 2 },
                                            exit = fadeOut() + scaleOut() + slideOutVertically { it / 2 }
                                        ) {
                                            Row {
                                                Column {
                                                    MyFAB(
                                                        onClick = {
                                                            sharedScreenModel.descGridCount(1)
                                                        },
                                                        size = 30.dp,
                                                        icon = Icons.Default.Remove
                                                    )
                                                }
                                                Column {
                                                    MyFAB(
                                                        onClick = {
                                                            sharedScreenModel.addGridCount(1)
                                                        },
                                                        size = 30.dp,
                                                        icon = Icons.Default.Add
                                                    )
                                                }
                                            }
                                        }
                                        AnimatedVisibility(
                                            visible = isExpanded and !showMidiCtrl,
                                            enter = fadeIn() + scaleIn() + slideInVertically { it / 2 },
                                            exit = fadeOut() + scaleOut() + slideOutVertically { it / 2 }
                                        ) {
                                            Row(
                                                verticalAlignment = Alignment.CenterVertically,
                                                horizontalArrangement = Arrangement.spacedBy(8.dp)
                                            ) {
                                                AnimatedVisibility(
                                                    visible = isShareExpanded,
                                                    enter = fadeIn() + expandHorizontally(),
                                                    exit = fadeOut() + shrinkHorizontally()
                                                ) {
                                                    Row(
                                                        horizontalArrangement = Arrangement.spacedBy(8.dp),
                                                        verticalAlignment = Alignment.CenterVertically
                                                    ) {
                                                        MyFAB(
                                                            onClick = {
                                                                sharedScreenModel.toggleQRCodeVisibility()
                                                                sharedScreenModel.setExpandedFAB(false)
                                                                isShareExpanded = false
                                                            },
                                                            icon = Icons.Filled.QrCode2
                                                        )

                                                        MyFAB(
                                                            onClick = {
                                                                showPrintSettings = !showPrintSettings
                                                                isShareExpanded = false
                                                            },
                                                            icon = Icons.Filled.Print
                                                        )

                                                        MyFAB(
                                                            onClick = {
                                                                isShareExpanded = false
                                                                scope.launch {
                                                                    withContext(Dispatchers.IO) {
                                                                        try {
                                                                            val cleanS = songTitle.replace(' ','_')
                                                                            val exportName = "${cleanS.ifEmpty { "partition" }}.mid"

                                                                            val savedPath = solfaScreenModel.fileRepository.pickSavePath(
                                                                                defaultName = exportName,
                                                                                title = "Enregistrer le fichier MIDI"
                                                                            )

                                                                            if (!savedPath.isNullOrEmpty()) {
                                                                                val bpm = sharedScreenModel.getBpmFlow().value ?: 120f

                                                                                solfaScreenModel.generateMidiFile(bpm, savedPath)
                                                                                println("Fichier MIDI enregistré avec succès sous : $savedPath")
                                                                            }
                                                                        } catch (e: Exception) {
                                                                            e.printStackTrace()
                                                                        }
                                                                    }
                                                                }
                                                            },
                                                            icon = Icons.Filled.AudioFile
                                                        )
                                                    }
                                                }

                                                MyFAB(
                                                    onClick = { isShareExpanded = !isShareExpanded },
                                                    icon = Icons.Filled.Share
                                                )
                                            }
                                        }

                                        AnimatedVisibility(
                                            visible = isExpanded,
                                            enter = fadeIn() + scaleIn() + slideInVertically { it / 2 },
                                            exit = fadeOut() + scaleOut() + slideOutVertically { it / 2 }
                                        ) {
                                            MyFAB(
                                                onClick = {
                                                    sharedScreenModel.setMidiCtrl(!showMidiCtrl)
                                                },
                                                icon = if (showMidiCtrl) Icons.Filled.StopCircle else Icons.Filled.PlayCircle
                                            )
                                        }
                                        if (!showMidiCtrl && !isSearchActive) {
                                            MyFAB(
                                                onClick = {
                                                    sharedScreenModel.setExpandedFAB(!isExpanded)
                                                    refreshTrigeer++
                                                    sharedScreenModel.loadNewSong("$midiFile")
                                                },
                                                icon = if (isExpanded) Icons.Filled.Close else Icons.Filled.Menu
                                            )
                                        }
                                        AnimatedVisibility(
                                            visible = showMidiCtrl,
                                            enter = fadeIn() + scaleIn() + slideInVertically { it / 2 },
                                            exit = fadeOut() + scaleOut() + slideOutVertically { it / 2 }
                                        ) {
                                            Box(
                                                modifier = Modifier.fillMaxWidth(0.9f)
                                            ) {
                                                if (player != null) {
                                                    MidiControlPanel(
                                                        isPause = isPos,
                                                        currentPos = currentPos,
                                                        volume = volumelevel,
                                                        duration = duration,
                                                        solfaScrollState,
                                                        onPlayPauseClick = {
                                                            sharedScreenModel.togglePlayPause()
                                                        },
                                                        onSeek = { newPos ->
                                                            sharedScreenModel.setDragging(true)
                                                            sharedScreenModel.seekTo(newPos)
                                                            scope.launch {
                                                                delay(100)
                                                                sharedScreenModel.setDragging(false)
                                                            }
                                                            //println("DrawerUI:335: mihetsika $newPos")
                                                        },
                                                        mediaPlayer = player,
                                                        onVolumeChange = { newVolume ->
                                                            sharedScreenModel.setVolume(newVolume)
                                                            //                                        println("Changement volume $newVolume -l $volumelevel")
                                                        },
                                                        onVoiceVolumeChange = { index, volume ->
                                                            player?.updateVoiceVolume(index, volume)
                                                        },
                                                        sharedScreenModel = sharedScreenModel
                                                    )
                                                } else {
                                                    Text("Sélectionner un morceau")
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }) { paddingValues ->

                    Column(
                        modifier = Modifier
                            .fillMaxSize()
                            .padding(paddingValues)
                    ) {
                        Box(
                            modifier = Modifier
                                .fillMaxWidth()
                                .weight(1f)
                        ) {
                            content(PaddingValues(0.dp))

                            androidx.compose.animation.AnimatedVisibility(
                                visible = isQrVisible,
                                enter = slideInVertically(
                                    initialOffsetY = { fullHeight -> fullHeight }
                                ) + fadeIn(),
                                exit = slideOutVertically(
                                    targetOffsetY = { fullHeight -> fullHeight }
                                ) + fadeOut()
                            ) {
                                QRDisplay(
                                    sharedScreenModel = sharedScreenModel,
                                    fileRepository = solfaScreenModel.fileRepository
                                )
                            }

                            if (createMode) {
                                NewPartition(
                                    onCreate = { partMtdata ->
                                        solfaScreenModel.newSolfa(partMtdata)
                                        sharedScreenModel.toggleCreateMode(!createMode)
                                        sharedScreenModel.toggleEditorMode(createMode)
                                        if (!isAndroid) {
                                            sharedScreenModel.toggleSourceMode()
                                        }
                                    },
                                    onDismissRequest = {
                                        sharedScreenModel.toggleCreateMode(false)
                                    },
                                    isAndroid
                                )
                            }

                            var isHovered by remember { mutableStateOf(false) }
                            val offsetX by animateDpAsState(targetValue = if (isHovered || isSearchActive) 0.dp else 15.dp)

                            androidx.compose.animation.AnimatedVisibility(
                                visible = !isEditMode && !isQrVisible && !createMode && !isExpanded,
                                modifier = Modifier
                                    .align(Alignment.TopEnd)
                                    .padding(top = 15.dp)
                                    .offset(x = offsetX)
                                    .pointerInput(Unit) {
                                        awaitPointerEventScope {
                                            while (true) {
                                                val event = awaitPointerEvent()
                                                when (event.type) {
                                                    PointerEventType.Enter -> isHovered = true
                                                    PointerEventType.Exit -> isHovered = false
                                                }
                                            }
                                        }
                                    }
                            ) {
                                IconButton(
                                    onClick = {
                                        if (isSearchActive) {
                                            sharedScreenModel.showSearchMenu(false)
                                            sharedScreenModel.updateSearchTxt("")
                                            textInput = ""
                                        } else {
                                            sharedScreenModel.showSearchMenu(true)
                                            scope.launch {
                                                delay(100)
                                                focusRequester.requestFocus()
                                            }
                                        }
                                    },
                                    modifier = Modifier
                                        .size(55.dp)
                                        .alpha(0.6f)
                                        .background(
                                            color = MaterialTheme.colorScheme.tertiary,
                                            shape = CircleShape
                                        )
                                ) {
                                    Icon(
                                        imageVector = if (isSearchActive) Icons.Default.Close else Icons.Default.Search,
                                        contentDescription = null,
                                        tint = MaterialTheme.colorScheme.onTertiary
                                    )
                                }
                            }

                            androidx.compose.animation.AnimatedVisibility(
                                visible = isSearchActive && textInput.isNotEmpty(),
                                enter = fadeIn() + expandVertically(),
                                exit = fadeOut() + shrinkVertically(),
                                modifier = Modifier
                                    .align(Alignment.TopCenter)
                                    .fillMaxWidth(0.85f)
                                    .padding(top = 8.dp)
                                    .padding(bottom = if (isAndroid && isNumericKeyboard) keyboardHeightDp else 0.dp)
                            ) {
                                Card(
                                    elevation = CardDefaults.cardElevation(defaultElevation = 8.dp),
                                    shape = RoundedCornerShape(12.dp),
                                    colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface),
                                    modifier = Modifier.fillMaxHeight()
                                ) {
                                    val sortedSongs = remember(filteredSongs) {
                                        filteredSongs.sortedBy { item ->
                                            item.path.startsWith("assets://")
                                        }
                                    }
                                    LazyColumn(Modifier.fillMaxSize()) {
                                        if (sortedSongs.isEmpty() && textInput.isNotEmpty()) {
                                            item {
                                                ListItem(
                                                    headlineContent = {
                                                        Text(
                                                            text = "Partition non trouvée pour \"$textInput\"",
                                                            color = MaterialTheme.colorScheme.error,
                                                            fontWeight = FontWeight.Medium,
                                                            fontSize = 14.sp
                                                        )
                                                    },
                                                    supportingContent = {
                                                        Text(
                                                            text = "Essayez un autre.",
                                                            fontSize = 12.sp,
                                                            color = MaterialTheme.colorScheme.onSurfaceVariant
                                                        )
                                                    },
                                                    leadingContent = {
                                                        Icon(
                                                            imageVector = Icons.Default.SearchOff,
                                                            contentDescription = null,
                                                            tint = MaterialTheme.colorScheme.error
                                                        )
                                                    }
                                                )
                                            }
                                        }
                                        itemsIndexed(sortedSongs, key = { _, item -> item.path }) { index, item ->
                                            val isFavorite = favoritePaths.contains(item)
                                            ListItem(
                                                leadingContent = {
                                                    Icon(
                                                        imageVector = if (item.path.startsWith("assets://")) Icons.Default.ArrowDropDownCircle else Icons.Default.Folder,
                                                        contentDescription = null,
                                                        modifier = Modifier.size(30.dp)
                                                    )
                                                },
                                                headlineContent = { Text(item.title) },
                                                supportingContent = { Text(item.contentTitle, maxLines = 1) },
                                                trailingContent = {
                                                    IconButton(
                                                        onClick = { sharedScreenModel.toggleFavorite(item.path) },
                                                        modifier = Modifier.size(25.dp)
                                                    ) {
                                                        Icon(
                                                            imageVector = Icons.Default.Star,
                                                            contentDescription = null,
                                                            tint = if (!isFavorite) Color.LightGray else Color(
                                                                0xFFFFD700
                                                            )
                                                        )
                                                    }
                                                },
                                                modifier = Modifier.clickable {
                                                    sharedScreenModel.updateSearchTxt("")
                                                    sharedScreenModel.reset()
                                                    solfaScreenModel.loadFromFile(item.path)
                                                    sharedScreenModel.stopMidi()
                                                    sharedScreenModel.seekTo(0f)
                                                    sharedScreenModel.setTranspositionInterval(0)
                                                })
                                            HorizontalDivider()
                                        }
                                    }
                                }
                            }

                            // --- CLAVIER NUMÉRIQUE PERSONNALISÉ (Sur couche supérieure) ---
                            androidx.compose.animation.AnimatedVisibility(
                                visible = isSearchActive && isAndroid && isNumericKeyboard,
                                enter = slideInVertically(initialOffsetY = { fullHeight -> fullHeight }) + fadeIn(),
                                exit = slideOutVertically(targetOffsetY = { fullHeight -> fullHeight }) + fadeOut(),
                                modifier = Modifier.align(Alignment.BottomCenter)
                            ) {
                                CustomKeyboard(
                                    modifier = Modifier.onGloballyPositioned { coordinates ->
                                        keyboardHeightDp = with(density) { coordinates.size.height.toDp() }
                                    },
                                    onDigitClick = { digit ->
                                        textInput += digit
                                        sharedScreenModel.updateSearchTxt(textInput)
                                    },
                                    onDeleteClick = {
                                        if (textInput.isNotEmpty()) {
                                            textInput = textInput.dropLast(1)
                                            sharedScreenModel.updateSearchTxt(textInput)
                                        }
                                    },
                                    onClearClick = {
                                        textInput = ""
                                        sharedScreenModel.updateSearchTxt("")
                                    },
                                    onPrefixClick = { prefix ->
                                        sharedScreenModel.updateSearchTxt(prefix)
                                    },
                                    isFullScreen = isFullScreenEnabled
                                )
                            }

                        }

                        AnimatedVisibility(
                            visible = solfaKeyboardState.isVisible && solfaKeyboardState.isDialogActive && isAndroid,
                            enter = slideInVertically(initialOffsetY = { fullHeight -> fullHeight }) + fadeIn(),
                            exit = slideOutVertically(targetOffsetY = { fullHeight -> fullHeight }) + fadeOut()
                        ) {
                            SolfaKeyboard(
                                currentVoiceIndex = solfaKeyboardState.activeVoiceIndex,
                                currentValue = solfaKeyboardState.currentText,
                                onNoteClick = { note -> solfaKeyboardState.onNoteInput?.invoke(note) },
                                onTabClick = { solfaKeyboardState.onTabNextVoice?.invoke() },
                                onBackspaceClick = { solfaKeyboardState.onBackspace?.invoke() },
                                onCloseClick = { solfaKeyboardState.onCloseDialog?.invoke() },
                                onBuildClick = { solfaKeyboardState.onBuildEdit?.invoke() },
                                onCustomSymbolClick = { symbol -> solfaKeyboardState.onCustomSymbol?.invoke(symbol) },
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .fillMaxHeight(0.3f)
                            )
                        }
                    }

                }
            }
        }
        }
    })
}

@Composable
private fun MyFAB(
    onClick: () -> Unit,
    size: Dp ?= 55.dp,
    icon: ImageVector
) {
    FloatingActionButton(
        onClick = onClick,
        modifier = Modifier.size(size!!),
        containerColor = MaterialTheme.colorScheme.onSecondary.copy(alpha = 0.1f),
        elevation = FloatingActionButtonDefaults.elevation(0.dp, 0.dp, 0.dp, 0.dp)
    ) {
        Icon(
            imageVector = icon,
            contentDescription = null,
            tint = MaterialTheme.colorScheme.primary
        )
    }
}

val LocalFullscreenController = staticCompositionLocalOf<(Boolean) -> Unit> {
    { _ -> }
}