package mg.dot.feufaro

import SharedScreenModel
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.safeDrawing
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Popup
import mg.dot.feufaro.solfa.LazyVerticalGridTUO
import mg.dot.feufaro.ui.MainScreenWithDrawer
import kotlin.math.roundToInt
import cafe.adriel.voyager.core.screen.Screen
import cafe.adriel.voyager.koin.koinScreenModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import mg.dot.feufaro.data.GridTUOData
import mg.dot.feufaro.ui.MyVerticalScrollbar
import mg.dot.feufaro.viewmodel.SolfaScreenModel
import java.io.ObjectStreamException

object ScreenSolfa : Screen {
    @Composable
    override fun Content() {
        val solfaScreenModel = koinScreenModel<SolfaScreenModel>()
        var menuPosition by remember { mutableStateOf(Offset.Zero) }
        var gridWidthPx by rememberSaveable { mutableStateOf(0) }
        val sharedScreenModel = koinScreenModel<SharedScreenModel>()
        val tuoList by sharedScreenModel.tuoList.collectAsState()
        val measure by sharedScreenModel.measure.collectAsState()
        val stanza by sharedScreenModel.stanza.collectAsState()
        val gridTUOData = GridTUOData(measure, tuoList, stanza)
        val coroutineScope = rememberCoroutineScope()
        val scrollState = rememberScrollState()
        var  viewportHeight by remember { mutableStateOf(0) }

        var isScanning by remember { mutableStateOf(false) }
        var qrCodeResult by remember { mutableStateOf("Aucun code scanné") }
        LaunchedEffect(Unit) {
            DeepLinkHandler.onSongReceived = { content, filePath ->
                println("2DeepLink: LaunchedEffect reçoit → $filePath")
                sharedScreenModel.reset()
                solfaScreenModel.loadFromFile(filePath)
            }
//            DeepLinkHandler.consumePending("")
        }

        DisposableEffect(Unit) {
            onDispose {
                DeepLinkHandler.onSongReceived = null
            }
        }

        MainScreenWithDrawer(
            solfaScreenModel,
            sharedScreenModel,
            qrCodeResult = qrCodeResult,
            onScannerButtonClick = {
                isScanning = true
            },
            solfaScrollState = scrollState
        ) { paddingValues ->
            Box(
                Modifier.fillMaxSize().padding(paddingValues)
                    .padding(horizontal = 16.dp)
            ) {
                Column(
                    Modifier
                        .verticalScroll(scrollState)
                        .pointerInput(Unit) {
                            detectTapGestures(
                                onDoubleTap = { offset ->
                                    menuPosition = offset
                                    showContextualMenu = true
                                }
                            )
                        }
                        .onGloballyPositioned { coordinates ->
                            viewportHeight = coordinates.size.height
                        },
                    horizontalAlignment = Alignment.CenterHorizontally,
                ) {
                    if (showContextualMenu) {
                        Popup(
                            alignment = Alignment.TopStart,
                            offset = IntOffset(
                                menuPosition.x.roundToInt(),
                                menuPosition.y.roundToInt()
                            ),
                            onDismissRequest = {
                                showContextualMenu = false
                            }
                        ) {
                            ContextualMenu(onMenuItemClick = { item ->
                                println("Clicked: $item")
                                showContextualMenu = false
                            })
                        }
                    }
                    Column(
                        modifier = Modifier
                            .fillMaxSize()
                    ) {
                        FlowRow(
                            modifier = Modifier.fillMaxWidth()
                                .windowInsetsPadding(WindowInsets.safeDrawing)
                                .padding(start = 8.dp, end = 8.dp, top = 8.dp),
                            horizontalArrangement = Arrangement.spacedBy(16.dp),
                            verticalArrangement = Arrangement.spacedBy(4.dp)
                        ) {
                            val measureString: String by sharedScreenModel.measure.collectAsState()
                            val songTitle: String by sharedScreenModel.songTitle.collectAsState()
                            val songKey: String by sharedScreenModel.songKey.collectAsState()
                            Text(text = songTitle, fontWeight = FontWeight.Bold)
                            Text(
                                text = songKey,
                                modifier = Modifier.background(Color(0xff, 0xea, 0xe7))
                                    .padding(horizontal = 4.dp)
                            )
                            Text(text = measureString)
                            Text(text = "Stanza: $stanza")
                            ScreenTranspose.Content()
                        }
                        LazyVerticalGridTUO(
                            gridTUOData,
                            gridWidthPx = gridWidthPx,
                            sharedScreenModel = sharedScreenModel,
                            onGridWidthMeasured = { width -> gridWidthPx = width }
                        )
                        FlowRow(
                            horizontalArrangement = Arrangement.spacedBy(16.dp),
                            verticalArrangement = Arrangement.spacedBy(4.dp)
                        ) {
                            MGButton(onClick = {
                                //showContent = !showContent

                                solfaScreenModel.loadNextInPlaylist()
                            }, modifier = Modifier.height(40.dp)) {
                                val nextLabel: String by sharedScreenModel.nextLabel.collectAsState()
                                Text(nextLabel)
                            }
                            MGButton(onClick = {
                                solfaScreenModel.loadCustomFile()
                            }) {
                                val loadFile: String by sharedScreenModel.loadFile.collectAsState()
                                Text(loadFile)
                            }
                        }
                        FlowRow(
                            modifier = Modifier.fillMaxWidth()
                                .windowInsetsPadding(WindowInsets.safeDrawing)
                                .padding(start = 8.dp, end = 8.dp, top = 8.dp),
                            horizontalArrangement = Arrangement.spacedBy(16.dp),
                            verticalArrangement = Arrangement.spacedBy(4.dp)
                        ) {
                            val nbStanzas: Int by sharedScreenModel.nbStanzas.collectAsState()
                            for (i in 1..nbStanzas) {
                                MGButton(
                                    enabled = (i != stanza.toInt()),
                                    onClick = {
                                        sharedScreenModel.setStanza(i)
                                        coroutineScope.launch {
                                            scrollState.animateScrollTo(0)
                                        }
                                    },
                                    modifier = Modifier.padding(horizontal = 4.dp)
                                ) {
                                    Text("$i")
                                }
                            }
                            val songAuthor: String by sharedScreenModel.songAuthor.collectAsState()
                            val songComposer: String by sharedScreenModel.songComposer.collectAsState()
                            val songRhythm: String by sharedScreenModel.songRhythm.collectAsState()
                            Text(text = songAuthor, fontStyle = FontStyle.Italic)
                            Text(text = songRhythm)
                            Text(text = songComposer)

                        }
                        Row (
                            modifier = Modifier
                                .height(75.dp)
                        ) {
                        }
                    }
                }
                MyVerticalScrollbar(
                    scrollState,
                    modifier = Modifier.align(Alignment.CenterEnd)
                ) {}
            }
        }
    }

    @Throws(ObjectStreamException::class) // C'est une méthode de sérialisation Java, donc l'exception est nécessaire
    private fun readResolve(): Any {
        return this // Toujours retourner l'instance unique de ce singleton
    }
}
