Skip to content

Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.

2.4 KB
Raw Blame
"use client";
import { zodResolver } from "@hookform/resolvers/zod";
import { mutationOptions } from "@next-safe-action/adapter-tanstack-query";
import { Button } from "@rallly/ui/button";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@rallly/ui/form";
import { Input } from "@rallly/ui/input";
import { useMutation } from "@tanstack/react-query";
import { useForm } from "react-hook-form";
import * as z from "zod";

import { updateUserNameAction } from "@/features/user/actions";
import { Trans } from "@/i18n/client";

import { ProfilePicture } from "./profile-picture";

const profileSettingsFormData = z.object({
  name: z.string().min(1).max(100),
});

export const ProfileSettings = ({
  name,
  image,
}: {
  name: string;
  image?: string;
}) => {
  const updateUserName = useMutation(mutationOptions(updateUserNameAction));
  const form = useForm({
    defaultValues: {
      name,
    },
    resolver: zodResolver(profileSettingsFormData),
  });

  const { control, handleSubmit, formState, reset } = form;
  return (
    <div className="grid gap-y-4">
      <Form {...form}>
        <form
          onSubmit={handleSubmit(async (data) => {
            if (data.name !== name) {
              try {
                await updateUserName.mutateAsync({ name: data.name });
              } catch {
                return;
              }
            }
            reset(data);
          })}
        >
          <div className="flex flex-col gap-y-4">
            <ProfilePicture name={name} image={image} />
            <FormField
              control={control}
              name="name"
              render={({ field }) => (
                <FormItem>
                  <FormLabel htmlFor="name">
                    <Trans i18nKey="name" />
                  </FormLabel>
                  <FormControl>
                    <Input id="name" autoComplete="name" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <div className="mt-4 flex">
              <Button
                loading={formState.isSubmitting}
                type="submit"
                disabled={!formState.isDirty}
              >
                <Trans i18nKey="save" />
              </Button>
            </div>
          </div>
        </form>
      </Form>
    </div>
  );
};