import { zodResolver } from '@hookform/resolvers/zod' import { PermissionAction } from '@supabase/shared-types/out/constants' import { useQueryClient } from '@tanstack/react-query' import { useParams } from 'common' import { useEffect } from 'react' import { useForm } from 'react-hook-form' import { toast } from 'sonner' import { Card, CardContent, CardFooter, Form, FormControl, FormField, Input } from 'ui' import { Input as PasswordInput } from 'ui-patterns/DataInputs/Input' import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout' import * as z from 'zod' import { FormActions } from '@/components/ui/Forms/FormActions' import { useOrganizationUpdateMutation } from '@/data/organizations/organization-update-mutation' import { invalidateOrganizationsQuery } from '@/data/organizations/organizations-query' import { useAsyncCheckPermissions } from '@/hooks/misc/useCheckPermissions' import { useSelectedOrganizationQuery } from '@/hooks/misc/useSelectedOrganization' import type { ResponseError } from '@/types' const OrgDetailsSchema = z.object({ name: z.string().min(1, 'Organization name is required'), }) export const OrganizationDetailsForm = () => { const { slug } = useParams() const queryClient = useQueryClient() const { data: selectedOrganization } = useSelectedOrganizationQuery() const { can: canUpdateOrganization } = useAsyncCheckPermissions( PermissionAction.UPDATE, 'organizations' ) const { mutate: updateOrganization, isPending: isUpdatingDetails } = useOrganizationUpdateMutation() const orgDetailsForm = useForm>({ resolver: zodResolver(OrgDetailsSchema as any), defaultValues: { name: selectedOrganization?.name ?? '' }, }) const onUpdateOrganizationDetails = async (values: z.infer) => { if (!canUpdateOrganization) { return toast.error('You do not have the required permissions to update this organization') } if (!slug) return console.error('Slug is required') updateOrganization( { slug, name: values.name }, { onSuccess: () => { invalidateOrganizationsQuery(queryClient) toast.success('Successfully updated organization name') }, onError: (error: ResponseError) => { toast.error(`Failed to update organization name: ${error.message}`) }, } ) } const permissionsHelperText = !canUpdateOrganization ? "You need additional permissions to manage this organization's settings" : undefined useEffect(() => { if (selectedOrganization && !isUpdatingDetails) { orgDetailsForm.reset({ name: selectedOrganization.name ?? '' }) } }, [selectedOrganization, orgDetailsForm, isUpdatingDetails]) return (
( )} /> orgDetailsForm.reset()} helper={permissionsHelperText} disabled={!canUpdateOrganization} />
) }