import { zodResolver } from "@hookform/resolvers/zod"; import { PenBoxIcon, Plus } from "lucide-react"; import { useEffect, useState } from "react"; import { useForm } from "react-hook-form"; import { toast } from "sonner"; import { z } from "zod"; import { Button } from "@/components/ui/button"; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger, } from "@/components/ui/dialog"; import { DropdownMenuItem } from "@/components/ui/dropdown-menu"; import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage, } from "@/components/ui/form"; import { Input } from "@/components/ui/input"; import { api } from "@/utils/api"; const organizationSchema = z.object({ name: z.string().min(1, { message: "Organization name is required", }), logo: z.string().optional(), }); type OrganizationFormValues = z.infer; interface Props { organizationId?: string; children?: React.ReactNode; } export function AddOrganization({ organizationId }: Props) { const [open, setOpen] = useState(false); const utils = api.useUtils(); const { data: organization } = api.organization.one.useQuery( { organizationId: organizationId ?? "", }, { enabled: !!organizationId, }, ); const { mutateAsync, isLoading } = organizationId ? api.organization.update.useMutation() : api.organization.create.useMutation(); const form = useForm({ resolver: zodResolver(organizationSchema), defaultValues: { name: "", logo: "", }, }); useEffect(() => { if (organization) { form.reset({ name: organization.name, logo: organization.logo || "", }); } }, [organization, form]); const onSubmit = async (values: OrganizationFormValues) => { await mutateAsync({ name: values.name, logo: values.logo, organizationId: organizationId ?? "", }) .then(() => { form.reset(); toast.success( `Organization ${organizationId ? "updated" : "created"} successfully`, ); utils.organization.all.invalidate(); setOpen(false); }) .catch((error) => { console.error(error); toast.error( `Failed to ${organizationId ? "update" : "create"} organization`, ); }); }; return ( {organizationId ? ( e.preventDefault()} > ) : ( e.preventDefault()} >
Add organization
)}
{organizationId ? "Update organization" : "Add organization"} {organizationId ? "Update the organization name and logo" : "Create a new organization to manage your projects."}
( Name )} /> ( Logo URL )} />
); }