"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(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 (
{error && {error}}
); }