import { jsx, jsxs } from "react/jsx-runtime";
import { useQueryClient, useQuery, useMutation } from "@tanstack/react-query";
import { useState } from "react";
import { s as supabase } from "./client-CJCZGN4z.js";
import { A as AdminShell } from "./AdminShell-fo83oaxY.js";
import { B as Button } from "./button-BXrfXN_b.js";
import { L as Label, I as Input } from "./label-BsuFFEVs.js";
import { T as Textarea } from "./textarea-BBisE2jS.js";
import { T as Table, a as TableHeader, b as TableRow, c as TableHead, d as TableBody, e as TableCell } from "./table-K6UF5XG9.js";
import { D as Dialog, a as DialogContent, b as DialogHeader, c as DialogTitle, d as DialogFooter, A as AlertDialog, e as AlertDialogContent, f as AlertDialogHeader, g as AlertDialogTitle, h as AlertDialogDescription, i as AlertDialogFooter, j as AlertDialogCancel, k as AlertDialogAction } from "./alert-dialog-Cbc2KPWf.js";
import { Trash2, Eye, Plus } from "lucide-react";
import { toast } from "sonner";
import { u as useAuth } from "./use-auth-DoD1gvcu.js";
import "@supabase/supabase-js";
import "@tanstack/react-router";
import "@radix-ui/react-slot";
import "class-variance-authority";
import "clsx";
import "tailwind-merge";
import "@radix-ui/react-label";
import "@radix-ui/react-dialog";
import "@radix-ui/react-alert-dialog";
const ROLES = ["admin", "editor", "writer", "citizen"];
function UsersPage() {
  const qc = useQueryClient();
  const {
    hasRole,
    user: currentUser
  } = useAuth();
  const [viewing, setViewing] = useState(null);
  const [editing, setEditing] = useState(null);
  const [removeTarget, setRemoveTarget] = useState(null);
  const users = useQuery({
    queryKey: ["admin", "users"],
    queryFn: async () => {
      const {
        data: profs,
        error
      } = await supabase.from("profiles").select("id, display_name, avatar_url, bio, created_at").order("created_at", {
        ascending: false
      });
      if (error) throw error;
      const {
        data: r
      } = await supabase.from("user_roles").select("user_id, role");
      return (profs ?? []).map((p) => ({
        ...p,
        roles: (r ?? []).filter((x) => x.user_id === p.id).map((x) => x.role)
      }));
    }
  });
  const saveProfile = useMutation({
    mutationFn: async () => {
      if (!editing) return;
      const {
        error
      } = await supabase.from("profiles").update({
        display_name: editing.display_name,
        bio: editing.bio
      }).eq("id", editing.id);
      if (error) throw error;
    },
    onSuccess: () => {
      toast.success("Profile updated");
      setEditing(null);
      qc.invalidateQueries({
        queryKey: ["admin", "users"]
      });
    },
    onError: (e) => toast.error(e.message)
  });
  const addRole = useMutation({
    mutationFn: async ({
      uid,
      role
    }) => {
      const {
        error
      } = await supabase.from("user_roles").insert({
        user_id: uid,
        role
      });
      if (error) throw error;
    },
    onSuccess: () => {
      toast.success("Role added");
      qc.invalidateQueries({
        queryKey: ["admin", "users"]
      });
    },
    onError: (e) => toast.error(e.message)
  });
  const removeRole = useMutation({
    mutationFn: async ({
      uid,
      role
    }) => {
      const {
        error
      } = await supabase.from("user_roles").delete().eq("user_id", uid).eq("role", role);
      if (error) throw error;
    },
    onSuccess: () => {
      toast.success("Role removed");
      setRemoveTarget(null);
      qc.invalidateQueries({
        queryKey: ["admin", "users"]
      });
    },
    onError: (e) => toast.error(e.message)
  });
  if (!hasRole("admin")) {
    return /* @__PURE__ */ jsx(AdminShell, { title: "Users", children: /* @__PURE__ */ jsx("p", { className: "text-muted-foreground", children: "Admins only." }) });
  }
  return /* @__PURE__ */ jsxs(AdminShell, { title: "Users & Roles", children: [
    /* @__PURE__ */ jsxs("p", { className: "text-sm text-muted-foreground mb-4", children: [
      "New accounts default to ",
      /* @__PURE__ */ jsx("strong", { children: "citizen" }),
      ". Grant ",
      /* @__PURE__ */ jsx("strong", { children: "writer" }),
      ", ",
      /* @__PURE__ */ jsx("strong", { children: "editor" }),
      ", or ",
      /* @__PURE__ */ jsx("strong", { children: "admin" }),
      " to give newsroom access."
    ] }),
    /* @__PURE__ */ jsx("div", { className: "border rounded-sm bg-surface", children: /* @__PURE__ */ jsxs(Table, { children: [
      /* @__PURE__ */ jsx(TableHeader, { children: /* @__PURE__ */ jsxs(TableRow, { children: [
        /* @__PURE__ */ jsx(TableHead, { children: "User" }),
        /* @__PURE__ */ jsx(TableHead, { children: "Roles" }),
        /* @__PURE__ */ jsx(TableHead, { className: "text-right", children: "Actions" })
      ] }) }),
      /* @__PURE__ */ jsxs(TableBody, { children: [
        users.data?.map((u) => /* @__PURE__ */ jsxs(TableRow, { children: [
          /* @__PURE__ */ jsxs(TableCell, { children: [
            /* @__PURE__ */ jsx("div", { className: "font-bold", children: u.display_name || u.id.slice(0, 8) }),
            /* @__PURE__ */ jsx("div", { className: "text-xs text-muted-foreground", children: u.id })
          ] }),
          /* @__PURE__ */ jsx(TableCell, { children: /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap gap-1", children: [
            u.roles.map((r) => /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-1 bg-muted px-2 py-0.5 rounded-sm text-xs", children: [
              r,
              /* @__PURE__ */ jsx("button", { type: "button", onClick: () => setRemoveTarget({
                uid: u.id,
                role: r
              }), children: /* @__PURE__ */ jsx(Trash2, { className: "w-3 h-3" }) })
            ] }, r)),
            !u.roles.length && /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: "none" })
          ] }) }),
          /* @__PURE__ */ jsx(TableCell, { className: "text-right", children: /* @__PURE__ */ jsxs("div", { className: "flex gap-1 justify-end flex-wrap", children: [
            /* @__PURE__ */ jsx(Button, { variant: "ghost", size: "sm", onClick: () => setViewing(u), children: /* @__PURE__ */ jsx(Eye, { className: "w-4 h-4" }) }),
            u.id === currentUser?.id && /* @__PURE__ */ jsx(Button, { variant: "outline", size: "sm", onClick: () => setEditing(u), children: "Edit profile" }),
            ROLES.filter((r) => !u.roles.includes(r)).map((r) => /* @__PURE__ */ jsxs(Button, { size: "sm", variant: "outline", onClick: () => addRole.mutate({
              uid: u.id,
              role: r
            }), children: [
              /* @__PURE__ */ jsx(Plus, { className: "w-3 h-3 mr-1" }),
              " ",
              r
            ] }, r))
          ] }) })
        ] }, u.id)),
        !users.data?.length && /* @__PURE__ */ jsx(TableRow, { children: /* @__PURE__ */ jsx(TableCell, { colSpan: 3, className: "text-center text-muted-foreground py-12", children: "No users yet" }) })
      ] })
    ] }) }),
    /* @__PURE__ */ jsx(Dialog, { open: !!viewing, onOpenChange: (o) => !o && setViewing(null), children: /* @__PURE__ */ jsxs(DialogContent, { children: [
      /* @__PURE__ */ jsx(DialogHeader, { children: /* @__PURE__ */ jsx(DialogTitle, { children: "User details" }) }),
      viewing && /* @__PURE__ */ jsxs("dl", { className: "space-y-2 text-sm", children: [
        /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsx("dt", { className: "text-muted-foreground", children: "Display name" }),
          /* @__PURE__ */ jsx("dd", { className: "font-bold", children: viewing.display_name ?? "—" })
        ] }),
        /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsx("dt", { className: "text-muted-foreground", children: "User ID" }),
          /* @__PURE__ */ jsx("dd", { className: "font-mono text-xs break-all", children: viewing.id })
        ] }),
        /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsx("dt", { className: "text-muted-foreground", children: "Bio" }),
          /* @__PURE__ */ jsx("dd", { children: viewing.bio ?? "—" })
        ] }),
        /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsx("dt", { className: "text-muted-foreground", children: "Joined" }),
          /* @__PURE__ */ jsx("dd", { children: new Date(viewing.created_at).toLocaleString() })
        ] }),
        /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsx("dt", { className: "text-muted-foreground", children: "Roles" }),
          /* @__PURE__ */ jsx("dd", { children: viewing.roles.join(", ") || "none" })
        ] })
      ] })
    ] }) }),
    /* @__PURE__ */ jsx(Dialog, { open: !!editing, onOpenChange: (o) => !o && setEditing(null), children: /* @__PURE__ */ jsxs(DialogContent, { children: [
      /* @__PURE__ */ jsx(DialogHeader, { children: /* @__PURE__ */ jsx(DialogTitle, { children: "Edit your profile" }) }),
      editing && /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
        /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsx(Label, { children: "Display name" }),
          /* @__PURE__ */ jsx(Input, { value: editing.display_name ?? "", onChange: (e) => setEditing({
            ...editing,
            display_name: e.target.value
          }) })
        ] }),
        /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsx(Label, { children: "Bio" }),
          /* @__PURE__ */ jsx(Textarea, { rows: 3, value: editing.bio ?? "", onChange: (e) => setEditing({
            ...editing,
            bio: e.target.value
          }) })
        ] })
      ] }),
      /* @__PURE__ */ jsxs(DialogFooter, { children: [
        /* @__PURE__ */ jsx(Button, { variant: "outline", onClick: () => setEditing(null), children: "Cancel" }),
        /* @__PURE__ */ jsx(Button, { onClick: () => saveProfile.mutate(), disabled: saveProfile.isPending, children: "Save" })
      ] })
    ] }) }),
    /* @__PURE__ */ jsx(AlertDialog, { open: !!removeTarget, onOpenChange: (o) => !o && setRemoveTarget(null), children: /* @__PURE__ */ jsxs(AlertDialogContent, { children: [
      /* @__PURE__ */ jsxs(AlertDialogHeader, { children: [
        /* @__PURE__ */ jsx(AlertDialogTitle, { children: "Remove role?" }),
        /* @__PURE__ */ jsxs(AlertDialogDescription, { children: [
          "Remove the ",
          /* @__PURE__ */ jsx("strong", { children: removeTarget?.role }),
          " role from this user?"
        ] })
      ] }),
      /* @__PURE__ */ jsxs(AlertDialogFooter, { children: [
        /* @__PURE__ */ jsx(AlertDialogCancel, { children: "Cancel" }),
        /* @__PURE__ */ jsx(AlertDialogAction, { onClick: () => removeTarget && removeRole.mutate(removeTarget), children: "Remove" })
      ] })
    ] }) })
  ] });
}
export {
  UsersPage as component
};
