package mg.dot.feufaro.ui

import SharedScreenModel
import androidx.compose.animation.*
import androidx.compose.foundation.*
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.material.icons.Icons
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.RectangleShape
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import mg.dot.feufaro.pdf.PrintSettings
import mg.dot.feufaro.pdf.defaultPrintSettings
import mg.dot.feufaro.ui.PrintSettingsDialog
import mg.dot.feufaro.pdf.rememberPdfExportAction
import mg.dot.feufaro.solfa.Solfa
import mg.dot.feufaro.viewmodel.SolfaScreenModel

@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)
    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()

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)
        }
    }
}

    LaunchedEffect(isSearchActive) {
        if (isSearchActive) {
            focusRequester.requestFocus()
        }
    }
    val fileContent = sharedScreenModel.fileContent.value ?: ""
    LaunchedEffect(Unit) {
        if(fileContent == "") {
            sharedScreenModel.loadNewSong("$midiFile")
        }
    }
    ModalNavigationDrawer(drawerState = drawerState, drawerContent = {
        SimpleDrawerContent(
            items,
            solfaScreenModel,
            sharedScreenModel,
            currentActivePath,
            drawerState,
            scope,
            onScannerButtonClick = {
                scope.launch { drawerState.close() }
                onScannerButtonClick()
            },
            onSongSelected = { newSong ->
                sharedScreenModel.loadNewSong("$midiFile")
            }
            )
    }, 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
        )

        if (showPrintSettings) {
            PrintSettingsDialog(
                initialSettings = defaultPrintSettings(),
//                nbStanza = nbStanzas,
                onDismiss = { showPrintSettings = false },
                onConfirm = { settings ->
                    showPrintSettings = false
                    pdfExportAction(settings)
                }
            )
        }
        Scaffold(contentWindowInsets = WindowInsets(0, 0, 0, 0), topBar = {
            TopAppBar(
                modifier = Modifier.height(55.dp).windowInsetsPadding(WindowInsets.statusBars), title = {
                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,
                        )
                    }
                }
            }, navigationIcon = {
                IconButton(onClick = {
                    scope.launch { drawerState.open() }
                }) {
                    Icon(Icons.Filled.Menu, contentDescription = "Ouvrir Menu")
                }
            }, actions = {
                Text(
                    text = songKey,
                    fontSize = 25.sp,
                    fontWeight = FontWeight.Black,
                )
                Spacer(Modifier.width(8.dp))

            }, 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() //horizontalAlignment = Alignment.CenterHorizontally
            ) {
                Column(
                    modifier = Modifier.fillMaxWidth().padding(5.dp), horizontalAlignment = Alignment.End,
                    verticalArrangement = Arrangement.spacedBy(7.dp)
                ) {
                    AnimatedVisibility(
                        visible = isExpanded and !showMidiCtrl,
                        enter = fadeIn() + scaleIn() + slideInVertically { it / 2 },
                        exit = fadeOut() + scaleOut() + slideOutVertically { it / 2 }
                    ) {
                        Row {
                            Column {
                                FloatingActionButton(
                                    onClick = {
                                        sharedScreenModel.descGridCount(1)
                                    }, modifier = Modifier.size(30.dp).alpha(0.45f)
                                ) {
                                    Icon(
                                        Icons.Default.Remove,
                                        contentDescription = null,
                                        tint = Color.Blue
                                    )
                                }
                            }
                            Column {
                                FloatingActionButton(
                                    onClick = {
                                        sharedScreenModel.addGridCount(1)
                                    }, modifier = Modifier.size(30.dp).alpha(0.45f)
                                ) {
                                    Icon(
                                        Icons.Default.Add,
                                        contentDescription = null,
                                        tint = Color.Blue
                                    )
                                }
                            }
                        }


                    }
                    AnimatedVisibility(
                        visible = isExpanded and !showMidiCtrl,
                        enter = fadeIn() + scaleIn() + slideInVertically { it / 2 },
                        exit = fadeOut() + scaleOut() + slideOutVertically { it / 2 }
                    ) {
                        FloatingActionButton(
                            onClick = {
                                sharedScreenModel.toggleQRCodeVisibility()
                                sharedScreenModel.setExpandedFAB(false)
                            }, modifier = Modifier.alpha(0.45f)
                        ) {
                            Icon(
                                imageVector = Icons.Filled.QrCode,
                                contentDescription = "share qr",
                                tint = Color.Blue
                            )
                        }
                    }


                    AnimatedVisibility(
                        visible = isExpanded and !showMidiCtrl,
                        enter = fadeIn() + scaleIn() + slideInVertically { it / 2 },
                        exit = fadeOut() + scaleOut() + slideOutVertically { it / 2 }
                    ) {
                        FloatingActionButton(
                            onClick = {
                                showPrintSettings = !showPrintSettings
                            }, modifier = Modifier.alpha(0.45f)
                        ) {
                            Icon(
                                imageVector = Icons.Filled.Print,
                                contentDescription = "Imprimer",
                                tint = Color.Blue
                            )
                        }
                    }

                    AnimatedVisibility(
                        visible = isExpanded,
                        enter = fadeIn() + scaleIn() + slideInVertically { it / 2 },
                        exit = fadeOut() + scaleOut() + slideOutVertically { it / 2 }
                    ) {
                        FloatingActionButton(
                            onClick = {
                                sharedScreenModel.setMidiCtrl(!showMidiCtrl)
                            }, modifier = Modifier.alpha(0.45f)
                        ) {
                            Icon(
                                imageVector = if(showMidiCtrl) Icons.Filled.StopCircle else Icons.Filled.PlayCircle,
                                contentDescription = "Jouer",
                                tint = Color.Blue
                            )
                        }
                    }
                    if (!showMidiCtrl) {
                        FloatingActionButton(
                            onClick = {
                                sharedScreenModel.setExpandedFAB(!isExpanded)
                                refreshTrigeer++
                                sharedScreenModel.loadNewSong("$midiFile")
                            }, modifier = Modifier.alpha(0.45f)
                        ) {
                            Icon(
                                imageVector = if (isExpanded) Icons.Filled.Close else Icons.Filled.Menu,
                                contentDescription = "MenuFermer",
                                tint = Color.Blue
                            )
                        }
                    }
                    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)
                                    }
                                )
                            } else {
                                Text("Sélectionner un morceau")
                            }
                        }
                    }
                }
            }

        }) { paddingValues ->

            Box(
                modifier = Modifier.fillMaxSize().padding(paddingValues).windowInsetsPadding(WindowInsets.ime)
            ) {
                content(PaddingValues(0.dp))
                if (sharedScreenModel.isQRCodeVisible.value) {
                    QRDisplay(sharedScreenModel = sharedScreenModel)
                } else {
                    if (filteredSongs.isNotEmpty()) {
                        Column(
                            modifier = Modifier.fillMaxWidth().fillMaxHeight().align(Alignment.TopCenter)
                                .background(MaterialTheme.colorScheme.surface).border(
                                    1.dp,
                                    MaterialTheme.colorScheme.outlineVariant,
                                    shape = MaterialTheme.shapes.medium
                                )
                        ) {
                            if (filteredSongs.isNotEmpty()) {
                                LazyColumn(Modifier.fillMaxSize()) {
                                    itemsIndexed(filteredSongs) { index, item ->
                                        ListItem(
                                            headlineContent = { Text(item.title) },
                                            supportingContent = { Text(item.contentTitle, maxLines = 1) },
                                            modifier = Modifier.clickable {
                                                sharedScreenModel.updateSearchTxt("")
                                                sharedScreenModel.reset()
                                                solfaScreenModel.loadFromFile(item.path)
                                                sharedScreenModel.stopMidi()
                                                sharedScreenModel.seekTo(0f)
                                            })
                                        HorizontalDivider()
                                    }
                                }
                            } else {
                                content(paddingValues)
                            }
                        }
                    }


                    Box(
                        modifier = Modifier.fillMaxSize().fillMaxWidth(0.75f).align(Alignment.Center)
                            .padding(paddingValues)
                    ) {
                        Row(
                            modifier = Modifier.align(Alignment.TopEnd).padding(16.dp),
                            verticalAlignment = Alignment.CenterVertically,
                            horizontalArrangement = Arrangement.spacedBy(8.dp)
                        ) {
                            Column(

                            ) {

                                AnimatedContent(
                                    targetState = isSearchActive, label = "Search Transition"
                                ) { targetIsActive ->
                                    if (targetIsActive) {
                                        TextField(
                                            value = textInput,
                                            onValueChange = { newValue ->
                                                textInput = newValue
                                                sharedScreenModel.updateSearchTxt(newValue)
                                            },
                                            placeholder = {
                                                Text("... ...")
                                            },
                                            textStyle = MaterialTheme.typography.titleLarge.copy(
                                                fontSize = 17.sp,
                                                fontWeight = FontWeight.Bold,
                                                color = MaterialTheme.colorScheme.onSurface
                                            ),
                                            modifier = Modifier.focusRequester(focusRequester).fillMaxWidth(0.45f)
                                                .border(
                                                    width = 2.dp,
                                                    color = Color.Gray,
                                                    shape = RoundedCornerShape(8.dp)
                                                )
                                                .alpha(0.6f)
                                        )
                                    }
                                }
                            }
                            Column(

                            ) {
                                IconButton(
                                    onClick = {
                                        sharedScreenModel.showSearchMenu(!isSearchActive)
                                        sharedScreenModel.updateSearchTxt("")
                                        textInput = ""
                                    }, modifier = Modifier.size(56.dp).alpha(0.45f).background(
                                            color = Color.Blue, shape = CircleShape
                                        )
                                ) {
                                    Icon(
                                        if(isSearchActive) Icons.Default.Close else Icons.Default.Search,
                                        contentDescription = "la recherche",
                                        tint = Color.White
                                    )
                                }
                            }

                        }
                    }


                }
            }
        }
    })
}