package mg.dot.feufaro.ui

import SharedScreenModel
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ListAlt
import androidx.compose.material.icons.automirrored.filled.NoteAdd
import androidx.compose.material.icons.automirrored.filled.PlaylistPlay
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.rotate
import androidx.compose.ui.draw.scale
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import feufaro.composeapp.generated.resources.Res
import feufaro.composeapp.generated.resources.icon
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import mg.dot.feufaro.data.DrawerItem
import mg.dot.feufaro.getPlatform
import mg.dot.feufaro.solfa.Solfa
import mg.dot.feufaro.viewmodel.SolfaScreenModel
import org.jetbrains.compose.resources.painterResource

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SimpleDrawerContent(
    items: List<DrawerItem>,
    solfaScreenModel: SolfaScreenModel,
    sharedScreenModel: SharedScreenModel,
    activePath: String = Solfa.currentFile,
    drawerState: DrawerState,
    scope: CoroutineScope,
    onScannerButtonClick: () -> Unit,
    onSongSelected: (String) -> Unit,
    onSettingsCheck: () -> Unit,
    onAboutCheck: () -> Unit,
) {
    var searchTxt by remember { mutableStateOf("") }

    val context = getPlatform()

    val midi = "whawyd3.mid"

    val internalList by sharedScreenModel.internalItems.collectAsState()
    val externalList by sharedScreenModel.externalItems.collectAsState()
    val playList by sharedScreenModel.playlistItems.collectAsState()
    val favoriteLists by sharedScreenModel.playlistItems.collectAsState()
    val listState = rememberLazyListState()

    var internalExpanded by remember { mutableStateOf(false) }
    var externalExpanded by remember { mutableStateOf(false) }
    var playListExpanded by remember { mutableStateOf(false) }

    val editMode by sharedScreenModel.modeEditor.collectAsState()
    val chordView by sharedScreenModel.harmonyView.collectAsState()
    ModalDrawerSheet(
        modifier = Modifier.width(300.dp)
    ) {
        Column(modifier = Modifier.fillMaxWidth()) {
            // SWITCHES
            Column(
                modifier = Modifier
                    .fillMaxWidth(),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceEvenly,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    CustomSwitchItem(
                        checked = editMode,
                        onCheckedChange = { newState ->
                            sharedScreenModel.toggleEditorMode(newState)
                        },
                        thumbIcon = Icons.Default.Edit,
                        label = "Edition"
                    )

                    CustomSwitchItem(
                        checked = chordView,
                        onCheckedChange = { newStateMod ->
                            sharedScreenModel.toggleHarmonyMode(newStateMod)
                        },
                        thumbIcon = Icons.Default.MusicNote,
                        label = "Analyse d\'accords"
                    )
                    Column(
                        horizontalAlignment = Alignment.CenterHorizontally,
                        verticalArrangement = Arrangement.Center
                    ) {
                        OutlinedButton(
                            onClick = { sharedScreenModel.toggleCreateMode(true) },
                            shape = IconButtonDefaults.filledShape,
                            colors = ButtonDefaults.buttonColors(
                                containerColor = Color.Transparent,
                                contentColor = MaterialTheme.colorScheme.onBackground
                            )
                        ) {
                            Icon(
                                imageVector = Icons.AutoMirrored.Default.NoteAdd, contentDescription = null, tint = MaterialTheme.colorScheme.error
                            )
                        }

                        Spacer(modifier = Modifier.height(4.dp))

                        Text(
                            text = "Créer une partition",
                            style = MaterialTheme.typography.labelSmall,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    }
                }
            }

            Box(modifier = Modifier.weight(1f).padding(0.dp, 10.dp)) {

                MyVerticalScrollbar(
                    lazyListState = listState,
                    modifier = Modifier
                        .align(Alignment.CenterEnd)
                        .fillMaxHeight()
                        .padding(end = 2.dp)
                ){
                    LazyColumn(
                        state = listState,
                        modifier = Modifier.fillMaxSize()
                    ) {
                        stickyHeader {
                            DrawerHeaderSticky(
                                title = "Solfa disponibles",
                                icon = Icons.AutoMirrored.Filled.ListAlt,
                                isExpanded = internalExpanded,
                                onToggle = { internalExpanded = !internalExpanded },
                                count = internalList.size
                            )
                        }

                        if (internalExpanded) {
                            items(internalList) { item ->
                                val isSelected = item.path == activePath
                                val isFavorite = favoriteLists.contains(item)
                                
                                NavigationDrawerItem(
                                    icon = {
                                        Text("\uD834\uDD1E", fontSize = 22.sp)
                                    },
                                    label = { DrawerItemLabel(item) },
                                    badge = {
                                        IconButton(
                                            onClick = {
                                                sharedScreenModel.toggleFavorite(item.path)
                                            },
                                            modifier = Modifier.size(32.dp)
                                        ) {
                                            Icon(
                                                imageVector = Icons.Default.PlaylistAddCircle,
                                                contentDescription = null,
                                                tint = if (!isFavorite) Color.LightGray else Color(0xFFFFD700),
                                                modifier = Modifier.size(18.dp)
                                            )
                                        }
                                    },
                                    selected = isSelected,
                                    onClick = {
                                        scope.launch { drawerState.close() }
                                        sharedScreenModel.reset()
                                        solfaScreenModel.loadFromFile(item.path)
                                        onSongSelected(midi)
                                    },
                                    shape = RoundedCornerShape(5.dp),
                                    modifier = Modifier.padding(horizontal = 12.dp, vertical = 2.dp),
                                    colors = NavigationDrawerItemDefaults.colors(
                                        selectedContainerColor = MaterialTheme.colorScheme.primary.copy(alpha = 0.12f),
                                        selectedTextColor = MaterialTheme.colorScheme.primary
                                    )
                                )
                            }
                        }

                        stickyHeader {
                            DrawerHeaderSticky(
                                title = "Personnel",
                                icon = Icons.Default.LibraryMusic,
                                isExpanded = externalExpanded,
                                onToggle = { externalExpanded = !externalExpanded },
                                count = externalList.size
                            )
                        }

                        if (externalExpanded) {
                            items(externalList) { item ->
                                val isSelected = item.path == activePath
                                val isFavorite = favoriteLists.contains(item)

                                if (item.path != "") {
                                    NavigationDrawerItem(
                                        icon = {
                                            Text("♬", fontSize = 20.sp)
                                        },
                                        label = { DrawerItemLabel(item) },
                                        badge = {
                                            IconButton(
                                                onClick = {
                                                    sharedScreenModel.toggleFavorite(item.path)
                                                },
                                                modifier = Modifier.size(32.dp)
                                            ) {
                                                Icon(
                                                    imageVector = Icons.Default.PlaylistAddCircle,
                                                    contentDescription = null,
                                                    tint = if (!isFavorite) Color.LightGray else Color(0xFFFFD700),
                                                    modifier = Modifier.size(18.dp)
                                                )
                                            }
                                        },
                                        selected = isSelected,
                                        onClick = {
                                            scope.launch { drawerState.close() }
                                            sharedScreenModel.reset()
                                            solfaScreenModel.loadFromFile(item.path)
                                            onSongSelected(midi)
                                        },
                                        shape = RoundedCornerShape(5.dp),
                                        modifier = Modifier.padding(horizontal = 12.dp, vertical = 2.dp),
                                        colors = NavigationDrawerItemDefaults.colors(
                                            selectedContainerColor = MaterialTheme.colorScheme.secondary.copy(alpha = 0.5f),
                                            selectedTextColor = MaterialTheme.colorScheme.onSecondary
                                        )
                                    )
                                }
                            }
                        }

                        stickyHeader {
                            DrawerHeaderSticky(
                                title = "Playlist",
                                icon = Icons.AutoMirrored.Filled.PlaylistPlay,
                                isExpanded = playListExpanded,
                                onToggle = { playListExpanded = !playListExpanded },
                                count = playList.size
                            )
                        }

                        if (playListExpanded) {
                            itemsIndexed(playList) { index, item ->
                                if (item.path.isNotBlank()) {
                                    val isSelected = item.path == activePath

                                    NavigationDrawerItem(
                                        icon = {
                                            Text("♯", fontSize = 22.sp)
                                        },
                                        label = {
                                            DrawerItemLabel(item)
                                        },
                                        badge = {
                                            if (index > 0) {
                                                IconButton(
                                                    onClick = { sharedScreenModel.moveToTop(index) },
                                                    modifier = Modifier.size(30.dp)
                                                ) {
                                                    Icon(
                                                        imageVector = Icons.Default.VerticalAlignTop,
                                                        contentDescription = null,
                                                        modifier = Modifier.size(16.dp),
                                                        tint = MaterialTheme.colorScheme.onSecondary
                                                    )
                                                }
                                            }
                                            IconButton(
                                                onClick = { sharedScreenModel.toggleFavorite(item.path) },
                                                modifier = Modifier.size(30.dp)
                                            ) {
                                                Icon(
                                                    imageVector = Icons.Default.Star,
                                                    contentDescription = null,
                                                    tint = if (isSelected) MaterialTheme.colorScheme.background else MaterialTheme.colorScheme.tertiary
                                                )
                                            }
                                        },
                                        selected = isSelected,
                                        onClick = {
                                            scope.launch { drawerState.close() }
                                            sharedScreenModel.reset()
                                            solfaScreenModel.loadFromFile(item.path)
                                            onSongSelected(midi)
                                        },
                                        shape = RoundedCornerShape(5.dp),
                                        modifier = Modifier.padding(horizontal = 12.dp, vertical = 2.dp),
                                        colors = NavigationDrawerItemDefaults.colors(
                                            selectedContainerColor = MaterialTheme.colorScheme.tertiary.copy(alpha = 0.5f),
                                            selectedTextColor = MaterialTheme.colorScheme.onTertiary,
                                        )
                                    )
                                }
                            }
                        }
                    }
                }
            }
            HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant)
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(vertical = 8.dp, horizontal =  16.dp),
                horizontalArrangement = Arrangement.SpaceEvenly,
                verticalAlignment = Alignment.CenterVertically
            ) {
                TooltipBox(
                    positionProvider = TooltipDefaults.rememberPlainTooltipPositionProvider(),
                    tooltip = { PlainTooltip { Text("Feufaro") } },
                    state = rememberTooltipState()
                ) {
                    Image(
                        painter = painterResource(Res.drawable.icon),
                        contentDescription = null,
                        modifier = Modifier.size(45.dp)
                    )
                }

                TooltipBox(
                    positionProvider = TooltipDefaults.rememberPlainTooltipPositionProvider(),
                    tooltip = { PlainTooltip { Text("Importer un fichier") } },
                    state = rememberTooltipState()
                ) {
                    IconButton(onClick = {
                        solfaScreenModel.loadCustomFile()
                        scope.launch { drawerState.close() }
                    }) {
                        Icon(Icons.Default.FolderOpen, contentDescription = null, tint = MaterialTheme.colorScheme.onSecondary)
                    }
                }

                TooltipBox(
                    positionProvider = TooltipDefaults.rememberPlainTooltipPositionProvider(),
                    tooltip = { PlainTooltip { Text("Paramètres") } },
                    state = rememberTooltipState()
                ) {
                    IconButton(onClick = {
                        onSettingsCheck()
                        scope.launch { drawerState.close() }
                    }) {
                        Icon(Icons.Default.Settings, contentDescription = null, tint = MaterialTheme.colorScheme.onSecondary)
                    }
                }

                TooltipBox(
                    positionProvider = TooltipDefaults.rememberPlainTooltipPositionProvider(),
                    tooltip = { PlainTooltip { Text("À propos") } },
                    state = rememberTooltipState()
                ) {
                    IconButton(onClick = {
                        onAboutCheck()
                        scope.launch { drawerState.close() }
                    }) {
                        Icon(Icons.Default.Info, contentDescription = null, tint = MaterialTheme.colorScheme.onSecondary)
                    }
                }
            }
        }
    }
}

@Composable
fun DrawerHeaderSticky(
    title: String,
    icon: ImageVector,
    isExpanded: Boolean,
    onToggle: () -> Unit,
    count: Int
) {
    val rotation by animateFloatAsState(if (isExpanded) 180f else 0f)

    Surface(
        color = MaterialTheme.colorScheme.surface,
        modifier = Modifier.fillMaxWidth().clickable { onToggle() }
    ) {
        Row(
            modifier = Modifier.padding(16.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Icon(icon, contentDescription = null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(20.dp))
            Spacer(Modifier.width(12.dp))
            Text(
                text = title.uppercase(),
                modifier = Modifier.weight(1f),
                style = MaterialTheme.typography.titleSmall.copy(fontWeight = FontWeight.Bold),
                color = MaterialTheme.colorScheme.primary
            )
            Surface(
                color = MaterialTheme.colorScheme.error.copy(alpha = 0.1f),
                shape = MaterialTheme.shapes.extraSmall
            ) {
                Text(
                    text = count.toString() ,
                    modifier = Modifier.padding(horizontal = 6.dp, vertical = 2.dp),
                    style = MaterialTheme.typography.labelSmall,
                    color = MaterialTheme.colorScheme.error
                )
            }
            Icon(
                imageVector = Icons.Default.KeyboardArrowDown,
                contentDescription = null,
                modifier = Modifier.rotate(rotation)
            )
        }
    }
}

@Composable
fun DrawerItemLabel(item: DrawerItem) {
    Row(
        modifier = Modifier.fillMaxWidth(),
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.SpaceBetween
    ) {
        Column(modifier = Modifier.weight(1f)) {
            Text(text = item.title, fontWeight = FontWeight.SemiBold, style = MaterialTheme.typography.titleSmall)
            Text(text = item.contentTitle, style = MaterialTheme.typography.labelSmall, maxLines = 1)
        }
    }
}

@Composable
fun CustomSwitchItem(
    checked: Boolean,
    onCheckedChange: (Boolean) -> Unit,
    label: String,
    thumbIcon: ImageVector
) {
    Column(
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Switch(
            checked = checked,
            onCheckedChange = onCheckedChange,
            colors = SwitchDefaults.colors(
                checkedThumbColor = MaterialTheme.colorScheme.error,
                checkedTrackColor = MaterialTheme.colorScheme.error.copy(alpha = 0.5f),
                uncheckedThumbColor = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.4f),
                uncheckedTrackColor = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.1f),
                uncheckedBorderColor =  MaterialTheme.colorScheme.error.copy(alpha = 0.2f),
            ),
            modifier = Modifier.scale(0.8f),
            thumbContent = {
                Icon(
                    imageVector = if (checked) thumbIcon else Icons.Default.Visibility,
                    contentDescription = null,
                    modifier = Modifier.size(SwitchDefaults.IconSize)
                )
            }
        )
        Text(
            text = label,
            style = MaterialTheme.typography.labelSmall,
            color = MaterialTheme.colorScheme.onSurfaceVariant
        )
    }
}