"use client"; import { Dispatch, SetStateAction, useTransition } from "react"; import { zodResolver } from "@hookform/resolvers/zod"; import { User, UserRole } from "@prisma/client"; import { useForm } from "react-hook-form"; import { toast } from "sonner"; import { ROLE_ENUM } from "@/lib/enums"; import { updateUserSchema } from "@/lib/validations/auth"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Icons } from "@/components/shared/icons"; import { FormSectionColumns } from "../dashboard/form-section-columns"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "../ui/select"; import { Switch } from "../ui/switch"; export type FormData = User; export type FormType = "edit"; export interface RecordFormProps { user: Pick; isShowForm: boolean; setShowForm: Dispatch>; type: FormType; initData?: User | null; onRefresh: () => void; } export function UserForm({ setShowForm, type, initData, onRefresh, }: RecordFormProps) { const [isPending, startTransition] = useTransition(); const [isDeleting, startDeleteTransition] = useTransition(); const { handleSubmit, register, formState: { errors }, getValues, setValue, } = useForm({ resolver: zodResolver(updateUserSchema), defaultValues: { id: initData?.id || "", name: initData?.name || "", active: initData?.active || 1, email: initData?.email || "", image: initData?.image || "", role: initData?.role || "USER", team: initData?.team || "free", }, }); const onSubmit = handleSubmit((data) => { if (type === "edit") { handleUpdate(data); } }); const handleUpdate = async (data: User) => { startTransition(async () => { if (type === "edit") { const response = await fetch("/api/user/admin/update", { method: "POST", body: JSON.stringify({ id: initData?.id, data }), }); if (!response.ok || response.status !== 200) { toast.error("Update Failed", { description: response.statusText, }); } else { toast.success(`Update successfully!`); setShowForm(false); onRefresh(); } } }); }; const handleDelete = async () => { if (type === "edit") { startDeleteTransition(async () => { const response = await fetch("/api/user/admin/delete", { method: "POST", body: JSON.stringify({ id: initData?.id }), }); if (!response.ok || response.status !== 200) { toast.error("Delete Failed", { description: response.statusText, }); } else { toast.success(`Success`); setShowForm(false); onRefresh(); } }); } }; return (
Edit User
{errors?.email && (

{errors.email.message}

)}
{errors?.name && (

{errors.name.message}

)}
setValue("active", value ? 1 : 0)} />
{/* Action buttons */}
{type === "edit" && ( )}
); }