import { useMemo, useState, type FormEvent } from "react"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { Navigate } from "react-router-dom"; import { useAuth } from "../auth/AuthContext"; import { useI18n } from "../i18n"; import { useToast } from "../hooks/useToast"; import { apiGet, apiPatch, apiPost } from "../services/api"; type UserRow = { id: string; username: string; role: string; is_active: boolean; created_at?: string | null; }; export function UsersPage() { const { t } = useI18n(); const { isAdmin, ready } = useAuth(); const { showOk, showError } = useToast(); const qc = useQueryClient(); const [username, setUsername] = useState(""); const [password, setPassword] = useState(""); const [role, setRole] = useState("user"); const [resetPwd, setResetPwd] = useState>({}); const usersQuery = useQuery({ queryKey: ["appUsers"], queryFn: () => apiGet<{ items: UserRow[] }>("/v1/users"), enabled: ready && isAdmin, }); const createMut = useMutation({ mutationFn: () => apiPost("/v1/users", { username, password, role }), onSuccess: async () => { setUsername(""); setPassword(""); setRole("user"); showOk(t("auth.userCreated")); await qc.invalidateQueries({ queryKey: ["appUsers"] }); }, onError: (e) => showError(String(e instanceof Error ? e.message : e)), }); const patchMut = useMutation({ mutationFn: (payload: { id: string; body: Record }) => apiPatch(`/v1/users/${encodeURIComponent(payload.id)}`, payload.body), onSuccess: async () => { showOk(t("auth.userUpdated")); await qc.invalidateQueries({ queryKey: ["appUsers"] }); }, onError: (e) => showError(String(e instanceof Error ? e.message : e)), }); const items = useMemo(() => usersQuery.data?.items || [], [usersQuery.data]); if (ready && !isAdmin) return ; const onCreate = (e: FormEvent) => { e.preventDefault(); createMut.mutate(); }; return (

{t("auth.usersTitle")}

{t("auth.usersHint")}

setUsername(e.target.value)} required /> setPassword(e.target.value)} required minLength={6} />
{usersQuery.isLoading ?

{t("common.refreshing")}

: null} {!items.length && !usersQuery.isLoading ? (

{t("common.empty")}

) : (
{items.map((u) => ( ))}
{t("auth.username")} {t("auth.role")} {t("auth.status")} {t("auth.actions")}
{u.username} {u.role === "admin" ? t("auth.roleAdmin") : t("auth.roleUser")} {u.is_active ? t("auth.active") : t("auth.disabled")}
setResetPwd((m) => ({ ...m, [u.id]: e.target.value })) } style={{ width: 140, minWidth: 140, flex: "0 0 auto" }} />
)}
); }