@file:Suppress("HardCodedStringLiteral", "AssignedValueIsNeverRead")

package eu.gaudian.translator.view.composable

import android.annotation.SuppressLint
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.Crossfade
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.spring
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutVertically
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.navigationBars
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.NavigationBarItemDefaults
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
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.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalHapticFeedback
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavDestination
import androidx.navigation.NavDestination.Companion.hierarchy
import eu.gaudian.translator.R
import eu.gaudian.translator.ui.theme.ThemePreviews
import eu.gaudian.translator.view.LocalShowExperimentalFeatures
import kotlinx.coroutines.launch

sealed class Screen(
    val route: String,
    val title: Int,
    val selectedIcon: ImageVector,
    val unselectedIcon: ImageVector
) {
    object Home : Screen("home", R.string.label_home, AppIcons.Home, AppIcons.Home)
    object Stats : Screen("stats", R.string.label_stats, AppIcons.Statistics, AppIcons.Statistics)
    object Translation : Screen("translation", R.string.label_translation, AppIcons.TranslateFilled, AppIcons.TranslateOutlined)
    object Library : Screen("library", R.string.label_library, AppIcons.VocabularyFilled, AppIcons.VocabularyOutlined)
    object Settings : Screen("settings", R.string.title_settings, AppIcons.SettingsFilled, AppIcons.SettingsOutlined)
    object More : Screen("more", R.string.label_more, AppIcons.MoreVert, AppIcons.MoreHorizontal)
    object Dictionary : Screen("dictionary", R.string.label_dictionary, AppIcons.DictionaryFilled, AppIcons.DictionaryOutlined)
    object Exercises : Screen("exercises", R.string.label_exercises, AppIcons.DictionaryFilled, AppIcons.DictionaryOutlined)

    companion object {
        fun getAllScreens(showExperimental: Boolean = false): List<Screen> {
            return listOf(Home, Library, Stats)
        }

        fun getMoreMenuItems(showExperimental: Boolean = false): List<Screen> {
            val items = mutableListOf<Screen>()
            items.add(Translation)
            items.add(Dictionary)
            items.add(Settings)
            if (showExperimental) {
                items.add(Exercises)
            }
            return items
        }

        @Composable
        fun fromDestination(destination: NavDestination?): Screen {
            val showExperimental = LocalShowExperimentalFeatures.current
            val allScreens = getAllScreens(showExperimental) + getMoreMenuItems(showExperimental) + More
            return allScreens.find { screen ->
                destination?.hierarchy?.any { it.route == screen.route } == true
            } ?: Home
        }
    }
}

@SuppressLint("UnusedBoxWithConstraintsScope")
@Composable
fun BottomNavigationBar(
    selectedItem: Screen,
    isVisible: Boolean,
    showLabels: Boolean,
    onItemSelected: (Screen) -> Unit,
    modifier: Modifier = Modifier,
    onPlayClicked: () -> Unit = {}
) {
    val showExperimental = LocalShowExperimentalFeatures.current
    val screens = remember(showExperimental) { Screen.getAllScreens(showExperimental) }
    val moreScreen = remember { Screen.More }
    val haptic = LocalHapticFeedback.current
    var showMoreMenu by remember { mutableStateOf(false) }
    val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
    val scope = rememberCoroutineScope()

    // Configuration for the play button
    val playButtonSize = 56.dp
    val glowPadding = 12.dp // Total extra space for the glow (16dp on each side)

    // This dictates how far up the button shifts.
    // Setting it to around half the button size centers it on the top border.
    val upwardOffset = 16.dp

    AnimatedVisibility(
        visible = isVisible,
        enter = slideInVertically(
            animationSpec = spring(stiffness = Spring.StiffnessHigh),
            initialOffsetY = { it }
        ),
        exit = slideOutVertically(
            animationSpec = spring(stiffness = Spring.StiffnessHigh),
            targetOffsetY = { it }
        )
    ) {
        val baseHeight = if (showLabels) 80.dp else 56.dp
        val density = LocalDensity.current
        val navBarDp = with(density) { WindowInsets.navigationBars.getBottom(this).toDp() }
        val height = baseHeight + navBarDp

        // Outer Box height is purely determined by the NavigationBar now
        Box(
            modifier = modifier.fillMaxWidth(),
            contentAlignment = Alignment.TopCenter
        ) {

            // The actual Navigation Bar
            NavigationBar(
                modifier = Modifier.height(height),
                containerColor = MaterialTheme.colorScheme.surface,
                tonalElevation = 8.dp,
            ) {
                // Create a list of 5 items (2 left, 1 empty spacer, 2 right)
                val allNavItems = buildList {
                    addAll(screens.take(2))
                    add(null) // Empty spacer for Play Button gap
                    if (screens.size > 2) {
                        addAll(screens.drop(2))
                    }
                    add(moreScreen)
                }

                allNavItems.forEach { screen ->
                    if (screen == null) {
                        // Dummy item to create the gap
                        NavigationBarItem(
                            selected = false,
                            onClick = {},
                            enabled = false, // Disables ripples and clicks
                            icon = { Spacer(modifier = Modifier.size(24.dp)) },
                            label = if (showLabels) { { Spacer(modifier = Modifier.size(10.dp)) } } else null,
                            colors = NavigationBarItemDefaults.colors(
                                disabledIconColor = Color.Transparent,
                                disabledTextColor = Color.Transparent
                            )
                        )
                    } else {
                        // Regular or More items
                        val isSelected = if (screen == Screen.More) {
                            selectedItem is Screen.More || Screen.getMoreMenuItems(showExperimental).contains(selectedItem)
                        } else {
                            screen == selectedItem
                        }
                        val title = stringResource(id = screen.title)

                        val scale by animateFloatAsState(
                            targetValue = if (isSelected) 1.2f else 1.0f,
                            animationSpec = spring(
                                dampingRatio = Spring.DampingRatioMediumBouncy,
                                stiffness = Spring.StiffnessLow
                            ),
                            label = "iconScale"
                        )

                        NavigationBarItem(
                            selected = isSelected,
                            onClick = {
                                if (!isSelected) {
                                    haptic.performHapticFeedback(HapticFeedbackType.LongPress)
                                    if (screen == Screen.More) showMoreMenu = true else onItemSelected(screen)
                                }
                            },
                            label = if (showLabels) {
                                {
                                    Text(
                                        text = title,
                                        maxLines = 1,
                                        fontSize = 10.sp,
                                        fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Normal,
                                        color = if(isSelected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant
                                    )
                                }
                            } else null,
                            icon = {
                                Crossfade(targetState = isSelected, label = "iconFade") { selected ->
                                    Icon(
                                        imageVector = if (selected) screen.selectedIcon else screen.unselectedIcon,
                                        contentDescription = title,
                                        modifier = Modifier.scale(scale)
                                    )
                                }
                            },
                            colors = NavigationBarItemDefaults.colors(
                                indicatorColor = MaterialTheme.colorScheme.primaryContainer,
                                selectedIconColor = MaterialTheme.colorScheme.onPrimaryContainer,
                                selectedTextColor = MaterialTheme.colorScheme.primary,
                                unselectedIconColor = MaterialTheme.colorScheme.onSurfaceVariant,
                                unselectedTextColor = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                        )
                    }
                }
            }

            // The Glowing Play Button
            Box(
                modifier = Modifier
                    // This negative offset pulls the button UP out of the bounding box
                    // without increasing the layout height of the parent Box.
                    .offset(y = -upwardOffset)
                    .size(playButtonSize + glowPadding),
                contentAlignment = Alignment.Center
            ) {
                // Background radial glow
                Box(
                    modifier = Modifier
                        .matchParentSize()
                        .background(
                            brush = Brush.radialGradient(
                                colors = listOf(
                                    MaterialTheme.colorScheme.primary.copy(alpha = 0.5f),
                                    Color.Transparent
                                )
                            ),
                            shape = CircleShape
                        )
                )

                // Actual clickable button
                Box(
                    modifier = Modifier
                        .size(playButtonSize)
                        .clip(CircleShape)
                        .background(MaterialTheme.colorScheme.primaryContainer)
                        .clickable {
                            haptic.performHapticFeedback(HapticFeedbackType.LongPress)
                            onPlayClicked()
                        },
                    contentAlignment = Alignment.Center
                ) {
                    Icon(
                        imageVector = Icons.Filled.PlayArrow,
                        contentDescription = "Play",
                        tint = Color.White,
                        modifier = Modifier.size(32.dp)
                    )
                }
            }
        }
    }

    // Modal Bottom Sheet for More menu (Remains exactly the same)
    if (showMoreMenu) {
        ModalBottomSheet(
            onDismissRequest = { showMoreMenu = false },
            sheetState = sheetState
        ) {
            MoreBottomSheetContent(
                showExperimental = showExperimental,
                onItemSelected = { screen ->
                    scope.launch {
                        sheetState.hide()
                        showMoreMenu = false
                        onItemSelected(screen)
                    }
                }
            )
        }
    }
}

@Composable
private fun MoreBottomSheetContent(
    showExperimental: Boolean,
    onItemSelected: (Screen) -> Unit
) {
    val moreItems = remember(showExperimental) { Screen.getMoreMenuItems(showExperimental) }

    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(bottom = 32.dp)
    ) {
        Text(
            text = stringResource(R.string.label_more),
            style = MaterialTheme.typography.titleLarge,
            fontWeight = FontWeight.Bold, // Added bold to match the new style
            modifier = Modifier.padding(horizontal = 24.dp, vertical = 16.dp)
        )

        // Removed HorizontalDivider() for a cleaner look

        moreItems.forEach { screen ->
            MoreMenuItem(
                screen = screen,
                onClick = { onItemSelected(screen) }
            )
        }
    }
}



@Composable
fun MoreMenuItem(
    screen: Screen,
    onClick: () -> Unit
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .clickable { onClick() }
            .padding(horizontal = 24.dp, vertical = 16.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        // Circular Icon Background
        Surface(
            shape = CircleShape,
            color = MaterialTheme.colorScheme.surfaceVariant,
            modifier = Modifier.size(52.dp)
        ) {
            Box(contentAlignment = Alignment.Center) {
                // Adjust this depending on whether your Screen uses ImageVector or Drawable Res
                Icon(
                    imageVector = screen.selectedIcon,
                    contentDescription = null,
                    tint = MaterialTheme.colorScheme.onSurfaceVariant,
                    modifier = Modifier.size(28.dp)
                )
            }
        }

        Spacer(modifier = Modifier.width(16.dp))

        // Title
        Text(
            text = stringResource(id = screen.title), // Adjust to your actual string property
            style = MaterialTheme.typography.titleMedium,
            fontWeight = FontWeight.Bold,
            color = MaterialTheme.colorScheme.onSurface,
            modifier = Modifier.weight(1f)
        )
    }
}
@ThemePreviews
@Composable
fun BottomNavigationBarPreview() {
    MaterialTheme {
        Box(
            modifier = Modifier
                .fillMaxSize()
                .background(MaterialTheme.colorScheme.background),
            contentAlignment = Alignment.BottomCenter
        ) {
            BottomNavigationBar(
                selectedItem = Screen.Home,
                isVisible = true,
                showLabels = true,
                onItemSelected = {}
            )
        }
    }
}