import { zodResolver } from '@hookform/resolvers/zod' import { groupBy } from 'lodash' import { SubmitHandler, useForm } from 'react-hook-form' import { toast } from 'sonner' import { Button, Card, CardContent, CardFooter, Form, FormControl, FormField, Input, Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from 'ui' import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout' import { PageSection, PageSectionContent, PageSectionMeta, PageSectionSummary, PageSectionTitle, } from 'ui-patterns/PageSection' import z from 'zod' import { useProfileIdentitiesQuery } from '@/data/profile/profile-identities-query' import { useProfileUpdateMutation } from '@/data/profile/profile-update-mutation' import { useProfile } from '@/lib/profile' const FormSchema = z.object({ first_name: z.string().optional(), last_name: z.string().optional(), username: z.string().optional(), primary_email: z.string().email().optional(), }) const formId = 'profile-information-form' export const ProfileInformation = () => { const { profile } = useProfile() const { data: identityData, isPending: isIdentitiesLoading, isSuccess: isIdentitiesSuccess, } = useProfileIdentitiesQuery() const identities = (identityData?.identities ?? []).filter((x) => x.identity_data?.email !== null) const dedupedIdentityEmails = Object.keys(groupBy(identities, 'identity_data.email')) const defaultValues = { first_name: profile?.first_name ?? '', last_name: profile?.last_name ?? '', username: profile?.username ?? '', primary_email: profile?.primary_email ?? '', } const form = useForm({ resolver: zodResolver(FormSchema as any), defaultValues, values: defaultValues, }) const { mutate: updateProfile, isPending: isUpdatingProfile } = useProfileUpdateMutation({ onSuccess: (data) => { toast.success('Successfully saved profile') const { first_name, last_name, username, primary_email } = data form.reset({ first_name: first_name ?? undefined, last_name: last_name ?? undefined, username, primary_email, }) }, onError: (error) => toast.error(`Failed to update profile: ${error.message}`), }) const onSubmit: SubmitHandler> = async (data) => { updateProfile({ firstName: data.first_name || '', lastName: data.last_name || '', username: data.username || '', primaryEmail: data.primary_email || '', }) } return ( Profile information
( )} /> ( )} /> (
)} />
(
)} />
{form.formState.isDirty && ( )}
) }