package chat.vojo.proxy.ui

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.WindowInsetsSides
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.only
import androidx.compose.foundation.layout.safeDrawing
import androidx.compose.foundation.layout.tappableElement
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.animation.core.FastOutSlowInEasing
import androidx.compose.animation.core.tween
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.PagerDefaults
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.unit.dp
import chat.vojo.proxy.service.VpnState
import chat.vojo.proxy.ui.theme.Vojo
import kotlinx.coroutines.launch

@Composable
fun MainScreen(
    vm: MainViewModel,
    onConnect: () -> Unit,
    onDisconnect: () -> Unit,
    onReconnect: () -> Unit,
) {
    val proxyState by vm.state.collectAsState()
    val status by vm.status.collectAsState()
    val stats by vm.stats.collectAsState()
    val error by vm.error.collectAsState()
    val connectedSince by vm.connectedSince.collectAsState()
    val events by vm.events.collectAsState()
    val applied by vm.applied.collectAsState()
    val apps by vm.apps.collectAsState()
    val appsLoading by vm.appsLoading.collectAsState()

    val tabs = listOf("Туннель", "Серверы", "Приложения", "Опции")
    val pagerState = rememberPagerState(pageCount = { tabs.size })
    val scope = rememberCoroutineScope()

    var editorOpen by rememberSaveable { mutableStateOf(false) }
    var editorInitialId by rememberSaveable { mutableStateOf<String?>(null) }

    val active = proxyState.activeConfig
    val settings = proxyState.settings
    val connected = status == VpnState.Status.CONNECTED
    // The config the running tunnel was actually built from (null when down).
    // Green/live styling keys off this, NOT the merely-selected server.
    val liveId = if (connected) applied?.configId else null

    // Static backdrop (#181A20) stretched edge-to-edge over the whole window —
    // shows through the inter-pane gap during a swipe and behind the system bars.
    Box(Modifier.fillMaxSize().background(Vojo.bgPanel)) {
        // Only the TOP (status bar / cutout) and SIDES are padded here — the
        // sheets reach the very bottom so the backdrop never shows as a strip
        // below them. The bottom system inset is applied INSIDE each sheet.
        Column(
            Modifier
                .fillMaxSize()
                .windowInsetsPadding(
                    WindowInsets.safeDrawing.only(WindowInsetsSides.Top + WindowInsetsSides.Horizontal)
                ),
        ) {
            SegmentTabs(
                tabs = tabs,
                pagerState = pagerState,
                onSelect = {
                    scope.launch { pagerState.animateScrollToPage(it, animationSpec = tween(260, easing = FastOutSlowInEasing)) }
                },
                modifier = Modifier.fillMaxWidth(),
            )
            Spacer(Modifier.height(8.dp)) // backdrop strip above the sheets

            // The panes are sheets (#0D0E11) with a rounded top, sliding on the
            // backdrop like a gallery; pageSpacing surfaces the backdrop gap.
            // A short ease-out snap keeps the settle from feeling sluggish.
            HorizontalPager(
                state = pagerState,
                modifier = Modifier.fillMaxSize(),
                pageSpacing = 18.dp,
                beyondViewportPageCount = 1,
                flingBehavior = PagerDefaults.flingBehavior(
                    state = pagerState,
                    snapAnimationSpec = tween(260, easing = FastOutSlowInEasing),
                ),
            ) { page ->
                Box(
                    Modifier
                        .fillMaxSize()
                        .clip(RoundedCornerShape(topStart = 26.dp, topEnd = 26.dp))
                        .background(Vojo.bgApp),
                ) {
                    // Sheet background reaches the bottom edge; its CONTENT clears
                    // the 3-button nav bar via tappableElement (0 in gesture mode,
                    // so gesture nav stays truly edge-to-edge).
                    Box(
                        Modifier
                            .fillMaxSize()
                            .windowInsetsPadding(WindowInsets.tappableElement.only(WindowInsetsSides.Bottom)),
                    ) {
                        when (page) {
                        0 -> ConnectionScreen(
                            activeConfig = active,
                            configs = proxyState.configs,
                            status = status,
                            stats = stats,
                            connectedSince = connectedSince,
                            error = error,
                            events = events,
                            applied = applied,
                            settings = settings,
                            liveId = liveId,
                            onConnect = onConnect,
                            onDisconnect = onDisconnect,
                            onReconnect = onReconnect,
                            onSelectServer = { vm.setActive(it) },
                        )
                        1 -> ServersScreen(
                            configs = proxyState.configs,
                            activeId = active?.id,
                            liveId = liveId,
                            onSelect = { vm.setActive(it) },
                            onAdd = { editorInitialId = null; editorOpen = true },
                            onEdit = { editorInitialId = it.id; editorOpen = true },
                            onDelete = { vm.deleteConfig(it) },
                        )
                        2 -> AppsScreen(
                            apps = apps,
                            loading = appsLoading,
                            selected = settings.allowedApps,
                            loadIcon = { vm.iconFor(it) },
                            cachedIcon = { vm.cachedIcon(it) },
                            onToggle = { pkg, on -> vm.toggleApp(pkg, on) },
                            onClear = { vm.clearApps() },
                            onLoad = { vm.loadApps() },
                        )
                        3 -> SettingsScreen(
                            settings = settings,
                            onChange = { transform -> vm.updateSettings(transform) },
                        )
                        }
                    }
                }
            }
        }
    }

    if (editorOpen) {
        ServerEditorDialog(
            initial = remember(editorInitialId, proxyState.configs) {
                proxyState.configs.firstOrNull { it.id == editorInitialId }
            },
            onSave = { vm.saveConfig(it); editorOpen = false },
            onDismiss = { editorOpen = false },
        )
    }
}
