package com.radiola.ui.navigation

import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.spring
import androidx.compose.animation.core.tween
import androidx.compose.animation.expandHorizontally
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.shrinkHorizontally
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.statusBarsPadding
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.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.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.scale
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import androidx.navigation.compose.currentBackStackEntryAsState
import com.radiola.ui.theme.Motion
import com.radiola.ui.theme.RadiolaTheme

// Обращаемся к объектам напрямую: companion-список NavDestinations.items
// при холодном старте может содержать null (порядок инициализации Kotlin).
private val navItems = listOf(
    NavDestinations.Stations,
    NavDestinations.Favorites,
    NavDestinations.History,
    NavDestinations.Charts,
    NavDestinations.Recordings,
    NavDestinations.Settings
)

/** Переход на раздел с сохранением состояния (общий для нижнего бара и бокового рейла). */
private fun NavController.navigateToTab(route: String, currentRoute: String?) {
    if (currentRoute != route) {
        navigate(route) {
            popUpTo(graph.startDestinationId) { saveState = true }
            launchSingleTop = true
            restoreState = true
        }
    }
}

@Composable
fun BottomNavBar(navController: NavController) {
    val colors = RadiolaTheme.colors
    val currentRoute = navController.currentBackStackEntryAsState().value?.destination?.route
    val items = navItems

    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(start = 16.dp, end = 16.dp, top = 8.dp, bottom = 16.dp)
            .clip(RoundedCornerShape(36.dp))
            .background(colors.surface2)
            .border(1.dp, colors.border, RoundedCornerShape(36.dp))
            .height(62.dp)
            .padding(6.dp),
        horizontalArrangement = Arrangement.spacedBy(4.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        items.forEach { destination ->
            val selected = currentRoute == destination.route
            PillTab(
                label = destination.labelRes,
                icon = destination.icon,
                selected = selected,
                modifier = Modifier.weight(1f),
                onClick = { navController.navigateToTab(destination.route, currentRoute) }
            )
        }
    }
}

/**
 * Боковой навигационный рейл для альбомной ориентации.
 * Вертикальная капсула с теми же иконками-вкладками, что и нижний бар.
 */
@Composable
fun SideNavRail(navController: NavController) {
    val colors = RadiolaTheme.colors
    val currentRoute = navController.currentBackStackEntryAsState().value?.destination?.route

    Column(
        modifier = Modifier
            .fillMaxHeight()
            .statusBarsPadding()
            .padding(start = 12.dp, end = 4.dp, top = 12.dp, bottom = 12.dp)
            .width(64.dp)
            .clip(RoundedCornerShape(32.dp))
            .background(colors.surface2)
            .border(1.dp, colors.border, RoundedCornerShape(32.dp))
            .verticalScroll(rememberScrollState())
            .padding(6.dp),
        verticalArrangement = Arrangement.spacedBy(4.dp),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        navItems.forEach { destination ->
            VerticalPillTab(
                label = destination.labelRes,
                icon = destination.icon,
                selected = currentRoute == destination.route,
                onClick = { navController.navigateToTab(destination.route, currentRoute) }
            )
        }
    }
}

@Composable
private fun VerticalPillTab(
    label: String,
    icon: androidx.compose.ui.graphics.vector.ImageVector,
    selected: Boolean,
    onClick: () -> Unit
) {
    val colors = RadiolaTheme.colors
    val bg by animateColorAsState(
        targetValue = if (selected) colors.accent else androidx.compose.ui.graphics.Color.Transparent,
        animationSpec = tween(Motion.Medium),
        label = "railTabBg"
    )
    val content by animateColorAsState(
        targetValue = if (selected) colors.bgBase else colors.textSecondary,
        animationSpec = tween(Motion.Medium),
        label = "railTabFg"
    )
    val pop = remember { Animatable(1f) }
    LaunchedEffect(selected) {
        if (selected) {
            pop.snapTo(0.5f)
            pop.animateTo(1f, spring(dampingRatio = Spring.DampingRatioMediumBouncy, stiffness = 620f))
        }
    }
    Row(
        modifier = Modifier
            .size(52.dp)
            .clip(RoundedCornerShape(26.dp))
            .background(bg)
            .clickable(
                interactionSource = remember { MutableInteractionSource() },
                indication = null,
                onClick = onClick
            ),
        horizontalArrangement = Arrangement.Center,
        verticalAlignment = Alignment.CenterVertically
    ) {
        Icon(
            imageVector = icon,
            contentDescription = label,
            tint = content,
            modifier = Modifier.size(22.dp).scale(pop.value)
        )
    }
}

@Composable
private fun PillTab(
    label: String,
    icon: androidx.compose.ui.graphics.vector.ImageVector,
    selected: Boolean,
    onClick: () -> Unit,
    modifier: Modifier = Modifier
) {
    val colors = RadiolaTheme.colors
    val bg by animateColorAsState(
        targetValue = if (selected) colors.accent else androidx.compose.ui.graphics.Color.Transparent,
        animationSpec = tween(Motion.Medium),
        label = "tabBg"
    )
    val content by animateColorAsState(
        targetValue = if (selected) colors.bgBase else colors.textSecondary,
        animationSpec = tween(Motion.Medium),
        label = "tabFg"
    )
    // Упругий «поп» иконки при выборе вкладки — маленькая приятная деталь.
    val pop = remember { Animatable(1f) }
    LaunchedEffect(selected) {
        if (selected) {
            pop.snapTo(0.5f)
            pop.animateTo(1f, spring(dampingRatio = Spring.DampingRatioMediumBouncy, stiffness = 620f))
        }
    }
    Row(
        modifier = modifier
            .fillMaxWidth()
            .height(50.dp)
            .clip(RoundedCornerShape(26.dp))
            .background(bg)
            .clickable(
                interactionSource = remember { MutableInteractionSource() },
                indication = null,
                onClick = onClick
            ),
        horizontalArrangement = Arrangement.Center,
        verticalAlignment = Alignment.CenterVertically
    ) {
        // Только иконки — подписи не помещались для 6 разделов.
        Icon(
            imageVector = icon,
            contentDescription = label,
            tint = content,
            modifier = Modifier.height(22.dp).width(22.dp).scale(pop.value)
        )
    }
}
