// Copyright (C) 2026 Jason M. Schwefel. All Rights Reserved.
package com.coldboreballisticsllc.scopedope.ui.navigation

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.navigationBars
import androidx.compose.foundation.layout.asPaddingValues
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Air
import androidx.compose.material.icons.filled.Layers
import androidx.compose.material.icons.filled.Print
import androidx.compose.material.icons.filled.ShowChart
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import com.coldboreballisticsllc.scopedope.ui.crash.CrashConsentDialog
import com.coldboreballisticsllc.scopedope.ui.crash.CrashConsentViewModel
import com.coldboreballisticsllc.scopedope.ui.screens.ammo.AmmoScreen
import com.coldboreballisticsllc.scopedope.ui.screens.conditions.ConditionsScreen
import com.coldboreballisticsllc.scopedope.ui.screens.dope.DopeScreen
import com.coldboreballisticsllc.scopedope.ui.screens.feedback.FeedbackScreen
import com.coldboreballisticsllc.scopedope.ui.screens.onboarding.OnboardingScreen
import com.coldboreballisticsllc.scopedope.ui.screens.onboarding.OnboardingViewModel
import com.coldboreballisticsllc.scopedope.ui.screens.tutorial.TutorialScreen
import com.coldboreballisticsllc.scopedope.ui.screens.print.PrintScreen
import com.coldboreballisticsllc.scopedope.ui.screens.results.ResultsScreen
import com.coldboreballisticsllc.scopedope.ui.screens.settings.AdvancedSettingsScreen
import com.coldboreballisticsllc.scopedope.ui.screens.settings.SettingsScreen
import com.coldboreballisticsllc.scopedope.ui.screens.splash.SplashScreen
import com.coldboreballisticsllc.scopedope.ui.screens.support.SupportScreen
import com.coldboreballisticsllc.scopedope.ui.session.SessionViewModel
import com.coldboreballisticsllc.scopedope.ui.theme.ColorAmber
import com.coldboreballisticsllc.scopedope.ui.theme.ColorBackground
import com.coldboreballisticsllc.scopedope.ui.theme.ColorBorder
import com.coldboreballisticsllc.scopedope.ui.theme.ColorSurface
import com.coldboreballisticsllc.scopedope.ui.theme.ColorTextMuted
import com.coldboreballisticsllc.scopedope.ui.theme.ColorTextPrimary
import com.coldboreballisticsllc.scopedope.ui.theme.NavLabelStyle

sealed class Screen(val route: String) {
    data object Splash           : Screen("splash")
    data object Onboarding       : Screen("onboarding")
    data object Dope             : Screen("dope")
    data object Conditions       : Screen("conditions")
    data object Results          : Screen("results")
    data object Print            : Screen("print")
    data object Ammo             : Screen("ammo")
    data object Settings         : Screen("settings")
    data object AdvancedSettings : Screen("advanced_settings")
    data object Tutorial         : Screen("tutorial")
    data object Feedback         : Screen("feedback")
    data object Support          : Screen("support")
}

private data class TabItem(
    val screen: Screen,
    val label:  String,
    val icon:   ImageVector,
)

private val TAB_ITEMS = listOf(
    TabItem(Screen.Dope,       "DOPE",    Icons.Default.Layers),
    TabItem(Screen.Conditions, "Cond",    Icons.Default.Air),
    TabItem(Screen.Results,    "Results", Icons.Default.ShowChart),
    TabItem(Screen.Print,      "Print",   Icons.Default.Print),
)

private val TAB_ROUTES = TAB_ITEMS.map { it.screen.route }.toSet()

@Composable
fun ScopeDopeNavGraph() {
    val navController  = rememberNavController()
    val sessionVm:     SessionViewModel    = hiltViewModel()
    val onboardingVm:  OnboardingViewModel = hiltViewModel()
    val crashConsentVm: CrashConsentViewModel = hiltViewModel()

    val backStackEntry by navController.currentBackStackEntryAsState()
    val currentRoute   = backStackEntry?.destination?.route
    val showBottomBar  = currentRoute in TAB_ROUTES

    // Re-sync crash reporting to the persisted opt-in choice once per app launch.
    LaunchedEffect(Unit) { crashConsentVm.syncOnLaunch() }

    // First-run crash-reporting consent prompt (SPEC §16.1): shown once, only after the
    // user is past splash/onboarding (on a main tab route), and only if not shown before.
    val crashPromptShown by crashConsentVm.promptShown.collectAsState()
    val showConsentPrompt = !crashPromptShown && currentRoute in TAB_ROUTES

    Column(Modifier.fillMaxSize()) {
        NavHost(
            navController    = navController,
            startDestination = Screen.Splash.route,
            modifier         = Modifier.weight(1f),
        ) {
            composable(Screen.Splash.route) {
                SplashScreen(
                    onComplete = {
                        navController.navigate(Screen.Onboarding.route) {
                            popUpTo(Screen.Splash.route) { inclusive = true }
                        }
                    },
                )
            }
            composable(Screen.Onboarding.route) {
                OnboardingScreen(
                    onNavigateAmmo = { navController.navigate(Screen.Ammo.route) },
                    onComplete     = {
                        navController.navigate(Screen.Dope.route) {
                            popUpTo(Screen.Onboarding.route) { inclusive = true }
                        }
                    },
                    sessionVm      = sessionVm,
                )
            }
            composable(Screen.Dope.route) {
                DopeScreen(
                    onNavigateAmmo     = { navController.navigate(Screen.Ammo.route) },
                    onNavigateSettings = { navController.navigate(Screen.Settings.route) },
                    sessionVm          = sessionVm,
                )
            }
            composable(Screen.Conditions.route) {
                ConditionsScreen(sessionVm = sessionVm)
            }
            composable(Screen.Results.route) {
                ResultsScreen(sessionVm = sessionVm)
            }
            composable(Screen.Print.route) {
                PrintScreen(sessionVm = sessionVm)
            }
            composable(Screen.Ammo.route) {
                AmmoScreen(
                    onBack    = { navController.popBackStack() },
                    sessionVm = sessionVm,
                )
            }
            composable(Screen.Settings.route) {
                SettingsScreen(
                    onBack            = { navController.popBackStack() },
                    onShowTutorial    = { navController.navigate(Screen.Tutorial.route) },
                    onShowAdvanced    = { navController.navigate(Screen.AdvancedSettings.route) },
                    onShowFeedback    = { navController.navigate(Screen.Feedback.route) },
                    onShowSupport     = { navController.navigate(Screen.Support.route) },
                    onResetOnboarding = {
                        onboardingVm.resetOnboarding()
                        navController.navigate(Screen.Onboarding.route) {
                            popUpTo(0) { inclusive = true }
                        }
                    },
                    sessionVm         = sessionVm,
                )
            }
            composable(Screen.AdvancedSettings.route) {
                AdvancedSettingsScreen(
                    onBack    = { navController.popBackStack() },
                    sessionVm = sessionVm,
                )
            }
            composable(Screen.Tutorial.route) {
                TutorialScreen(onDone = { navController.popBackStack() })
            }
            composable(Screen.Feedback.route) {
                FeedbackScreen(onBack = { navController.popBackStack() })
            }
            composable(Screen.Support.route) {
                SupportScreen(onBack = { navController.popBackStack() })
            }
        }

        if (showBottomBar) {
            ScopeDopeBottomNav(
                currentRoute = currentRoute,
                onTabSelected = { screen ->
                    navController.navigate(screen.route) {
                        popUpTo(Screen.Dope.route) { inclusive = false }
                        launchSingleTop = true
                    }
                },
            )
        }
    }

    if (showConsentPrompt) {
        CrashConsentDialog(
            onAllow = {
                crashConsentVm.setEnabled(true)
                crashConsentVm.markPromptShown()
            },
            onDecline = {
                crashConsentVm.setEnabled(false)
                crashConsentVm.markPromptShown()
            },
        )
    }
}

// ── Custom bottom navigation bar ──────────────────────────────────────────────

@Composable
private fun ScopeDopeBottomNav(
    currentRoute: String?,
    onTabSelected: (Screen) -> Unit,
) {
    val navBarBottom = WindowInsets.navigationBars.asPaddingValues().calculateBottomPadding()

    Column(
        modifier = Modifier
            .fillMaxWidth()
            .background(ColorSurface)
            .drawBehind {
                drawLine(
                    color       = ColorBorder,
                    start       = Offset(0f, 0f),
                    end         = Offset(size.width, 0f),
                    strokeWidth = 1.dp.toPx(),
                )
            },
    ) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .height(72.dp),
    ) {
        TAB_ITEMS.forEach { tab ->
            val active = currentRoute == tab.screen.route
            Column(
                modifier = Modifier
                    .weight(1f)
                    .fillMaxHeight()
                    .clickable { onTabSelected(tab.screen) }
                    .background(if (active) ColorAmber.copy(alpha = 0.07f) else ColorBackground)
                    .drawBehind {
                        if (active) {
                            drawRect(
                                color   = ColorAmber,
                                topLeft = Offset(size.width * 0.12f, 0f),
                                size    = androidx.compose.ui.geometry.Size(
                                    size.width * 0.76f,
                                    2.dp.toPx(),
                                ),
                            )
                        }
                    },
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.Center,
            ) {
                Icon(
                    imageVector         = tab.icon,
                    contentDescription  = tab.label,
                    modifier            = Modifier.size(24.dp),
                    tint                = if (active) ColorAmber else ColorTextMuted,
                )
                Spacer(Modifier.height(4.dp))
                Text(
                    text  = tab.label.uppercase(),
                    style = NavLabelStyle,
                    color = if (active) ColorAmber else ColorTextMuted,
                )
            }
        }
    }
        // Fill the system navigation bar area with the same surface color
        if (navBarBottom > 0.dp) {
            Spacer(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(navBarBottom)
                    .background(ColorSurface),
            )
        }
    }
}
