import { r as reactExports, U as jsxRuntimeExports } from "./worker-entry-DSg7Z9cD.js";
import { c as createLucideIcon, u as useAuth, a as useNavigate, L as Link, B as Button, X, s as supabase, t as toast } from "./router-CNfq_WjB.js";
import { u as useIsAdmin } from "./useIsAdmin-Di1gULMM.js";
import { I as Input } from "./input-CCsXbGDd.js";
import { C as Card } from "./card-ItD3O6C2.js";
import { A as ArrowLeft } from "./arrow-left-CSW_t4oE.js";
import { S as Save } from "./save-aCyIokqt.js";
import { T as Trash2 } from "./trash-2-BomqsDeC.js";
import "node:events";
import "node:async_hooks";
import "node:stream/web";
import "node:stream";
const __iconNode$5 = [
  ["path", { d: "M8 2v4", key: "1cmpym" }],
  ["path", { d: "M16 2v4", key: "4m81vk" }],
  ["rect", { width: "18", height: "18", x: "3", y: "4", rx: "2", key: "1hopcy" }],
  ["path", { d: "M3 10h18", key: "8toen8" }]
];
const Calendar = createLucideIcon("calendar", __iconNode$5);
const __iconNode$4 = [
  ["path", { d: "m22 7-8.991 5.727a2 2 0 0 1-2.009 0L2 7", key: "132q7q" }],
  ["rect", { x: "2", y: "4", width: "20", height: "16", rx: "2", key: "izxlao" }]
];
const Mail = createLucideIcon("mail", __iconNode$4);
const __iconNode$3 = [
  ["path", { d: "m21 21-4.34-4.34", key: "14j7rj" }],
  ["circle", { cx: "11", cy: "11", r: "8", key: "4ej97u" }]
];
const Search = createLucideIcon("search", __iconNode$3);
const __iconNode$2 = [
  ["path", { d: "m2 2 20 20", key: "1ooewy" }],
  [
    "path",
    {
      d: "M5 5a1 1 0 0 0-1 1v7c0 5 3.5 7.5 7.67 8.94a1 1 0 0 0 .67.01c2.35-.82 4.48-1.97 5.9-3.71",
      key: "1jlk70"
    }
  ],
  [
    "path",
    {
      d: "M9.309 3.652A12.252 12.252 0 0 0 11.24 2.28a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1v7a9.784 9.784 0 0 1-.08 1.264",
      key: "18rp1v"
    }
  ]
];
const ShieldOff = createLucideIcon("shield-off", __iconNode$2);
const __iconNode$1 = [
  [
    "path",
    {
      d: "M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",
      key: "oel41y"
    }
  ]
];
const Shield = createLucideIcon("shield", __iconNode$1);
const __iconNode = [
  ["path", { d: "M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2", key: "1yyitq" }],
  ["circle", { cx: "9", cy: "7", r: "4", key: "nufk8" }],
  ["line", { x1: "19", x2: "19", y1: "8", y2: "14", key: "1bvyxn" }],
  ["line", { x1: "22", x2: "16", y1: "11", y2: "11", key: "1shjgl" }]
];
const UserPlus = createLucideIcon("user-plus", __iconNode);
function AdminUsersPage() {
  const {
    user
  } = useAuth();
  const isAdmin = useIsAdmin();
  const navigate = useNavigate();
  const [items, setItems] = reactExports.useState([]);
  const [loading, setLoading] = reactExports.useState(true);
  const [email, setEmail] = reactExports.useState("");
  const [name, setName] = reactExports.useState("");
  const [busy, setBusy] = reactExports.useState(false);
  const [editId, setEditId] = reactExports.useState(null);
  const [editName, setEditName] = reactExports.useState("");
  const [search, setSearch] = reactExports.useState("");
  reactExports.useEffect(() => {
    if (isAdmin === false) navigate({
      to: "/app"
    });
  }, [isAdmin, navigate]);
  const load = async () => {
    setLoading(true);
    const {
      data,
      error
    } = await supabase.functions.invoke("admin-users", {
      body: {
        action: "list"
      }
    });
    setLoading(false);
    if (error) return toast.error(error.message);
    if (data?.error) return toast.error(data.error);
    setItems(data?.users ?? []);
  };
  reactExports.useEffect(() => {
    if (user && isAdmin) load();
  }, [user, isAdmin]);
  const create = async (e) => {
    e.preventDefault();
    setBusy(true);
    const {
      data,
      error
    } = await supabase.functions.invoke("admin-create-user", {
      body: {
        email: email.trim().toLowerCase(),
        displayName: name.trim() || null
      }
    });
    setBusy(false);
    if (error) return toast.error(error.message);
    if (data?.error) return toast.error(data.error);
    if (data?.warning) toast.warning(data.warning);
    else toast.success("Compte créé et email envoyé");
    setEmail("");
    setName("");
    load();
  };
  const saveProfile = async (id) => {
    const {
      data,
      error
    } = await supabase.functions.invoke("admin-users", {
      body: {
        action: "updateProfile",
        userId: id,
        displayName: editName
      }
    });
    if (error || data?.error) return toast.error(error?.message ?? data?.error);
    toast.success("Profil mis à jour");
    setEditId(null);
    load();
  };
  const removeUser = async (u) => {
    if (!confirm(`Supprimer définitivement ${u.email} ?`)) return;
    const {
      data,
      error
    } = await supabase.functions.invoke("admin-users", {
      body: {
        action: "delete",
        userId: u.id
      }
    });
    if (error || data?.error) return toast.error(error?.message ?? data?.error);
    toast.success("Utilisateur supprimé");
    load();
  };
  const toggleRole = async (u) => {
    const newRole = u.role === "admin" ? "user" : "admin";
    const {
      data,
      error
    } = await supabase.functions.invoke("admin-users", {
      body: {
        action: "setRole",
        userId: u.id,
        role: newRole
      }
    });
    if (error || data?.error) return toast.error(error?.message ?? data?.error);
    toast.success(`Rôle changé en ${newRole}`);
    load();
  };
  const filtered = items.filter((u) => {
    const q = search.trim().toLowerCase();
    if (!q) return true;
    return u.email?.toLowerCase().includes(q) || (u.display_name ?? "").toLowerCase().includes(q);
  });
  const fmt = (d) => d ? new Date(d).toLocaleDateString("fr-FR", {
    day: "2-digit",
    month: "short",
    year: "numeric"
  }) : "—";
  if (isAdmin === null) return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "p-10 text-muted-foreground", children: "Chargement…" });
  if (!isAdmin) return null;
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mx-auto max-w-6xl p-6 md:p-10", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs(Link, { to: "/app", className: "mb-4 inline-flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(ArrowLeft, { className: "h-4 w-4" }),
      " Retour"
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("h1", { className: "mb-1 text-3xl font-bold", children: "Utilisateurs" }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mb-8 text-sm text-muted-foreground", children: "Créez et gérez les comptes des collègues." }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { className: "mb-6 p-5", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: "mb-3 font-semibold", children: "Créer un nouvel utilisateur" }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("form", { onSubmit: create, className: "grid gap-3 md:grid-cols-[1fr_1fr_auto]", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(Input, { type: "email", placeholder: "email@exemple.com", required: true, value: email, onChange: (e) => setEmail(e.target.value) }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(Input, { placeholder: "Nom complet", value: name, onChange: (e) => setName(e.target.value) }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Button, { type: "submit", disabled: busy, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(UserPlus, { className: "h-4 w-4" }),
          " ",
          busy ? "..." : "Créer & envoyer"
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "mt-2 text-xs text-muted-foreground", children: "Un mot de passe sera généré et envoyé par email à l'utilisateur." })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "mb-4 flex items-center justify-between gap-3", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("h2", { className: "text-lg font-semibold", children: [
        "Liste (",
        filtered.length,
        ")"
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "relative w-full max-w-xs", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(Search, { className: "absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(Input, { placeholder: "Rechercher…", className: "pl-8", value: search, onChange: (e) => setSearch(e.target.value) })
      ] })
    ] }),
    loading ? /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "text-muted-foreground", children: "Chargement…" }) : filtered.length === 0 ? /* @__PURE__ */ jsxRuntimeExports.jsx(Card, { className: "p-10 text-center text-muted-foreground", children: "Aucun utilisateur trouvé." }) : /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid gap-4 sm:grid-cols-2 lg:grid-cols-3", children: filtered.map((u) => {
      const initial = (u.display_name ?? u.email ?? "?").trim().charAt(0).toUpperCase();
      const isSelf = u.id === user?.id;
      return /* @__PURE__ */ jsxRuntimeExports.jsxs(Card, { className: "flex flex-col gap-3 p-5", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-start gap-3", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex h-11 w-11 shrink-0 items-center justify-center rounded-full bg-primary/10 text-lg font-semibold text-primary", children: initial }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "min-w-0 flex-1", children: [
            editId === u.id ? /* @__PURE__ */ jsxRuntimeExports.jsx(Input, { value: editName, onChange: (e) => setEditName(e.target.value), className: "h-8", autoFocus: true }) : /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "truncate font-semibold", children: u.display_name ?? "(sans nom)" }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-1 truncate text-xs text-muted-foreground", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Mail, { className: "h-3 w-3 shrink-0" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "truncate", children: u.email })
            ] })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: `rounded-full px-2 py-0.5 text-xs font-medium ${u.role === "admin" ? "bg-primary/10 text-primary" : "bg-muted text-muted-foreground"}`, children: u.role === "admin" ? "Admin" : "Utilisateur" })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "space-y-1 text-xs text-muted-foreground", children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-1.5", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(Calendar, { className: "h-3 w-3" }),
            " Créé le ",
            fmt(u.created_at)
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-1.5", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(Calendar, { className: "h-3 w-3" }),
            " Dernière connexion : ",
            fmt(u.last_sign_in_at)
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "mt-auto flex flex-wrap gap-2 border-t pt-3", children: editId === u.id ? /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs(Button, { size: "sm", onClick: () => saveProfile(u.id), children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(Save, { className: "h-3.5 w-3.5" }),
            " Enregistrer"
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(Button, { size: "sm", variant: "ghost", onClick: () => setEditId(null), children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(X, { className: "h-3.5 w-3.5" }),
            " Annuler"
          ] })
        ] }) : /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Button, { size: "sm", variant: "outline", onClick: () => {
            setEditId(u.id);
            setEditName(u.display_name ?? "");
          }, children: "Modifier" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(Button, { size: "sm", variant: "outline", onClick: () => toggleRole(u), disabled: isSelf, title: isSelf ? "Vous ne pouvez pas changer votre propre rôle" : "", children: u.role === "admin" ? /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(ShieldOff, { className: "h-3.5 w-3.5" }),
            " Retirer admin"
          ] }) : /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(Shield, { className: "h-3.5 w-3.5" }),
            " Promouvoir admin"
          ] }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(Button, { size: "sm", variant: "ghost", className: "ml-auto text-destructive hover:bg-destructive/10 hover:text-destructive", onClick: () => removeUser(u), disabled: isSelf, children: /* @__PURE__ */ jsxRuntimeExports.jsx(Trash2, { className: "h-3.5 w-3.5" }) })
        ] }) })
      ] }, u.id);
    }) })
  ] });
}
export {
  AdminUsersPage as component
};
