File size: 1,762 Bytes
689359a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | "use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { useTranslations } from "next-intl";
import { Button } from "@/components/ui/button";
interface AdminUserToggleProps {
userId: string;
isAdmin: boolean;
isCurrentUser: boolean;
}
export function AdminUserToggle({ userId, isAdmin, isCurrentUser }: AdminUserToggleProps) {
const t = useTranslations("admin");
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const router = useRouter();
const handleToggle = async () => {
if (isCurrentUser && isAdmin) {
return;
}
setError(null);
setIsLoading(true);
try {
const response = await fetch(`/api/admin/users/${userId}/admin`, {
method: "PATCH",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ is_admin: !isAdmin }),
});
if (!response.ok) {
const data = await response.json().catch(() => ({}));
throw new Error(data.error || t("users.updateFailed"));
}
router.refresh();
} catch (toggleError) {
setError(toggleError instanceof Error ? toggleError.message : t("users.updateFailed"));
} finally {
setIsLoading(false);
}
};
return (
<div className="flex items-center justify-end gap-2">
<Button
variant={isAdmin ? "outline" : "default"}
size="sm"
onClick={handleToggle}
disabled={isLoading || (isCurrentUser && isAdmin)}
>
{isLoading ? t("savingDots") : isAdmin ? t("users.removeAdmin") : t("users.makeAdmin")}
</Button>
{error && <span className="text-xs text-red-600">{error}</span>}
</div>
);
}
|