package com.placeholder.sherpai2.ui.presentation

import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.compose.rememberNavController
import androidx.navigation.compose.currentBackStackEntryAsState
import com.placeholder.sherpai2.ui.navigation.AppNavHost
import com.placeholder.sherpai2.ui.navigation.AppRoutes
import kotlinx.coroutines.launch

/**
 * MainScreen - Complete app container with drawer navigation
 *
 * CRITICAL FIX APPLIED:
 * ✅ Removed AppRoutes.DISCOVER from screensWithOwnTopBar
 * ✅ DiscoverPeopleScreen now shows hamburger menu + "Discover People" title!
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun MainScreen(
    viewModel: MainViewModel = hiltViewModel()
) {
    val navController = rememberNavController()
    val drawerState = rememberDrawerState(DrawerValue.Closed)
    val scope = rememberCoroutineScope()

    val currentBackStackEntry by navController.currentBackStackEntryAsState()
    val currentRoute = currentBackStackEntry?.destination?.route

    // Face cache prompt dialog state
    val needsFaceCachePopulation by viewModel.needsFaceCachePopulation.collectAsState()
    val unscannedPhotoCount by viewModel.unscannedPhotoCount.collectAsState()

    // ✅ CRITICAL FIX: DISCOVER is NOT in this list!
    // These screens handle their own TopAppBar/navigation
    val screensWithOwnTopBar = setOf(
        AppRoutes.IMAGE_DETAIL,
        AppRoutes.TRAINING_SCREEN,
        AppRoutes.CROP_SCREEN
    )

    ModalNavigationDrawer(
        drawerState = drawerState,
        drawerContent = {
            AppDrawerContent(
                currentRoute = currentRoute,
                onDestinationClicked = { route ->
                    scope.launch {
                        drawerState.close()
                    }
                    navController.navigate(route) {
                        popUpTo(navController.graph.startDestinationId) {
                            saveState = true
                        }
                        launchSingleTop = true
                        restoreState = true
                    }
                }
            )
        }
    ) {
        Scaffold(
            topBar = {
                // ✅ Show TopAppBar for ALL screens except those with their own
                if (currentRoute !in screensWithOwnTopBar) {
                    TopAppBar(
                        title = {
                            Text(
                                text = when (currentRoute) {
                                    AppRoutes.SEARCH -> "Search"
                                    AppRoutes.EXPLORE -> "Explore"
                                    AppRoutes.COLLECTIONS -> "Collections"
                                    AppRoutes.DISCOVER -> "Discover People"  // ✅ SHOWS NOW!
                                    AppRoutes.INVENTORY -> "People"
                                    AppRoutes.TRAIN -> "Train Model"
                                    AppRoutes.ScanResultsScreen -> "Train New Person"
                                    AppRoutes.TAGS -> "Tags"
                                    AppRoutes.UTILITIES -> "Utilities"
                                    AppRoutes.SETTINGS -> "Settings"
                                    AppRoutes.MODELS -> "AI Models"
                                    else -> {
                                        // Handle dynamic routes like album/{type}/{id}
                                        if (currentRoute?.startsWith("album/") == true) {
                                            "Album"
                                        } else {
                                            "SherpAI"
                                        }
                                    }
                                }
                            )
                        },
                        navigationIcon = {
                            IconButton(onClick = {
                                scope.launch {
                                    drawerState.open()
                                }
                            }) {
                                Icon(
                                    imageVector = Icons.Default.Menu,
                                    contentDescription = "Open menu"
                                )
                            }
                        },
                        colors = TopAppBarDefaults.topAppBarColors(
                            containerColor = MaterialTheme.colorScheme.primaryContainer,
                            titleContentColor = MaterialTheme.colorScheme.onPrimaryContainer,
                            navigationIconContentColor = MaterialTheme.colorScheme.onPrimaryContainer,
                            actionIconContentColor = MaterialTheme.colorScheme.onPrimaryContainer
                        )
                    )
                }
            }
        ) { paddingValues ->
            // ✅ Use YOUR existing AppNavHost - it already has all the screens defined!
            AppNavHost(
                navController = navController,
                modifier = Modifier.padding(paddingValues)
            )
        }
    }

    // ✅ Face cache prompt dialog (shows on app launch if needed)
    if (needsFaceCachePopulation) {
        FaceCachePromptDialog(
            unscannedPhotoCount = unscannedPhotoCount,
            onDismiss = { viewModel.dismissFaceCachePrompt() },
            onScanNow = {
                viewModel.dismissFaceCachePrompt()
                navController.navigate(AppRoutes.UTILITIES)
            }
        )
    }
}