package no.svorka.mcms

import android.app.Application
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.BackHandler
import androidx.activity.compose.setContent
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Dashboard
import androidx.compose.material.icons.filled.Hub
import androidx.compose.material.icons.filled.Router
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material3.Icon
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import no.svorka.mcms.core.McmsConnection
import no.svorka.mcms.core.OltStateDoc
import no.svorka.mcms.core.OnuStateDoc
import no.svorka.mcms.ui.*

/**
 * Holds [AppState] in a ViewModel so it (and its in-memory session/cookie jar)
 * survives configuration changes — rotation/dark-mode no longer rebuilds the
 * connection and bounces the user back to the login screen.
 */
class AppViewModel(application: Application) : AndroidViewModel(application) {
    val state = AppState(application.applicationContext)
}

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            val app = viewModel<AppViewModel>().state
            PonGoTheme { RootApp(app) }
        }
    }
}

private sealed interface Screen {
    data object Main : Screen
    data class OnuDetail(val id: String) : Screen
    data class OltDetail(val id: String, val title: String) : Screen
    data class AbnormalRx(val onus: List<OnuStateDoc>) : Screen
    data class LaserOff(val olts: List<OltStateDoc>) : Screen
}

@Composable
private fun RootApp(app: AppState) {
    when {
        !app.isConfigured -> SettingsScreen(app, initialSetup = true, onClose = {})
        !app.isAuthenticated -> {
            var showSettings by remember { mutableStateOf(false) }
            if (showSettings) SettingsScreen(app, initialSetup = false, onClose = { showSettings = false })
            else LoginScreen(app, onOpenSettings = { showSettings = true })
        }
        else -> {
            val connection = app.connection
            if (connection == null) { SettingsScreen(app, initialSetup = true, onClose = {}); return }
            var stack by remember { mutableStateOf<List<Screen>>(listOf(Screen.Main)) }
            BackHandler(enabled = stack.size > 1) { stack = stack.dropLast(1) }
            when (val top = stack.last()) {
                Screen.Main -> MainScaffold(
                    app, connection,
                    openOnu = { stack = stack + Screen.OnuDetail(it) },
                    openOlt = { id, t -> stack = stack + Screen.OltDetail(id, t) },
                    openAbnormalRx = { stack = stack + Screen.AbnormalRx(it) },
                    openLaserOff = { stack = stack + Screen.LaserOff(it) },
                )
                is Screen.OnuDetail -> OnuDetailScreen(connection, top.id, onBack = { stack = stack.dropLast(1) })
                is Screen.OltDetail -> OltDetailScreen(connection, top.id, top.title, onBack = { stack = stack.dropLast(1) }, openOnu = { stack = stack + Screen.OnuDetail(it) })
                is Screen.AbnormalRx -> AbnormalRxScreen(top.onus, onBack = { stack = stack.dropLast(1) }, openOnu = { stack = stack + Screen.OnuDetail(it) })
                is Screen.LaserOff -> LaserOffScreen(top.olts, onBack = { stack = stack.dropLast(1) }, openOlt = { id, t -> stack = stack + Screen.OltDetail(id, t) })
            }
        }
    }
}

@Composable
private fun MainScaffold(
    app: AppState,
    connection: McmsConnection,
    openOnu: (String) -> Unit,
    openOlt: (String, String) -> Unit,
    openAbnormalRx: (List<OnuStateDoc>) -> Unit,
    openLaserOff: (List<OltStateDoc>) -> Unit,
) {
    var tab by rememberSaveable { mutableStateOf(0) }
    Scaffold(bottomBar = {
        NavigationBar {
            NavigationBarItem(selected = tab == 0, onClick = { tab = 0 }, icon = { Icon(Icons.Filled.Dashboard, null) }, label = { Text("Dashboard") })
            NavigationBarItem(selected = tab == 1, onClick = { tab = 1 }, icon = { Icon(Icons.Filled.Hub, null) }, label = { Text("ONUs") })
            NavigationBarItem(selected = tab == 2, onClick = { tab = 2 }, icon = { Icon(Icons.Filled.Router, null) }, label = { Text("OLTs") })
            NavigationBarItem(selected = tab == 3, onClick = { tab = 3 }, icon = { Icon(Icons.Filled.Settings, null) }, label = { Text("Settings") })
        }
    }) { padding ->
        Box(Modifier.padding(padding)) {
            when (tab) {
                0 -> DashboardScreen(connection, openAbnormalRx, openLaserOff)
                1 -> OnuListScreen(connection, openOnu)
                2 -> OltListScreen(connection, openOlt)
                else -> SettingsScreen(app, initialSetup = false, onClose = { tab = 0 })
            }
        }
    }
}
