from nicegui import ui, app
from auth import current_user, is_superadmin


# (label, path, icon, superadmin_only, hide_from_superadmin)
NAV_ITEMS = [
    ("Overview", "/dashboard", "dashboard", False, False),
    ("─" * 20, None, None, True, False),  # separator
    ("Organizations", "/admin/organizations", "business", True, False),
    ("Departments", "/admin/departments", "folder_open", True, False),
    ("Users", "/admin/users", "people", True, False),
    ("Access Management", "/admin/access-management", "science", True, False),
    ("Mappers", "/admin/mapper", "swap_horiz", True, False),
    ("Settings", "/admin/settings", "settings", True, False),
    ("─" * 20, None, None, False, True),  # separator
    ("My Departments", "/dept/members", "group", False, True),
    ("─" * 20, None, None, False, False),  # separator
    ("Data Explorer", "/data/explorer", "table_view", False, False),
    ("Plots", "/data/plots", "show_chart", False, False),
    ("Alarms", "/alarms", "notifications", False, False),
    ("API Tokens", "/tokens", "vpn_key", False, False),
]


def header() -> None:
    with (
        ui.header()
        .classes("items-center justify-between text-white px-6 py-3")
        .style("background: #1c1c1c")
    ):
        with ui.row().classes("items-center gap-3"):
            ui.image("/images/icon.svg").classes("w-8 h-8")
            ui.label("LEAF Portal").classes("text-xl font-bold tracking-wide")

        user = current_user()
        if user:
            with ui.row().classes("items-center gap-4"):
                ui.label(user["name"]).classes("text-sm opacity-80")
                ui.button(icon="logout", on_click=_logout).props(
                    "flat round dense color=white"
                ).tooltip("Sign out")


def sidebar() -> None:
    with ui.left_drawer(value=True).classes("bg-gray-50 border-r border-gray-200 pt-4"):
        with ui.column().classes("w-full gap-0.5 px-2"):
            current = None
            try:
                from nicegui.client import Client

                current = Client.current.page.path if Client.current else None
            except Exception:
                pass

            superadmin = is_superadmin()
            for label, path, icon, admin_only, hide_from_superadmin in NAV_ITEMS:
                if admin_only and not superadmin:
                    continue
                if hide_from_superadmin and superadmin:
                    continue
                if path is None:
                    ui.separator().classes("my-2")
                    continue
                active = current == path
                with (
                    ui.item(on_click=lambda p=path: ui.navigate.to(p))
                    .classes(
                        "rounded-lg cursor-pointer "
                        + ("text-gray-700" if not active else "")
                    )
                    .style("background: #fff4f0; color: #f15b25;" if active else "")
                    .classes("" if active else "hover:bg-gray-100")
                ):
                    with ui.row().classes("items-center gap-3 px-2 py-2"):
                        ui.icon(icon).classes("text-lg").style(
                            "color: #f15b25" if active else "color: #6b7280"
                        )
                        ui.label(label).classes("text-sm font-medium")


def page(title: str) -> ui.column:
    """Call at the top of every page. Returns the main content column."""
    ui.colors(primary="#f15b25", secondary="#6fd3f2")
    header()
    sidebar()
    col = ui.column().classes("w-full max-w-5xl mx-auto p-6 gap-6")
    with col:
        ui.label(title).classes("text-2xl font-bold text-gray-800")
    return col


async def _logout() -> None:
    app.storage.user.clear()
    ui.navigate.to("/login")
