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


SETTING_GROUPS = [
    {
        "namespace": "smtp",
        "title": "Mail (SMTP)",
        "icon": "email",
        "fields": [
            {"key": "host", "label": "Host", "password": False},
            {"key": "port", "label": "Port", "password": False},
            {"key": "user", "label": "User", "password": False},
            {"key": "password", "label": "Password", "password": True},
            {"key": "from", "label": "From", "password": False},
        ],
    },
]


@ui.page("/admin/settings")
async def settings_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

    with layout.page("Settings"):
        for group in SETTING_GROUPS:
            await _setting_group(group)


async def _setting_group(group: dict) -> None:
    namespace = group["namespace"]
    with ui.card().classes("w-full p-6 gap-4"):
        with ui.row().classes("items-center gap-2 mb-2"):
            ui.icon(group["icon"]).classes("text-xl").style("color: #f15b25")
            ui.label(group["title"]).classes("text-lg font-semibold")

        inputs: dict[str, ui.input] = {}
        for field in group["fields"]:
            current = await db.get_setting(field["key"], namespace) or ""
            kwargs = {"label": field["label"], "value": current}
            if field["password"]:
                kwargs["password"] = True
                kwargs["password_toggle_button"] = True
            inp = ui.input(**kwargs).classes("w-full")
            inputs[field["key"]] = inp

        status = ui.label("").classes("text-sm")

        async def save(ns=namespace, inps=inputs, lbl=status):
            try:
                for k, inp in inps.items():
                    await db.set_setting(k, inp.value, ns)
                lbl.classes("text-green-600", remove="text-red-500")
                lbl.text = "Saved."
            except Exception as e:
                lbl.classes("text-red-500", remove="text-green-600")
                lbl.text = f"Error: {e}"

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