package com.placeholder.sherpai2.ui.navigation

import android.net.Uri
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavHostController
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.navArgument
import com.placeholder.sherpai2.ui.devscreens.DummyScreen
import com.placeholder.sherpai2.ui.album.AlbumViewScreen
import com.placeholder.sherpai2.ui.album.AlbumViewModel
import com.placeholder.sherpai2.ui.collections.CollectionsScreen
import com.placeholder.sherpai2.ui.collections.CollectionsViewModel
import com.placeholder.sherpai2.ui.discover.DiscoverPeopleScreen
import com.placeholder.sherpai2.ui.explore.ExploreScreen
import com.placeholder.sherpai2.ui.imagedetail.ImageDetailScreen
import com.placeholder.sherpai2.ui.modelinventory.PersonInventoryScreen
import com.placeholder.sherpai2.ui.search.SearchScreen
import com.placeholder.sherpai2.ui.search.SearchViewModel
import com.placeholder.sherpai2.ui.tags.TagManagementScreen
import com.placeholder.sherpai2.ui.trainingprep.ScanResultsScreen
import com.placeholder.sherpai2.ui.trainingprep.ScanningState
import com.placeholder.sherpai2.ui.trainingprep.TrainViewModel
import com.placeholder.sherpai2.ui.trainingprep.TrainingScreen
import com.placeholder.sherpai2.ui.trainingprep.TrainingPhotoSelectorScreen
import com.placeholder.sherpai2.ui.rollingscan.RollingScanScreen
import com.placeholder.sherpai2.ui.utilities.PhotoUtilitiesScreen
import java.net.URLDecoder
import java.net.URLEncoder
import com.placeholder.sherpai2.ui.navigation.AppRoutes

/**
 * AppNavHost - UPDATED with Discover People screen
 *
 * NEW: Replaces placeholder "Models" screen with auto-clustering face discovery
 */
@Composable
fun AppNavHost(
    navController: NavHostController,
    modifier: Modifier = Modifier
) {
    NavHost(
        navController = navController,
        startDestination = AppRoutes.SEARCH,
        modifier = modifier
    ) {

        // ==========================================
        // PHOTO BROWSING
        // ==========================================

        /**
         * SEARCH SCREEN
         */
        composable(AppRoutes.SEARCH) {
            val searchViewModel: SearchViewModel = hiltViewModel()
            val collectionsViewModel: CollectionsViewModel = hiltViewModel()

            SearchScreen(
                searchViewModel = searchViewModel,
                onImageClick = { imageUri ->
                    ImageListHolder.clear()
                    val encodedUri = URLEncoder.encode(imageUri, "UTF-8")
                    navController.navigate("${AppRoutes.IMAGE_DETAIL}/$encodedUri")
                },
                onAlbumClick = { tagValue ->
                    navController.navigate("album/tag/$tagValue")
                },
                onSaveToCollection = { includedPeople, excludedPeople, includedTags, excludedTags, dateRange, photoCount ->
                    collectionsViewModel.startSmartCollectionFromSearch(
                        includedPeople = includedPeople,
                        excludedPeople = excludedPeople,
                        includedTags = includedTags,
                        excludedTags = excludedTags,
                        dateRange = dateRange,
                        photoCount = photoCount
                    )
                }
            )
        }

        /**
         * EXPLORE SCREEN
         */
        composable(AppRoutes.EXPLORE) {
            ExploreScreen(
                onAlbumClick = { albumType, albumId ->
                    navController.navigate("album/$albumType/$albumId")
                }
            )
        }

        /**
         * COLLECTIONS SCREEN
         */
        composable(AppRoutes.COLLECTIONS) {
            val collectionsViewModel: CollectionsViewModel = hiltViewModel()

            CollectionsScreen(
                viewModel = collectionsViewModel,
                onCollectionClick = { collectionId ->
                    navController.navigate("album/collection/$collectionId")
                },
                onCreateClick = {
                    navController.navigate(AppRoutes.SEARCH)
                }
            )
        }

        /**
         * IMAGE DETAIL SCREEN
         */
        composable(
            route = "${AppRoutes.IMAGE_DETAIL}/{imageUri}",
            arguments = listOf(
                navArgument("imageUri") {
                    type = NavType.StringType
                }
            )
        ) { backStackEntry ->
            val imageUri = backStackEntry.arguments?.getString("imageUri")
                ?.let { URLDecoder.decode(it, "UTF-8") }
                ?: error("imageUri missing from navigation")

            val allImageUris = ImageListHolder.getImageList()

            ImageDetailScreen(
                imageUri = imageUri,
                onBack = {
                    ImageListHolder.clear()
                    navController.popBackStack()
                },
                navController = navController,
                allImageUris = allImageUris
            )
        }

        /**
         * ALBUM VIEW SCREEN
         */
        composable(
            route = "album/{albumType}/{albumId}",
            arguments = listOf(
                navArgument("albumType") {
                    type = NavType.StringType
                },
                navArgument("albumId") {
                    type = NavType.StringType
                }
            )
        ) {
            val albumViewModel: AlbumViewModel = hiltViewModel()
            val uiState by albumViewModel.uiState.collectAsStateWithLifecycle()

            AlbumViewScreen(
                onBack = {
                    navController.popBackStack()
                },
                onImageClick = { imageUri ->
                    val allImageUris = if (uiState is com.placeholder.sherpai2.ui.album.AlbumUiState.Success) {
                        (uiState as com.placeholder.sherpai2.ui.album.AlbumUiState.Success)
                            .photos
                            .map { it.image.imageUri }
                    } else {
                        emptyList()
                    }

                    ImageListHolder.setImageList(allImageUris)

                    val encodedUri = URLEncoder.encode(imageUri, "UTF-8")
                    navController.navigate("${AppRoutes.IMAGE_DETAIL}/$encodedUri")
                }
            )
        }

        // ==========================================
        // FACE RECOGNITION SYSTEM
        // ==========================================

        /**
         * DISCOVER PEOPLE SCREEN - ✨ NEW!
         *
         * Auto-clustering face discovery with spoon-feed naming flow:
         * 1. Auto-clusters all faces in library (2-5 min)
         * 2. Shows beautiful grid of discovered people
         * 3. User taps to name each person
         * 4. Captures: name, DOB, sibling relationships
         * 5. Triggers deep background scan with age tagging
         *
         * Replaces: Old "Models" placeholder screen
         */
        composable(AppRoutes.DISCOVER) {
            DiscoverPeopleScreen()
        }

        /**
         * PERSON INVENTORY SCREEN
         */
        composable(AppRoutes.INVENTORY) {
            PersonInventoryScreen(
                onNavigateToPersonDetail = { personId ->
                    navController.navigate(AppRoutes.SEARCH)
                }
            )
        }

        /**
         * TRAINING FLOW - Manual training (still available)
         */
        composable(AppRoutes.TRAIN) { entry ->
            val trainViewModel: TrainViewModel = hiltViewModel()
            val uiState by trainViewModel.uiState.collectAsState()

            val selectedUris = entry.savedStateHandle.get<List<Uri>>("selected_image_uris")

            LaunchedEffect(selectedUris) {
                if (selectedUris != null && uiState is ScanningState.Idle) {
                    trainViewModel.scanAndTagFaces(selectedUris)
                    entry.savedStateHandle.remove<List<Uri>>("selected_image_uris")
                }
            }

            when (uiState) {
                is ScanningState.Idle -> {
                    TrainingScreen(
                        onSelectImages = {
                            // Navigate to custom photo selector (shows only faces!)
                            navController.navigate(AppRoutes.TRAINING_PHOTO_SELECTOR)
                        }
                    )
                }
                else -> {
                    ScanResultsScreen(
                        state = uiState,
                        onFinish = {
                            navController.navigate(AppRoutes.INVENTORY) {
                                popUpTo(AppRoutes.TRAIN) { inclusive = true }
                            }
                        }
                    )
                }
            }
        }

        /**
         * TRAINING PHOTO SELECTOR - Premium grid with rolling scan
         */
        composable(AppRoutes.TRAINING_PHOTO_SELECTOR) {
            TrainingPhotoSelectorScreen(
                onBack = {
                    navController.popBackStack()
                },
                onPhotosSelected = { uris ->
                    // Pass selected URIs back to training flow
                    navController.previousBackStackEntry
                        ?.savedStateHandle
                        ?.set("selected_image_uris", uris)
                    navController.popBackStack()
                },
                onLaunchRollingScan = { seedImageIds ->
                    // Navigate to rolling scan with seeds
                    navController.navigate(AppRoutes.rollingScanRoute(seedImageIds))
                }
            )
        }

        /**
         * ROLLING SCAN - Similarity-based photo discovery
         *
         * Takes seed image IDs, finds similar faces across library
         */
        composable(
            route = AppRoutes.ROLLING_SCAN,
            arguments = listOf(
                navArgument("seedImageIds") {
                    type = NavType.StringType
                }
            )
        ) { backStackEntry ->
            val seedImageIdsString = backStackEntry.arguments?.getString("seedImageIds") ?: ""
            val seedImageIds = seedImageIdsString.split(",").filter { it.isNotBlank() }

            RollingScanScreen(
                seedImageIds = seedImageIds,
                onSubmitForTraining = { selectedUris ->
                    // Pass selected URIs back to training flow (via photo selector)
                    navController.getBackStackEntry(AppRoutes.TRAIN)
                        .savedStateHandle
                        .set("selected_image_uris", selectedUris.map { Uri.parse(it) })
                    // Pop back to training screen
                    navController.popBackStack(AppRoutes.TRAIN, inclusive = false)
                },
                onNavigateBack = {
                    navController.popBackStack()
                }
            )
        }

        /**
         * MODELS SCREEN - DEPRECATED, kept for backwards compat
         */
        composable(AppRoutes.MODELS) {
            DummyScreen(
                title = "AI Models",
                subtitle = "Use 'Discover' instead"
            )
        }

        // ==========================================
        // ORGANIZATION
        // ==========================================

        /**
         * TAGS SCREEN
         */
        composable(AppRoutes.TAGS) {
            TagManagementScreen()
        }

        /**
         * UTILITIES SCREEN
         */
        composable(AppRoutes.UTILITIES) {
            PhotoUtilitiesScreen()
        }

        // ==========================================
        // SETTINGS
        // ==========================================

        /**
         * SETTINGS SCREEN
         */
        composable(AppRoutes.SETTINGS) {
            com.placeholder.sherpai2.ui.settings.SettingsScreen()
        }
    }
}