// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later

package space.rcmd.android.sizzle.ui

import androidx.activity.compose.BackHandler
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.GridView
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material.icons.filled.Tune
import androidx.compose.material.icons.filled.Widgets
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Icon
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.NavigationBarItemDefaults
import androidx.compose.material3.NavigationRail
import androidx.compose.material3.NavigationRailItem
import androidx.compose.material3.NavigationRailItemDefaults
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import space.rcmd.android.sizzle.ui.mixer.MixerScreen
import space.rcmd.android.sizzle.ui.settings.SettingsScreen
import space.rcmd.android.sizzle.ui.theme.LocalRetro
import space.rcmd.android.sizzle.ui.toolbox.ToolboxScreen
import space.rcmd.android.sizzle.ui.tracker.TrackerScreen

/**
 * The top-level layout: the active tab's screen fills the space above a standard
 * Material 3 [NavigationBar]. The pattern grid / mixer still use the bespoke retro
 * look, but chrome (this bar and the Settings tab) uses stock Material components
 * for familiar, accessible interaction.
 */
private data class TabSpec(val title: String, val icon: ImageVector)

private val TABS = listOf(
    TabSpec("Tracker", Icons.Filled.GridView),
    TabSpec("Mix", Icons.Filled.Tune),
    TabSpec("Toolbox", Icons.Filled.Widgets),
    TabSpec("Setup", Icons.Filled.Settings),
)

@Composable
fun SizzleApp(vm: AppViewModel) {
    val c = LocalRetro.current
    // System back / edge-swipe steps to the previous tab. Deeper handlers (a
    // Toolbox editor, a Settings subsection) are composed inside the active screen
    // and intercept first. On the first tab this is disabled, so back falls through
    // to the system default (leaving the app).
    BackHandler(enabled = vm.selectedTab > 0) { vm.selectTab(vm.selectedTab - 1) }
    if (isLandscape()) {
        // Landscape: a side nav rail so the (short) vertical space goes entirely to
        // the active screen instead of a bottom bar.
        Row(Modifier.fillMaxSize().background(c.background)) {
            SideNav(vm)
            Box(Modifier.weight(1f).fillMaxHeight()) { ActiveScreen(vm) }
        }
    } else {
        Column(Modifier.fillMaxSize().background(c.background)) {
            Box(Modifier.weight(1f).fillMaxWidth()) { ActiveScreen(vm) }
            BottomNav(vm)
        }
    }

    // App-wide notice if the low-latency (Oboe) backend couldn't start and playback
    // fell back to the standard path.
    vm.nativeAudioError?.let { msg ->
        AlertDialog(
            onDismissRequest = { vm.dismissNativeAudioError() },
            title = { Text("Audio engine") },
            text = { Text(msg) },
            confirmButton = { TextButton(onClick = { vm.dismissNativeAudioError() }) { Text("OK") } },
        )
    }
}

/** The active tab's screen. */
@Composable
private fun ActiveScreen(vm: AppViewModel) {
    when (vm.selectedTab) {
        0 -> TrackerScreen(vm)
        1 -> MixerScreen(vm)
        2 -> ToolboxScreen(vm)
        3 -> SettingsScreen(vm)
    }
}

/** Bottom navigation bar (portrait). */
@Composable
private fun BottomNav(vm: AppViewModel) {
    val c = LocalRetro.current
    NavigationBar(containerColor = c.surface) {
        TABS.forEachIndexed { index, tab ->
            NavigationBarItem(
                selected = vm.selectedTab == index,
                onClick = { vm.selectTab(index) },
                icon = { Icon(tab.icon, contentDescription = tab.title) },
                label = { Text(tab.title) },
                colors = NavigationBarItemDefaults.colors(
                    selectedIconColor = c.background,
                    selectedTextColor = c.accent,
                    indicatorColor = c.accent,
                    unselectedIconColor = c.textDim,
                    unselectedTextColor = c.textDim,
                ),
            )
        }
    }
}

/** Side navigation rail (landscape) — same tabs, laid out vertically down the left
 *  edge so the screen keeps its full height. */
@Composable
private fun SideNav(vm: AppViewModel) {
    val c = LocalRetro.current
    NavigationRail(containerColor = c.surface) {
        TABS.forEachIndexed { index, tab ->
            NavigationRailItem(
                selected = vm.selectedTab == index,
                onClick = { vm.selectTab(index) },
                icon = { Icon(tab.icon, contentDescription = tab.title) },
                label = { Text(tab.title) },
                colors = NavigationRailItemDefaults.colors(
                    selectedIconColor = c.background,
                    selectedTextColor = c.accent,
                    indicatorColor = c.accent,
                    unselectedIconColor = c.textDim,
                    unselectedTextColor = c.textDim,
                ),
            )
        }
    }
}
