"use client"; import { useState } from "react"; import { useRouter } from "next/navigation"; import { useForm } from "react-hook-form"; import { zodResolver } from "@hookform/resolvers/zod"; import { z } from "zod"; import { Loader2, Send } from "lucide-react"; import { toast } from "sonner"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage, } from "@/components/ui/form"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select"; const formSchema = z.object({ email: z.string().email("Invalid email address"), name: z.string().optional(), role: z.enum(["admin", "user"]), }); type FormData = z.infer; export function InviteUserForm() { const router = useRouter(); const [isLoading, setIsLoading] = useState(false); const form = useForm({ resolver: zodResolver(formSchema), defaultValues: { email: "", name: "", role: "user", }, }); async function onSubmit(data: FormData) { setIsLoading(true); try { const response = await fetch("/api/admin/users/invite", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data), }); if (!response.ok) { const result = await response.json(); throw new Error(result.error || "Failed to send invitation"); } toast.success("Invitation sent successfully"); router.push("/admin/users"); } catch (error) { toast.error(error instanceof Error ? error.message : "An error occurred"); } finally { setIsLoading(false); } } return (
( Email Address An invitation email will be sent to this address )} /> ( Name (Optional) If not provided, the email prefix will be used )} /> ( Role The role determines what the user can access )} />
); }