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


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

    organizations = await db.fetch("SELECT id, name FROM organization ORDER BY name")
    rows = await db.fetch(
        """
        SELECT d.id, d.name, d.created_at, i.name AS organization_name
        FROM department d
        JOIN organization i ON i.id = d.organization_id
        ORDER BY i.name, d.name
        """
    )

    with layout.page("Departments"):
        with ui.row().classes("w-full items-center justify-between -mt-2"):
            ui.label(f"{len(rows)} department(s)").classes("text-sm text-gray-500")
            ui.button(
                "Add department", icon="add", on_click=lambda: add_dialog.open()
            ).props("color=primary")

        columns = [
            {
                "name": "organization_name",
                "label": "Organization",
                "field": "organization_name",
                "align": "left",
            },
            {"name": "name", "label": "Department", "field": "name", "align": "left"},
            {
                "name": "created_at",
                "label": "Created",
                "field": "created_at",
                "align": "left",
            },
            {"name": "actions", "label": "", "field": "actions", "align": "right"},
        ]
        row_data = [
            {
                "id": str(r["id"]),
                "name": r["name"],
                "organization_name": r["organization_name"],
                "created_at": r["created_at"].strftime("%Y-%m-%d"),
            }
            for r in rows
        ]

        table = ui.table(columns=columns, rows=row_data, row_key="id").classes("w-full")
        with table.add_slot("body-cell-actions"):
            with table.cell():
                ui.button(icon="delete").props("flat round dense color=negative").on(
                    "click",
                    js_handler="() => emit(props.row)",
                    handler=lambda e: _confirm_delete(e.args["id"], e.args["name"]),
                )

        # ── add dialog ────────────────────────────────────────────────────────
        organization_options = {str(i["id"]): i["name"] for i in organizations}

        with ui.dialog() as add_dialog, ui.card().classes("w-80 p-6 gap-4"):
            ui.label("New department").classes("text-lg font-semibold")
            inst_select = ui.select(organization_options, label="Organization").classes(
                "w-full"
            )
            name_input = (
                ui.input("Name", placeholder="e.g. MBP")
                .on("keydown.enter", lambda e: save())
                .classes("w-full")
            )
            error = ui.label("").classes("text-red-500 text-sm")

            async def save():
                error.text = ""
                if not inst_select.value or not name_input.value.strip():
                    error.text = "All fields are required."
                    return
                try:
                    await db.execute(
                        "INSERT INTO department (organization_id, name) VALUES ($1::uuid, $2)",
                        inst_select.value,
                        name_input.value.strip(),
                    )
                    add_dialog.close()
                    ui.navigate.to("/admin/departments")
                except Exception as e:
                    error.text = f"Error: {e}"

            with ui.row().classes("w-full justify-end gap-2 mt-2"):
                ui.button("Cancel", on_click=add_dialog.close).props("flat")
                ui.button("Save", on_click=save).props("color=primary")


def _confirm_delete(dept_id: str, name: str) -> None:
    with ui.dialog() as dlg, ui.card().classes("p-6 gap-4"):
        ui.label(f'Delete "{name}"?').classes("text-lg font-semibold")
        ui.label(
            "Sensor data linked to this department will lose its department reference."
        ).classes("text-sm text-gray-500")

        async def confirm():
            try:
                await db.execute("DELETE FROM department WHERE id = $1", dept_id)
                dlg.close()
                ui.navigate.to("/admin/departments")
            except Exception as e:
                ui.notify(f"Error: {e}", color="negative")

        with ui.row().classes("w-full justify-end gap-2"):
            ui.button("Cancel", on_click=dlg.close).props("flat")
            ui.button("Delete", on_click=confirm).props("color=negative")

    dlg.open()
