from nicegui import ui
import db
import auth as auth_module
import layout


def _stat_card(label: str, value: int, icon: str, color: str) -> None:
    with ui.card().classes("flex-1 p-5"):
        with ui.row().classes("items-center justify-between w-full"):
            with ui.column().classes("gap-1"):
                ui.label(str(value)).classes("text-3xl font-bold text-gray-800")
                ui.label(label).classes("text-sm text-gray-500")
            ui.icon(icon, size="xl").classes(f"text-{color}-400")


@ui.page("/dashboard")
async def dashboard():
    await auth_module.sync_session()
    if not auth_module.is_authenticated():
        ui.navigate.to("/login")
        return

    user = auth_module.current_user()

    with layout.page("Overview"):
        # ── stat cards ──────────────────────────────────────────────────────
        n_organizations = await db.fetchval("SELECT COUNT(*) FROM organization")
        n_departments = await db.fetchval("SELECT COUNT(*) FROM department")
        n_users = await db.fetchval("SELECT COUNT(*) FROM user_account")
        n_management = await db.fetchval("SELECT COUNT(*) FROM management")

        with ui.row().classes("w-full gap-4"):
            _stat_card("Organizations", n_organizations, "business", "black")
            _stat_card("Departments", n_departments, "folder", "black")
            _stat_card("Users", n_users, "people", "black")
            _stat_card("Access grants", n_management, "science", "black")

        # ── recent sensor activity ───────────────────────────────────────────
        ui.label("Recent sensor activity").classes(
            "text-lg font-semibold text-gray-700 mt-2"
        )

        try:
            rows = await db.fetch(
                "SELECT time, entity, metric, value FROM sensor_data_recent($1, 20)",
                user["email"],
            )

            columns = [
                {"name": "time", "label": "Time", "field": "time", "align": "left"},
                {
                    "name": "entity",
                    "label": "Entity",
                    "field": "entity",
                    "align": "left",
                },
                {
                    "name": "metric",
                    "label": "Metric",
                    "field": "metric",
                    "align": "left",
                },
                {"name": "value", "label": "Value", "field": "value", "align": "right"},
            ]
            row_data = [
                {
                    "time": r["time"].strftime("%Y-%m-%d %H:%M:%S"),
                    "entity": r["entity"],
                    "metric": r["metric"],
                    "value": round(r["value"], 4),
                }
                for r in rows
            ]

            if row_data:
                ui.table(columns=columns, rows=row_data, row_key="time").classes(
                    "w-full"
                )
            else:
                ui.label("No sensor data yet.").classes("text-gray-400 text-sm")

        except Exception as e:
            with ui.card().classes("w-full p-4 bg-yellow-50 border border-yellow-200"):
                ui.label("⚠ Could not load sensor data").classes(
                    "font-semibold text-yellow-800"
                )
                ui.label(str(e)).classes("text-sm text-yellow-700 font-mono mt-1")
