package mg.dot.feufaro

import SharedScreenModel
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.Code
import androidx.compose.material3.Icon
import androidx.compose.material3.IconToggleButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
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 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.solfa.ColorPrefixB
import mg.dot.feufaro.solfa.EditSourceCompose
import mg.dot.feufaro.solfa.LazyVerticalGridTUO
import mg.dot.feufaro.ui.MainScreenWithDrawer
import mg.dot.feufaro.ui.MyVerticalScrollbar
import mg.dot.feufaro.viewmodel.SolfaScreenModel
import java.io.ObjectStreamException
import kotlin.math.roundToInt

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 = remember(tuoList, measure, stanza) { GridTUOData(measure, tuoList, stanza) }
        val coroutineScope = rememberCoroutineScope()
        val scrollState = rememberScrollState()
        var showContextualMenu = false
        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("")
        }

        val tuoEditState by sharedScreenModel.tuoEditState.collectAsState()
        val isFullScreenEnabled by sharedScreenModel.isFullScreen.collectAsState()

        LaunchedEffect(tuoEditState) {
            tuoEditState?.let { state ->
                coroutineScope.launch(Dispatchers.IO) {
                    solfaScreenModel.saveTUOEdit(state)
                }
                sharedScreenModel.closeTUOEditor()
            }
        }
        DisposableEffect(Unit) {
            onDispose {
                DeepLinkHandler.onSongReceived = null
            }
        }

        MainScreenWithDrawer(
            solfaScreenModel,
            sharedScreenModel,
            qrCodeResult = qrCodeResult,
            onScannerButtonClick = {
                isScanning = true
            },
            solfaScrollState = scrollState
        ) { paddingValues ->
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(paddingValues)
                    .padding(horizontal = 16.dp)
            ) {
                Column(
                    Modifier
                        .verticalScroll(scrollState)
                        .windowInsetsPadding(
                            if (isFullScreenEnabled) WindowInsets(0)
                            else WindowInsets.safeDrawing.only(WindowInsetsSides.Bottom)
                        )
                        .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, style = MaterialTheme.typography.bodyLarge, fontWeight = FontWeight.Bold)
                            Text(
                                text = songKey,
                                style = MaterialTheme.typography.bodyLarge,
                                modifier = Modifier.background(MaterialTheme.colorScheme.tertiary.copy(alpha = 0.1f))
                                    .padding(horizontal = 4.dp)
                            )
                            Text(text = measureString, style = MaterialTheme.typography.bodyLarge)
                            Text(text = "Stanza: $stanza", style = MaterialTheme.typography.bodyLarge)
                            //ScreenTranspose.Content()
                        }
                        LazyVerticalGridTUO(
                            gridTUOData,
                            gridWidthPx = gridWidthPx,
                            sharedScreenModel = sharedScreenModel,
                            onGridWidthMeasured = { width -> gridWidthPx = width }
                        )
                        EditSourceCompose(sharedScreenModel, solfaScreenModel)
                        FlowRow(
                            horizontalArrangement = Arrangement.spacedBy(16.dp),
                            verticalArrangement = Arrangement.spacedBy(4.dp)
                        ) {
                            val isEditMode = sharedScreenModel.sourceModeState.value
                            IconToggleButton(
                                checked = isEditMode,
                                onCheckedChange = { sharedScreenModel.toggleSourceMode() },
                                modifier = Modifier.size(40.dp)
                            ) {
                                Icon(
                                    imageVector = if (isEditMode) Icons.Filled.Check else Icons.Filled.Code,
                                    contentDescription = "Mode édition",
                                    tint = if (isEditMode) ColorPrefixB else Color.Gray
                                )
                            }
                            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 = 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
    }
}
