package id.iiyh.inatrading.navigation

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Cancel
import androidx.compose.material.icons.outlined.WifiTethering
import androidx.compose.material3.Icon
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.material3.ripple
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.Alignment
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavGraph.Companion.findStartDestination
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import id.iiyh.inatrading.MainActivity
import id.iiyh.inatrading.R
import id.iiyh.inatrading.core.ui.components.InaBottomNavBar
import id.iiyh.inatrading.core.ui.components.InaTopAppBar
import id.iiyh.inatrading.core.ui.theme.Background
import id.iiyh.inatrading.core.ui.theme.BrandRed
import id.iiyh.inatrading.core.ui.theme.ManropeFontFamily
import id.iiyh.inatrading.core.ui.theme.OnSurface
import id.iiyh.inatrading.core.ui.theme.OnSurfaceVariant
import id.iiyh.inatrading.feature.auth.presentation.ForgotPasswordScreen
import id.iiyh.inatrading.feature.auth.presentation.LoginScreen
import id.iiyh.inatrading.feature.auth.presentation.RegisterScreen
import id.iiyh.inatrading.feature.auth.presentation.RegisterSuccessScreen
import androidx.hilt.navigation.compose.hiltViewModel
import id.iiyh.inatrading.feature.cart.presentation.CartScreen
import id.iiyh.inatrading.feature.cart.presentation.CartViewModel
import id.iiyh.inatrading.feature.info.presentation.AboutScreen
import id.iiyh.inatrading.feature.info.presentation.HelpCenterScreen
import id.iiyh.inatrading.feature.info.presentation.PrivacyPolicyScreen
import id.iiyh.inatrading.feature.info.presentation.TermsConditionsScreen
import id.iiyh.inatrading.feature.explore.presentation.ExploreDetailScreen
import id.iiyh.inatrading.feature.explore.presentation.ExploreNavViewModel
import id.iiyh.inatrading.feature.explore.presentation.ExploreScreen
import id.iiyh.inatrading.feature.home.presentation.HomeScreen
import id.iiyh.inatrading.feature.news.presentation.NewsDetailScreen
import id.iiyh.inatrading.feature.news.presentation.NewsListScreen
import id.iiyh.inatrading.feature.news.presentation.NewsNavViewModel
import id.iiyh.inatrading.feature.product.presentation.ProductDetailScreen
import id.iiyh.inatrading.feature.product.presentation.ProductNavViewModel
import id.iiyh.inatrading.feature.product.presentation.ProductsScreen
import id.iiyh.inatrading.feature.profile.presentation.EditProfileScreen
import id.iiyh.inatrading.feature.profile.presentation.FavoriteGroupDetailScreen
import id.iiyh.inatrading.feature.profile.presentation.FavoritesScreen
import id.iiyh.inatrading.feature.profile.presentation.AddShippingAddressScreen
import id.iiyh.inatrading.feature.profile.presentation.ChangePasswordScreen
import id.iiyh.inatrading.feature.profile.presentation.EditShippingAddressScreen
import id.iiyh.inatrading.feature.profile.presentation.ProfileScreen
import id.iiyh.inatrading.feature.profile.presentation.ShippingAddressesViewModel
import id.iiyh.inatrading.feature.profile.presentation.ShippingAddressesScreen

@Composable
fun AppNavigation(
    navController: NavHostController = rememberNavController(),
    cartViewModel: CartViewModel = hiltViewModel(),
    newsNavViewModel: NewsNavViewModel = hiltViewModel(),
    exploreNavViewModel: ExploreNavViewModel = hiltViewModel(),
    productNavViewModel: ProductNavViewModel = hiltViewModel(),
) {
    val cartUiState by cartViewModel.uiState.collectAsState()
    val backStackEntry by navController.currentBackStackEntryAsState()
    val currentRoute   = backStackEntry?.destination?.route
    val isMainScreen   = currentRoute in mainRoutes
    val context = LocalContext.current
    val activity = context as? MainActivity
    val snackbarHostState = remember { SnackbarHostState() }
    var isRfidDialogVisible by rememberSaveable { mutableStateOf(false) }

    Scaffold(
        topBar = {
            if (isMainScreen) {
                InaTopAppBar(
                    cartItemCount = cartUiState.itemCount,
                    onMenuClick  = { /* TODO: open drawer */ },
                    onRfidClick = { isRfidDialogVisible = true },
                    onCartClick  = { navController.navigate(Screen.Cart.route) },
                    onNotifClick = { /* TODO: navigate to notifications */ },
                )
            }
        },
        snackbarHost = { SnackbarHost(snackbarHostState) },
        bottomBar = {
            if (isMainScreen) {
                InaBottomNavBar(
                    currentRoute  = currentRoute,
                    onTabSelected = { screen ->
                        navController.navigate(screen.route) {
                            popUpTo(navController.graph.findStartDestination().id) {
                                saveState = true
                            }
                            launchSingleTop = true
                            restoreState    = true
                        }
                    },
                )
            }
        },
    ) { innerPadding ->
        NavHost(
            navController    = navController,
            startDestination = Screen.Home.route,
            modifier         = Modifier.padding(innerPadding),
        ) {
            // ── Main tabs ─────────────────────────────────────────────────
            composable(Screen.Home.route) {
                HomeScreen(
                    onNewsClick = { article ->
                        newsNavViewModel.select(article)
                        navController.navigate(Screen.NewsDetail.createRoute(article.id))
                    },
                    onViewAllNews = { navController.navigate(Screen.NewsList.route) },
                )
            }
            composable(Screen.Explore.route)  {
                ExploreScreen(
                    onLocationClick = { location ->
                        exploreNavViewModel.select(location)
                        navController.navigate(Screen.ExploreDetail.createRoute(location.id))
                    },
                )
            }
            composable(Screen.Products.route) {
                ProductsScreen(
                    onProductClick = { product ->
                        productNavViewModel.select(product)
                        navController.navigate(Screen.ProductDetail.createRoute(product.id))
                    },
                    onLoginRequired = { navController.navigate(Screen.Login.route) },
                    onSessionExpired = {
                        navController.navigate(Screen.Login.route) {
                            popUpTo(Screen.Products.route) { inclusive = false }
                            launchSingleTop = true
                        }
                    },
                )
            }
            composable(Screen.Profile.route)  {
                ProfileScreen(
                    onLoginClick        = { navController.navigate(Screen.Login.route) },
                    onEditProfile       = { navController.navigate(Screen.EditProfile.route) },
                    onChangePassword    = { navController.navigate(Screen.ChangePassword.route) },
                    onShippingAddresses = { navController.navigate(Screen.ShippingAddresses.route) },
                    onFavoritesClick    = { navController.navigate(Screen.Favorites.route) },
                    onPaymentMethods    = { navController.navigate(Screen.PaymentMethods.route) },
                    onHelpCenterClick   = { navController.navigate(Screen.HelpCenter.route) },
                    onTermsClick        = { navController.navigate(Screen.TermsConditions.route) },
                    onPrivacyPolicyClick = { navController.navigate(Screen.PrivacyPolicy.route) },
                    onAboutClick        = { navController.navigate(Screen.About.route) },
                )
            }

            // ── Auth ──────────────────────────────────────────────────────
            composable(Screen.Login.route) {
                LoginScreen(
                    onBack           = { navController.popBackStack() },
                    onLoginSuccess   = {
                        navController.navigate(Screen.Profile.route) {
                            popUpTo(Screen.Login.route) { inclusive = true }
                        }
                    },
                    onForgotPassword = { navController.navigate(Screen.ForgotPassword.route) },
                    onRegister       = { navController.navigate(Screen.Register.route) },
                )
            }
            composable(Screen.ForgotPassword.route) {
                ForgotPasswordScreen(onBack = { navController.popBackStack() })
            }
            composable(Screen.Register.route) {
                RegisterScreen(
                    onBack            = { navController.popBackStack() },
                    onRegisterSuccess = {
                        navController.navigate(Screen.RegisterSuccess.route) {
                            popUpTo(Screen.Register.route) { inclusive = true }
                        }
                    },
                    onLoginClick = {
                        navController.navigate(Screen.Login.route) {
                            popUpTo(Screen.Register.route) { inclusive = true }
                        }
                    },
                )
            }
            composable(Screen.RegisterSuccess.route) {
                RegisterSuccessScreen(
                    onLoginClick = {
                        navController.navigate(Screen.Login.route) {
                            popUpTo(Screen.RegisterSuccess.route) { inclusive = true }
                        }
                    },
                )
            }

            // ── Inner screens ─────────────────────────────────────────────
            composable(Screen.About.route) {
                AboutScreen(onBack = { navController.popBackStack() })
            }
            composable(Screen.HelpCenter.route) {
                HelpCenterScreen(onBack = { navController.popBackStack() })
            }
            composable(Screen.TermsConditions.route) {
                TermsConditionsScreen(onBack = { navController.popBackStack() })
            }
            composable(Screen.PrivacyPolicy.route) {
                PrivacyPolicyScreen(
                    onBack           = { navController.popBackStack() },
                    onFullTermsClick = { navController.navigate(Screen.TermsConditions.route) },
                )
            }
            composable(Screen.NewsDetail.route) {
                val article = newsNavViewModel.selectedArticle.collectAsState().value
                if (article != null) {
                    NewsDetailScreen(
                        article = article,
                        onBack  = { navController.popBackStack() },
                    )
                }
            }
            composable(Screen.NewsList.route) {
                NewsListScreen(
                    onBack = { navController.popBackStack() },
                    onArticleClick = { article ->
                        newsNavViewModel.select(article)
                        navController.navigate(Screen.NewsDetail.createRoute(article.id))
                    },
                )
            }
            composable(Screen.ExploreDetail.route) {
                val location = exploreNavViewModel.selectedLocation.collectAsState().value
                if (location != null) {
                    ExploreDetailScreen(
                        location = location,
                        onBack = { navController.popBackStack() },
                    )
                } else {
                    PlaceholderDetailFallback(
                        title = stringResource(R.string.explore_error_title),
                        body = stringResource(R.string.explore_detail_missing_body),
                        onBack = { navController.popBackStack() },
                    )
                }
            }
            composable(Screen.ProductDetail.route) {
                ProductDetailScreen(
                    onBack = { navController.popBackStack() },
                    cartItemCount = cartUiState.itemCount,
                    onCartClick = { navController.navigate(Screen.Cart.route) },
                    onLoginRequired = { navController.navigate(Screen.Login.route) },
                    onCartAdded = { cartViewModel.onItemAdded() },
                    onSessionExpired = {
                        navController.navigate(Screen.Login.route) {
                            popUpTo(Screen.ProductDetail.route) { inclusive = false }
                            launchSingleTop = true
                        }
                    },
                )
            }
            composable(Screen.Cart.route) {
                CartScreen(
                    onBack = { navController.popBackStack() },
                    onLoginRequired = { navController.navigate(Screen.Login.route) },
                    viewModel = cartViewModel,
                )
            }
            composable(Screen.Favorites.route) {
                FavoritesScreen(
                    onBack = { navController.popBackStack() },
                    onBrowseProducts = {
                        navController.navigate(Screen.Products.route) {
                            popUpTo(navController.graph.findStartDestination().id) {
                                saveState = true
                            }
                            launchSingleTop = true
                            restoreState = true
                        }
                    },
                    onGroupClick = { group ->
                        navController.navigate(
                            Screen.FavoriteGroupDetail.createRoute(group.id, group.name)
                        )
                    },
                    onSessionExpired = {
                        navController.navigate(Screen.Login.route) {
                            popUpTo(Screen.Favorites.route) { inclusive = true }
                            launchSingleTop = true
                        }
                    },
                )
            }
            composable(Screen.FavoriteGroupDetail.route) {
                FavoriteGroupDetailScreen(
                    onBack = { navController.popBackStack() },
                    onProductClick = { productId ->
                        navController.navigate(Screen.ProductDetail.createRoute(productId))
                    },
                    onSessionExpired = {
                        navController.navigate(Screen.Login.route) {
                            popUpTo(Screen.FavoriteGroupDetail.route) { inclusive = true }
                            launchSingleTop = true
                        }
                    },
                )
            }
            composable(Screen.EditProfile.route) {
                EditProfileScreen(onBack = { navController.popBackStack() })
            }
            composable(Screen.ChangePassword.route) {
                ChangePasswordScreen(
                    onBack = { navController.popBackStack() },
                    onLoggedOut = {
                        navController.navigate(Screen.Login.route) {
                            popUpTo(Screen.Profile.route) { inclusive = false }
                            launchSingleTop = true
                        }
                    },
                )
            }
            composable(Screen.ShippingAddresses.route) { backStackEntry ->
                val refreshAddresses by backStackEntry.savedStateHandle
                    .getStateFlow("refresh_addresses", false)
                    .collectAsState()
                val viewModel: ShippingAddressesViewModel = hiltViewModel()

                LaunchedEffect(refreshAddresses) {
                    if (refreshAddresses) {
                        viewModel.loadAddresses()
                        backStackEntry.savedStateHandle["refresh_addresses"] = false
                    }
                }

                ShippingAddressesScreen(
                    onBack = { navController.popBackStack() },
                    onAddAddressClick = { navController.navigate(Screen.AddShippingAddress.route) },
                    onEditAddressClick = { address ->
                        address.id?.let {
                            navController.navigate(Screen.EditShippingAddress.createRoute(it))
                        }
                    },
                    viewModel = viewModel,
                )
            }
            composable(Screen.AddShippingAddress.route) {
                AddShippingAddressScreen(
                    onBack = { navController.popBackStack() },
                    onSaveSuccess = {
                        navController.previousBackStackEntry
                            ?.savedStateHandle
                            ?.set("refresh_addresses", true)
                        navController.popBackStack()
                    },
                )
            }
            composable(Screen.EditShippingAddress.route) {
                EditShippingAddressScreen(
                    onBack = { navController.popBackStack() },
                    onFinished = {
                        navController.previousBackStackEntry
                            ?.savedStateHandle
                            ?.set("refresh_addresses", true)
                        navController.popBackStack()
                    },
                )
            }
            composable(Screen.PaymentMethods.route)    { /* TODO */ }
        }
    }

    var snackbarMessage by remember { mutableStateOf<String?>(null) }

    LaunchedEffect(snackbarMessage) {
        snackbarMessage?.let {
            snackbarHostState.showSnackbar(it)
            snackbarMessage = null
        }
    }

    LaunchedEffect(isRfidDialogVisible, activity) {
        if (!isRfidDialogVisible) return@LaunchedEffect
        val scanActivity = activity ?: run {
            snackbarMessage = context.getString(R.string.rfid_not_supported)
            isRfidDialogVisible = false
            return@LaunchedEffect
        }

        val started = scanActivity.startRfidScan(
            onValueDetected = { value ->
                isRfidDialogVisible = false
                navController.navigate(Screen.ProductDetail.createRoute(value))
            },
            onError = { message ->
                snackbarMessage = message
            },
        )

        if (!started) {
            snackbarMessage = context.getString(R.string.rfid_not_supported)
            isRfidDialogVisible = false
        }
    }

    if (isRfidDialogVisible) {
        RfidScanDialog(
            onDismiss = {
                isRfidDialogVisible = false
                activity?.stopRfidScan()
            },
        )
    }
}

@Composable
private fun PlaceholderDetailFallback(
    title: String,
    body: String,
    onBack: () -> Unit,
) {
    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(Background)
            .padding(24.dp),
        contentAlignment = Alignment.Center,
    ) {
        Column(
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.spacedBy(12.dp),
        ) {
            Text(
                text = title,
                fontFamily = ManropeFontFamily,
                fontWeight = FontWeight.ExtraBold,
                fontSize = 22.sp,
                color = OnSurface,
                textAlign = TextAlign.Center,
            )
            Text(
                text = body,
                color = OnSurfaceVariant,
                textAlign = TextAlign.Center,
            )
            Row(
                modifier = Modifier
                    .clickable(
                        interactionSource = remember { MutableInteractionSource() },
                        indication = ripple(),
                        onClick = onBack,
                    )
                    .padding(horizontal = 18.dp, vertical = 10.dp),
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.spacedBy(8.dp),
            ) {
                Icon(
                    imageVector = Icons.Outlined.Cancel,
                    contentDescription = null,
                    tint = BrandRed,
                    modifier = Modifier.size(18.dp),
                )
                Text(
                    text = stringResource(R.string.favorite_back),
                    color = BrandRed,
                    fontWeight = FontWeight.Bold,
                )
            }
        }
    }
}

@Composable
private fun RfidScanDialog(
    onDismiss: () -> Unit,
) {
    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(Color.Black.copy(alpha = 0.56f))
            .clickable(
                interactionSource = remember { MutableInteractionSource() },
                indication = null,
                onClick = {},
            ),
        contentAlignment = Alignment.Center,
    ) {
        Column(
            modifier = Modifier
                .padding(horizontal = 32.dp)
                .fillMaxWidth()
                .background(Background, RoundedCornerShape(28.dp))
                .padding(horizontal = 28.dp, vertical = 36.dp),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.spacedBy(18.dp),
        ) {
            Box(
                modifier = Modifier
                    .size(100.dp)
                    .background(BrandRed.copy(alpha = 0.10f), RoundedCornerShape(50.dp)),
                contentAlignment = Alignment.Center,
            ) {
                Box(
                    modifier = Modifier
                        .size(48.dp)
                        .background(BrandRed, RoundedCornerShape(24.dp)),
                    contentAlignment = Alignment.Center,
                ) {
                    Icon(
                        imageVector = Icons.Outlined.WifiTethering,
                        contentDescription = null,
                        tint = Color.White,
                        modifier = Modifier.size(24.dp),
                    )
                }
            }

            Text(
                text = stringResource(R.string.rfid_waiting_title),
                fontFamily = ManropeFontFamily,
                fontWeight = FontWeight.ExtraBold,
                fontSize = 22.sp,
                color = OnSurface,
                textAlign = TextAlign.Center,
            )

            Text(
                text = stringResource(R.string.rfid_waiting_body),
                color = OnSurfaceVariant,
                textAlign = TextAlign.Center,
                lineHeight = 24.sp,
            )

            Row(
                modifier = Modifier
                    .padding(top = 8.dp)
                    .clickable(
                        interactionSource = remember { MutableInteractionSource() },
                        indication = ripple(),
                        onClick = onDismiss,
                    )
                    .padding(horizontal = 18.dp, vertical = 10.dp),
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.spacedBy(8.dp),
            ) {
                Icon(
                    imageVector = Icons.Outlined.Cancel,
                    contentDescription = null,
                    tint = OnSurfaceVariant,
                    modifier = Modifier.size(18.dp),
                )
                Text(
                    text = stringResource(R.string.rfid_cancel),
                    color = OnSurfaceVariant,
                    fontWeight = FontWeight.Bold,
                )
            }
        }
    }
}
