package mg.dot.feufaro.ui

import SharedScreenModel
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.ExperimentalFoundationApi
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.EventNote
import androidx.compose.material.icons.automirrored.filled.Note
import androidx.compose.material.icons.automirrored.filled.StarHalf
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.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 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

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun SimpleDrawerContent(
    items: List<DrawerItem>,
    solfaScreenModel: SolfaScreenModel,
    sharedScreenModel: SharedScreenModel,
    activePath: String = Solfa.currentFile,
    drawerState: DrawerState,
    scope: CoroutineScope,
    onScannerButtonClick: () -> Unit,
    onSongSelected: (String) -> 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 listState = rememberLazyListState()

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

    ModalDrawerSheet(
        modifier = Modifier.width(300.dp)
    ) {
        Column(modifier = Modifier.fillMaxWidth()) {
            Box(modifier = Modifier.weight(1f).padding(0.dp, 20.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.Note,
                                color = MaterialTheme.colorScheme.primary,
                                isExpanded = internalExpanded,
                                onToggle = { internalExpanded = !internalExpanded },
                                count = internalList.size
                            )
                        }

                        if (internalExpanded) {
                            items(internalList) { item ->
                                val isSelected = item.path == activePath
                                NavigationDrawerItem(
                                    label = { DrawerItemLabel(item, sharedScreenModel) },
                                    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 = Color(0, 157, 255).copy(alpha = 0.1f),
                                        selectedTextColor = Color(0, 157, 255)
                                    )
                                )
                            }
                        }

                        stickyHeader {
                            DrawerHeaderSticky(
                                title = "Personnel",
                                icon = Icons.AutoMirrored.Filled.EventNote,
                                color = MaterialTheme.colorScheme.tertiary,
                                isExpanded = externalExpanded,
                                onToggle = { externalExpanded = !externalExpanded },
                                count = externalList.size
                            )
                        }

                        if (externalExpanded) {
                            items(externalList) { item ->
                                val isSelected = item.path == activePath
                                if (item.path != "") {
                                    NavigationDrawerItem(
                                        label = { DrawerItemLabel(item, sharedScreenModel) },
                                        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 = Color.Blue.copy(alpha = 0.1f),
                                            selectedTextColor = Color.Blue
                                        )
                                    )
                                }
                            }
                        }

                        stickyHeader {
                            DrawerHeaderSticky(
                                title = "Playlist",
                                icon = Icons.AutoMirrored.Filled.StarHalf,
                                color = MaterialTheme.colorScheme.tertiary,
                                isExpanded = playListExpanded,
                                onToggle = { playListExpanded = !playListExpanded },
                                count = playList.size
                            )
                        }

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

                                    NavigationDrawerItem(
                                        label = {
                                            DrawerFavorisItemLabel(item, index, isSelected, sharedScreenModel)
                                        },
                                        selected = isSelected,
                                        onClick = {
                                            scope.launch { drawerState.close() }
                                            sharedScreenModel.reset()
                                            solfaScreenModel.loadFromFile(item.path)
                                            onSongSelected(midi)
                                        },
                                        modifier = Modifier.padding(horizontal = 12.dp, vertical = 2.dp),
                                        colors = NavigationDrawerItemDefaults.colors(
                                            selectedContainerColor = Color(0xFFFFD700).copy(alpha = 0.3f),
                                            selectedTextColor = Color(0xFF665500),
                                            selectedIconColor = Color(0xFF665500)
                                        )
                                    )
                                }
                            }
                        }
                    }
                }
            }
            HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant)
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(16.dp),
                horizontalArrangement = Arrangement.SpaceEvenly
            ) {
                Button(onClick = {
                    scope.launch { drawerState.close() }
                }) {
                    Text("Scanner")
                }
                Button(onClick = {
                    solfaScreenModel.loadCustomFile()
                    scope.launch { drawerState.close() }
                }) {
                    Text("Importer")
                }
            }
        }
    }
}

@Composable
fun DrawerAccordionSection(
    title: String,
    items: List<DrawerItem>,
    icon: ImageVector,
    iconColor: Color,
    activePath: String,
    scope: CoroutineScope,
    solfaScreenModel: SolfaScreenModel,
    onItemClick: (DrawerItem) -> Unit
) {
    var expanded by remember { mutableStateOf(true) }

    val rotationState by animateFloatAsState(targetValue = if (expanded) 180f else 0f)

    Column(modifier = Modifier.fillMaxWidth()) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .clickable { expanded = !expanded }
                .padding(horizontal = 16.dp, vertical = 12.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Icon(
                imageVector = icon,
                contentDescription = null,
                tint = iconColor,
                modifier = Modifier.size(20.dp)
            )
            Spacer(Modifier.width(12.dp))
            Text(
                text = title.uppercase(),
                style = MaterialTheme.typography.labelLarge.copy(
                    letterSpacing = 1.sp,
                    fontWeight = FontWeight.Bold
                ),
                color = MaterialTheme.colorScheme.onSurfaceVariant,
                modifier = Modifier.weight(1f)
            )
            Surface(
                color = iconColor.copy(alpha = 0.1f),
                shape = MaterialTheme.shapes.extraSmall
            ) {
                Text(
                    text = "${items.size}",
                    modifier = Modifier.padding(horizontal = 6.dp, vertical = 2.dp),
                    style = MaterialTheme.typography.labelSmall,
                    color = iconColor
                )
            }
            Spacer(Modifier.width(8.dp))
            Icon(
                imageVector = Icons.Default.KeyboardArrowDown,
                contentDescription = null,
                modifier = Modifier.rotate(rotationState).size(20.dp)
            )
        }

        AnimatedVisibility(visible = expanded) {
            Column {
                items.forEach { item ->
                    val isSelected = item.path == activePath
                    NavigationDrawerItem(
                        label = {
                            Column {
                                Text(
                                    text = item.title,
                                    fontWeight = FontWeight.SemiBold,
                                    style = MaterialTheme.typography.bodyMedium
                                )
                                Text(
                                    text = item.contentTitle,
                                    style = MaterialTheme.typography.labelSmall,
                                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                                    maxLines = 1
                                )
                            }
                        },
                        selected = isSelected,
                        onClick = { onItemClick(item) },
                        modifier = Modifier.padding(horizontal = 12.dp, vertical = 2.dp),
                        shape = MaterialTheme.shapes.medium,
                        colors = NavigationDrawerItemDefaults.colors(
                            unselectedContainerColor = Color.Transparent
                        )
                    )
                }
            }
        }

        HorizontalDivider(
            modifier = Modifier.padding(top = 8.dp),
            thickness = 0.5.dp,
            color = MaterialTheme.colorScheme.outlineVariant
        )

        Box(
            modifier = Modifier
                .fillMaxWidth()
                .align(Alignment.CenterHorizontally)
                .padding(16.dp),
            contentAlignment = Alignment.Center
        ) {
            Column(
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                Row (

                ) {
                    Spacer(modifier = Modifier.width(10.dp))
                    Button(
                        onClick = {

                        }
                    ) {
                        Text("Scanner")
                    }
                    Spacer(modifier = Modifier.width(10.dp))
                    Button(
                        onClick = {
                            scope.launch {
                                //drawerState.close()
                            }
                            solfaScreenModel.loadCustomFile()
                        }
                    ) {
                        Text("Importer")
                    }
                }
            }
        }
    }
}

@Composable
fun DrawerHeaderSticky(
    title: String,
    icon: ImageVector,
    color: Color,
    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 = color, modifier = Modifier.size(20.dp))
            Spacer(Modifier.width(12.dp))
            Text(
                text = "$title".uppercase(),
                modifier = Modifier.weight(1f),
                style = MaterialTheme.typography.labelLarge.copy(fontWeight = FontWeight.Bold),
                color = color
            )
            Surface(
                color = Color.Green.copy(alpha = 0.1f),
                shape = MaterialTheme.shapes.extraSmall
            ) {
                Text(
                    text = "${count}",
                    modifier = Modifier.padding(horizontal = 6.dp, vertical = 2.dp),
                    style = MaterialTheme.typography.labelSmall,
                    color = Color.Green
                )
            }
            Icon(
                imageVector = Icons.Default.KeyboardArrowDown,
                contentDescription = null,
                modifier = Modifier.rotate(rotation)
            )
        }
    }
}

@Composable
fun DrawerItemLabel(item: DrawerItem, sharedScreenModel: SharedScreenModel) {
    val favoriteLists by sharedScreenModel.playlistItems.collectAsState()
    val isFavorite = favoriteLists.contains(item)
    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.bodyMedium)
            Text(text = item.contentTitle, style = MaterialTheme.typography.labelSmall, maxLines = 1)
        }

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

@Composable
fun DrawerFavorisItemLabel(item: DrawerItem, index: Int, isSelected: Boolean, sharedScreenModel: SharedScreenModel) {
    Row(
        modifier = Modifier.fillMaxWidth(),
        verticalAlignment = Alignment.CenterVertically
    ) {
        Icon(
            imageVector = Icons.Default.Reorder,
            contentDescription = null,
            modifier = Modifier.padding(end = 8.dp).size(18.dp),
            tint = Color.Gray.copy(alpha = 0.5f)
        )
        Column(modifier = Modifier.weight(1f)) {
            Text(
                text = item.title,
                fontWeight = FontWeight.Bold,
                style = MaterialTheme.typography.bodyMedium
            )
            Text(
                text = item.contentTitle,
                style = MaterialTheme.typography.labelSmall,
                maxLines = 1
            )
        }

        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 = if (isSelected) Color.White else Color.Gray
                )
            }
        }

        IconButton(
            onClick = { sharedScreenModel.toggleFavorite(item.path) },
            modifier = Modifier.size(30.dp)
        ) {
            Icon(
                imageVector = Icons.Default.Star,
                contentDescription = null,
                tint = if (isSelected) Color.White else Color(0xFFFFD700)
            )
        }
    }
}