package de.tsschulz.timeclock.ui.components

import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.EventNote
import androidx.compose.material.icons.filled.AdminPanelSettings
import androidx.compose.material.icons.filled.Assessment
import androidx.compose.material.icons.filled.CalendarMonth
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
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.graphics.vector.ImageVector
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import de.tsschulz.timeclock.ui.model.AppRoute
import de.tsschulz.timeclock.ui.model.MenuSection
import de.tsschulz.timeclock.ui.theme.TcColors
import de.tsschulz.timeclock.ui.theme.TcRadius
import de.tsschulz.timeclock.ui.theme.TcSpacing

@Composable
fun TcSectionMenu(
    sections: List<MenuSection>,
    selectedRoute: AppRoute,
    onRouteSelected: (AppRoute) -> Unit,
    modifier: Modifier = Modifier,
) {
    Column(
        modifier = modifier
            .fillMaxHeight()
            .width(230.dp)
            .background(TcColors.Background)
            .border(BorderStroke(1.dp, TcColors.Border))
            .verticalScroll(rememberScrollState())
            .padding(vertical = TcSpacing.Md),
    ) {
        sections.forEach { section ->
            Text(
                text = section.title,
                color = TcColors.TextMuted,
                fontSize = 14.sp,
                fontWeight = FontWeight.Normal,
                modifier = Modifier.padding(horizontal = TcSpacing.Lg, vertical = TcSpacing.Sm),
            )
            section.items.forEach { item ->
                val selected = item.route == selectedRoute
                Text(
                    text = item.label,
                    color = if (selected) TcColors.Text else Color333,
                    fontSize = 14.sp,
                    fontWeight = if (selected) FontWeight.SemiBold else FontWeight.Normal,
                    modifier = Modifier
                        .fillMaxWidth()
                        .background(if (selected) TcColors.ActiveMenu else TcColors.Background)
                        .clickable { onRouteSelected(item.route) }
                        .padding(horizontal = TcSpacing.Xl, vertical = TcSpacing.Sm),
                )
            }
        }
    }
}

@Composable
fun TcBottomNavigation(
    sections: List<MenuSection>,
    selectedRoute: AppRoute,
    onRouteSelected: (AppRoute) -> Unit,
    modifier: Modifier = Modifier,
) {
    val items = sections.mapNotNull { section ->
        val firstRoute = section.items.firstOrNull()?.route ?: return@mapNotNull null
        BottomNavItem(section.title, firstRoute, section.icon())
    }
    var openSectionTitle by rememberSaveable { mutableStateOf<String?>(null) }

    Column(
        modifier = modifier
            .fillMaxWidth()
            .background(TcColors.Navbar)
            .border(BorderStroke(1.dp, TcColors.BorderSoft))
            .padding(horizontal = TcSpacing.Sm, vertical = TcSpacing.Xs),
    ) {
        val openSection = sections.firstOrNull { it.title == openSectionTitle }
        openSection?.let { section ->
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .background(TcColors.Card, RoundedCornerShape(TcRadius.Medium))
                    .border(BorderStroke(1.dp, TcColors.Border), RoundedCornerShape(TcRadius.Medium))
                    .padding(vertical = TcSpacing.Sm),
            ) {
                section.items.forEach { menuItem ->
                    val selected = menuItem.route == selectedRoute
                    Text(
                        text = menuItem.label,
                        color = if (selected) TcColors.Text else Color333,
                        fontSize = 15.sp,
                        fontWeight = if (selected) FontWeight.SemiBold else FontWeight.Normal,
                        modifier = Modifier
                            .fillMaxWidth()
                            .background(if (selected) TcColors.ActiveMenu else TcColors.Card)
                            .clickable {
                                onRouteSelected(menuItem.route)
                                openSectionTitle = null
                            }
                            .padding(horizontal = TcSpacing.Xl, vertical = TcSpacing.Md),
                    )
                }
            }
        }

        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceAround,
            verticalAlignment = Alignment.CenterVertically,
        ) {
            items.forEach { item ->
                val selected = item.route == selectedRoute || isRouteInSection(item.route, selectedRoute)
                val expanded = openSectionTitle == item.label
                Column(
                    modifier = Modifier
                        .heightIn(min = 56.dp)
                        .weight(1f)
                        .background(if (selected || expanded) TcColors.ActiveMenu else TcColors.Navbar, RoundedCornerShape(TcRadius.Small))
                        .clickable {
                            openSectionTitle = if (expanded) null else item.label
                        }
                        .padding(vertical = TcSpacing.Sm),
                    horizontalAlignment = Alignment.CenterHorizontally,
                    verticalArrangement = Arrangement.Center,
                ) {
                    Icon(imageVector = item.icon, contentDescription = item.label, tint = TcColors.TextMuted)
                    Text(text = item.label, color = TcColors.TextMuted, fontSize = 11.sp)
                }
            }
        }
    }
}

@Composable
fun TcMobileSubMenu(
    sections: List<MenuSection>,
    selectedRoute: AppRoute,
    onRouteSelected: (AppRoute) -> Unit,
    modifier: Modifier = Modifier,
) {
    val section = sections.firstOrNull { s -> s.items.any { it.route == selectedRoute } } ?: return
    Column(
        modifier = modifier
            .fillMaxWidth()
            .background(TcColors.Card)
            .border(BorderStroke(1.dp, TcColors.Border), RoundedCornerShape(TcRadius.Medium))
            .padding(TcSpacing.Md),
        verticalArrangement = Arrangement.spacedBy(TcSpacing.Sm),
    ) {
        Text(section.title, color = TcColors.TextMuted, fontSize = 13.sp, fontWeight = FontWeight.SemiBold)
        section.items.forEach { item ->
            val selected = item.route == selectedRoute
            Text(
                text = item.label,
                color = if (selected) TcColors.Text else Color333,
                fontSize = 14.sp,
                fontWeight = if (selected) FontWeight.SemiBold else FontWeight.Normal,
                modifier = Modifier
                    .fillMaxWidth()
                    .background(if (selected) TcColors.ActiveMenu else TcColors.Card, RoundedCornerShape(TcRadius.Small))
                    .clickable { onRouteSelected(item.route) }
                    .padding(horizontal = TcSpacing.Md, vertical = TcSpacing.Sm),
            )
        }
    }
}

@Composable
fun TcMobileMainMenu(
    sections: List<MenuSection>,
    selectedRoute: AppRoute,
    onRouteSelected: (AppRoute) -> Unit,
    modifier: Modifier = Modifier,
) {
    val selectedSectionTitle = sections.firstOrNull { section ->
        section.items.any { it.route == selectedRoute }
    }?.title
    var openSectionTitle by rememberSaveable { mutableStateOf(selectedSectionTitle) }

    LaunchedEffect(selectedSectionTitle) {
        openSectionTitle = selectedSectionTitle
    }

    Column(
        modifier = modifier
            .fillMaxWidth()
            .background(TcColors.Card)
            .border(BorderStroke(1.dp, TcColors.Border), RoundedCornerShape(TcRadius.Medium))
            .padding(vertical = TcSpacing.Sm),
    ) {
        sections.forEach { section ->
            val open = openSectionTitle == section.title
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .clickable {
                        openSectionTitle = if (open) null else section.title
                    }
                    .padding(horizontal = TcSpacing.Lg, vertical = TcSpacing.Md),
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.spacedBy(TcSpacing.Sm),
            ) {
                Text(
                    text = section.title,
                    color = TcColors.Text,
                    fontSize = 15.sp,
                    fontWeight = FontWeight.SemiBold,
                    modifier = Modifier.weight(1f),
                )
                Text(if (open) "▾" else "▸", color = TcColors.TextMuted, fontSize = 14.sp)
            }
            if (open) {
                section.items.forEach { item ->
                    val selected = item.route == selectedRoute
                    Text(
                        text = item.label,
                        color = if (selected) TcColors.Text else Color333,
                        fontSize = 14.sp,
                        fontWeight = if (selected) FontWeight.SemiBold else FontWeight.Normal,
                        modifier = Modifier
                            .fillMaxWidth()
                            .background(if (selected) TcColors.ActiveMenu else TcColors.Card)
                            .clickable { onRouteSelected(item.route) }
                            .padding(horizontal = TcSpacing.Xl, vertical = TcSpacing.Sm),
                    )
                }
            }
        }
    }
}

private data class BottomNavItem(
    val label: String,
    val route: AppRoute,
    val icon: ImageVector,
)

private fun isRouteInSection(sectionRoute: AppRoute, selectedRoute: AppRoute): Boolean =
    when (sectionRoute) {
        AppRoute.Week -> selectedRoute in setOf(AppRoute.Timefix, AppRoute.Vacation, AppRoute.Sick, AppRoute.Workdays, AppRoute.Calendar)
        AppRoute.Profile -> selectedRoute in setOf(AppRoute.Password, AppRoute.Timewish, AppRoute.Permissions, AppRoute.Invite)
        AppRoute.Entries -> selectedRoute == AppRoute.Stats
        AppRoute.Holidays -> selectedRoute == AppRoute.Roles
        else -> false
    }

private fun MenuSection.icon(): ImageVector =
    when (title) {
        "Buchungen" -> Icons.AutoMirrored.Filled.EventNote
        "Einstellungen" -> Icons.Filled.Settings
        "Auswertung" -> Icons.Filled.Assessment
        "Verwaltung" -> Icons.Filled.AdminPanelSettings
        else -> Icons.Filled.CalendarMonth
    }

private val Color333 = androidx.compose.ui.graphics.Color(0xFF333333)
