package lu.rewardflow.terminal.ui

import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import lu.rewardflow.terminal.ui.pin.PinScreen
import lu.rewardflow.terminal.ui.setup.SetupScreen
import lu.rewardflow.terminal.ui.setup.SetupViewModel
import lu.rewardflow.terminal.ui.terminal.TerminalScreen

/**
 * Navigation flow:
 *
 * 1. SetupScreen — first-time device setup (scan QR from web)
 * 2. PinScreen — staff enters PIN to unlock terminal
 * 3. TerminalScreen — main POS terminal (scan, search, transact)
 *
 * After setup, the app always starts at PinScreen.
 * After 2 min idle on TerminalScreen, auto-lock back to PinScreen.
 */
@Composable
fun RewardFlowNavHost() {
    val navController = rememberNavController()
    val setupViewModel: SetupViewModel = hiltViewModel()
    val isSetUp by setupViewModel.isDeviceSetUp.collectAsState(initial = false)

    val startDestination = if (isSetUp) "pin" else "setup"

    NavHost(navController = navController, startDestination = startDestination) {
        composable("setup") {
            SetupScreen(
                onSetupComplete = {
                    navController.navigate("pin") {
                        popUpTo("setup") { inclusive = true }
                    }
                },
            )
        }

        composable("pin") {
            PinScreen(
                onPinVerified = { staffPinId, staffName ->
                    navController.navigate("terminal/$staffPinId/$staffName") {
                        popUpTo("pin") { inclusive = true }
                    }
                },
            )
        }

        composable("terminal/{staffPinId}/{staffName}") { backStackEntry ->
            val staffPinId = backStackEntry.arguments?.getString("staffPinId")?.toIntOrNull() ?: 0
            val staffName = backStackEntry.arguments?.getString("staffName") ?: ""

            TerminalScreen(
                staffPinId = staffPinId,
                staffName = staffName,
                onLockScreen = {
                    navController.navigate("pin") {
                        popUpTo("terminal/{staffPinId}/{staffName}") { inclusive = true }
                    }
                },
            )
        }
    }
}
