package com.doctate.watch.presentation

import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.platform.LocalContext
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavType
import androidx.navigation.navArgument
import androidx.wear.compose.material3.AppScaffold
import androidx.wear.compose.navigation.SwipeDismissableNavHost
import androidx.wear.compose.navigation.composable
import androidx.wear.compose.navigation.rememberSwipeDismissableNavController
import com.doctate.watch.DoctateApp
import com.doctate.watch.presentation.theme.DoctateWatchTheme
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch

object Routes {
    const val LIST = "list"
    const val DETAIL = "detail/{caseId}"
    const val RECORDING = "recording/{caseId}"
    fun detail(caseId: String) = "detail/$caseId"
    fun recording(caseId: String) = "recording/$caseId"
}

@Composable
fun AppNav(pendingCommand: StateFlow<NavCommand.Pending>) {
    val navController = rememberSwipeDismissableNavController()
    val pending by pendingCommand.collectAsStateWithLifecycle()
    val app = LocalContext.current.applicationContext as DoctateApp
    val coroutineScope = rememberCoroutineScope()

    // Key on seq so repeated identical commands still fire.
    LaunchedEffect(pending.seq) {
        when (val c = pending.cmd) {
            NavCommand.ShowList -> {
                // Initial value fires at app start; NavHost is already on LIST. No-op.
                // Incoming Complication tap or Tile "Fälle" tap: pop to list if stacked.
                navController.popBackStack(Routes.LIST, inclusive = false)
            }
            NavCommand.NewCase -> {
                val id = app.caseStore.createLocal()
                // Push DETAIL under RECORDING so popBackStack on stop lands
                // on the case page, ready for another recording.
                navController.navigate(Routes.detail(id))
                navController.navigate(Routes.recording(id))
            }
            is NavCommand.ContinueCase -> {
                navController.navigate(Routes.detail(c.caseId))
            }
        }
    }

    DoctateWatchTheme {
        AppScaffold {
            SwipeDismissableNavHost(
                navController = navController,
                startDestination = Routes.LIST,
            ) {
                composable(Routes.LIST) {
                    CaseListScreen(
                        onCaseTap = { caseId ->
                            navController.navigate(Routes.detail(caseId))
                        },
                        onNewCase = {
                            coroutineScope.launch {
                                val id = app.caseStore.createLocal()
                                // Same backstack shape as NavCommand.NewCase:
                                // [LIST, DETAIL, RECORDING] so stop returns to
                                // the case page rather than the list.
                                navController.navigate(Routes.detail(id))
                                navController.navigate(Routes.recording(id))
                            }
                        },
                    )
                }
                composable(
                    route = Routes.DETAIL,
                    arguments = listOf(navArgument("caseId") { type = NavType.StringType }),
                ) { backStack ->
                    val caseId = backStack.arguments?.getString("caseId").orEmpty()
                    CaseDetailScreen(
                        caseId = caseId,
                        onRecord = { navController.navigate(Routes.recording(caseId)) },
                    )
                }
                composable(
                    route = Routes.RECORDING,
                    arguments = listOf(navArgument("caseId") { type = NavType.StringType }),
                ) { backStack ->
                    val caseId = backStack.arguments?.getString("caseId").orEmpty()
                    RecordingScreen(caseId = caseId, onDone = { navController.popBackStack() })
                }
            }
        }
    }
}
