@file:OptIn(ExperimentalMaterial3AdaptiveApi::class)

package wang.yaojia.webterm.nav

import androidx.compose.material3.adaptive.ExperimentalMaterial3AdaptiveApi
import androidx.compose.material3.adaptive.currentWindowAdaptiveInfo
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavHostController
import wang.yaojia.webterm.hostregistry.Host
import wang.yaojia.webterm.screens.AdaptiveHome
import wang.yaojia.webterm.screens.ProjectsScreen
import wang.yaojia.webterm.viewmodels.ApiClientProjectsGateway
import wang.yaojia.webterm.viewmodels.ProjectsViewModel
import wang.yaojia.webterm.wiring.AppEnvironment

/**
 * The Projects grid (A23) inside the A26 adaptive shell: [ProjectsScreen] (list pane) beside the selected
 * [ProjectDetailContent] (detail pane) on large screens, or a single grid on compact where a card tap
 * pushes the project-detail destination. "在此启动 Claude" (from a card or the detail) is routed through
 * [ProjectsViewModel.requestOpenClaude] → a validated [ProjectOpenRequest], which this pane consumes into
 * a `newTerminalRoute` navigation (`attach(null, cwd=projectPath)`).
 *
 * Projects run against the FIRST paired host (single-host is the common case; cross-host project selection
 * is a device-QA refinement). The navigation-suite "会话" entry returns to [SessionsHome].
 */
@Composable
public fun ProjectsHome(
    env: AppEnvironment,
    navController: NavHostController,
    modifier: Modifier = Modifier,
) {
    val host by produceState<Host?>(initialValue = null) {
        value = runCatchingCancellable { env.hostStore.loadAll().firstOrNull() }.getOrNull()
    }
    val resolved = host
    if (resolved == null) {
        DetailPlaceholder("尚未配对主机。", modifier)
        return
    }

    val gateway = remember(resolved) { ApiClientProjectsGateway(env.apiClientFactory.create(resolved.endpoint)) }
    val viewModel = remember(gateway) { ProjectsViewModel(gateway) }
    val state by viewModel.uiState.collectAsStateWithLifecycle()

    // "Open Claude here" → spawn a new session in the project cwd, then clear the one-shot signal.
    LaunchedEffect(state.openRequest) {
        val request = state.openRequest ?: return@LaunchedEffect
        navController.navigate(newTerminalRoute(resolved.id, request.cwd))
        viewModel.consumeOpenRequest()
    }

    val sizeClass = currentWindowAdaptiveInfo().windowSizeClass
    val mode = LayoutPolicy.mode(windowWidthOf(sizeClass))
    var selectedPath by rememberSaveable { mutableStateOf<String?>(null) }

    AdaptiveHome(
        listPane = {
            ProjectsScreen(
                viewModel = viewModel,
                onOpenDetail = { path ->
                    if (mode == LayoutMode.LIST_DETAIL) {
                        selectedPath = path
                    } else {
                        navController.navigate(projectDetailRoute(resolved.id, path))
                    }
                },
            )
        },
        detailPane = {
            val path = selectedPath
            if (path != null) {
                ProjectDetailContent(
                    gateway = gateway,
                    path = path,
                    onBack = { selectedPath = null },
                    onOpenClaude = { cwd -> navController.navigate(newTerminalRoute(resolved.id, cwd)) },
                    onViewDiff = { diffPath -> navController.navigate(diffRoute(resolved.id, diffPath)) },
                )
            } else {
                DetailPlaceholder("选择一个项目查看详情。")
            }
        },
        selectedDestination = 1,
        onSelectDestination = { index ->
            if (index == 0) {
                navController.navigate(NavRoutes.SESSIONS) {
                    popUpTo(NavRoutes.SESSIONS) { inclusive = false }
                    launchSingleTop = true
                }
            }
        },
        windowSizeClass = sizeClass,
        modifier = modifier,
    )
}
