import json

from fasthtml.common import *


def rbac_admin_content(cfg, error, success, preview_text):
    return Div(
        H1("RBAC Administration", cls="text-3xl font-bold"),
        P("Edits save to SQLite immediately and also update the .vyasa file for transparency.", cls="text-slate-600 dark:text-slate-400"),
        P("Rule patterns are matched against request paths (e.g. /posts/ai/...).", cls="text-slate-500 dark:text-slate-500 text-sm"),
        Div(P(error, cls="text-red-600") if error else None, P(success, cls="text-emerald-600") if success else None, cls="mt-4"),
        Form(
            Div(Label(Input(type="checkbox", name="enabled", checked=cfg.get("enabled", False), cls="mr-2"), Span("Enable RBAC"), cls="flex items-center gap-2"), cls="mt-6"),
            Div(Label("Default roles (comma separated)", cls="block text-sm font-medium mb-2"), Input(type="text", name="default_roles", value=", ".join(cfg.get("default_roles", [])), cls="w-full px-3 py-2 rounded-md border border-slate-200 dark:border-slate-700 bg-white/80 dark:bg-slate-900/60"), cls="mt-6"),
            Div(Label("Role users JSON", cls="block text-sm font-medium mb-2"), Textarea(json.dumps(cfg.get("role_users", {}), indent=2, sort_keys=True), name="role_users_json", rows="6", cls="w-full px-3 py-2 font-mono text-xs rounded-md border border-slate-200 dark:border-slate-700 bg-white/80 dark:bg-slate-900/60"), cls="mt-6"),
            Div(Label("User roles JSON", cls="block text-sm font-medium mb-2"), Textarea(json.dumps(cfg.get("user_roles", {}), indent=2, sort_keys=True), name="user_roles_json", rows="6", cls="w-full px-3 py-2 font-mono text-xs rounded-md border border-slate-200 dark:border-slate-700 bg-white/80 dark:bg-slate-900/60"), cls="mt-6"),
            Div(Label("Rules JSON", cls="block text-sm font-medium mb-2"), Textarea(json.dumps(cfg.get("rules", []), indent=2, sort_keys=True), name="rules_json", rows="8", cls="w-full px-3 py-2 font-mono text-xs rounded-md border border-slate-200 dark:border-slate-700 bg-white/80 dark:bg-slate-900/60"), cls="mt-6"),
            Button("Save RBAC", type="submit", cls="mt-6 px-4 py-2 rounded-md bg-blue-600 text-white hover:bg-blue-700"),
            method="post", cls="mt-4",
        ),
        Div(H2("Preview (.vyasa)", cls="text-xl font-semibold mt-10"), Pre(preview_text, cls="mt-3 p-4 rounded-md bg-slate-100 dark:bg-slate-900/60 text-xs overflow-x-auto")),
        cls="max-w-3xl mx-auto py-10 px-6",
    )
