📦 EqualifyEverything / equalify-dashboard

📄 account-form.tsx · 194 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194import { useEffect, useState } from 'react';
import { zodResolver } from '@hookform/resolvers/zod';
import { useForm, useWatch } from 'react-hook-form';
import { toast } from '~/components/alerts';
import { z } from 'zod';

import { Button } from '~/components/buttons';
import {
  Input,
} from '~/components/inputs';
import { useAuth } from '~/hooks/useAuth';
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '.';
import { useQuery } from '@tanstack/react-query';
import { getApikey } from '~/services';

const AccountSchema = z.object({
  firstName: z.string().min(1, 'First name is required'),
  lastName: z.string().min(1, 'Last name is required'),
  email: z.string().email('Please enter a valid email address'),
  selectedAccount: z.string(),
});

type AccountFormInputs = z.infer<typeof AccountSchema>;

const AccountForm = () => {
  const { user, updateUserAttributes, loading } = useAuth();
  const form = useForm<AccountFormInputs>({
    resolver: zodResolver(AccountSchema),
    defaultValues: {
      firstName: user?.firstName,
      lastName: user?.lastName,
      email: user?.email ?? '',
      selectedAccount: '',
    },
  });

  const { data: apikey } = useQuery({
    queryKey: ['apikey'],
    queryFn: () => getApikey(),
  })

  const [isFormChanged, setIsFormChanged] = useState(false);

  const watchedFields = useWatch({ control: form.control });

  useEffect(() => {
    const isChanged =
      (watchedFields.firstName?.trim() ?? '') !== (user?.firstName ?? '') ||
      (watchedFields.lastName?.trim() ?? '') !== (user?.lastName ?? '');
    setIsFormChanged(isChanged);
  }, [watchedFields, user]);

  const handleUpdateAccount = async (values: AccountFormInputs) => {
    try {
      await updateUserAttributes({
        firstName: values.firstName,
        lastName: values.lastName,
      });
      form.reset(values);
      toast.success({title:'Success', description:'Account updated successfully.'});
    } catch (error) {
      toast.error({title: 'Success', description:'Failed to update account'});
    }
  };

  const handleCancel = () => {
    form.reset({
      firstName: user?.firstName,
      lastName: user?.lastName,
      email: user?.email ?? '',
      selectedAccount: '',
    });
    setIsFormChanged(false);
  };

  return (
    <Form {...form}>
      <form
        onSubmit={form.handleSubmit(handleUpdateAccount)}
        className="grid grid-cols-1 gap-x-10 md:grid-cols-2"
      >
        <FormField
          control={form.control}
          name="firstName"
          render={({ field }) => (
            <FormItem>
              <FormLabel>First Name</FormLabel>
              <FormControl>
                <Input
                  type="text"
                  className="h-12 bg-white"
                  {...field}
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        <FormField
          control={form.control}
          name="lastName"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Last Name</FormLabel>
              <FormControl>
                <Input
                  type="text"
                  className="h-12 bg-white"
                  {...field}
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        <FormField
          control={form.control}
          name="email"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Email</FormLabel>
              <FormControl>
                <Input
                  type="email"
                  className="h-12 bg-white"
                  disabled
                  aria-readonly
                  {...field}
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        <FormField
          control={form.control}
          name="apikey"
          render={({ field }) => (
            <FormItem>
              <FormLabel>API Key</FormLabel>
              <FormControl>
                <input className='border-[1px] p-[11px] rounded-md' id='apikey' name='apikey' value={apikey?.apikey} disabled readOnly />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        <div className='flex space-x-4' />
        <div className="flex space-x-4">
          <Button
            type="submit"
            className="w-fit bg-[#1D781D] text-white"
            disabled={!isFormChanged}
            aria-disabled={!isFormChanged}
            aria-live="polite"
          >
            {loading ? (
              <>
                <span className="sr-only">Processing, please wait...</span>
                <div
                  role="status"
                  className="h-4 w-4 animate-spin rounded-full border-2 border-solid border-white border-t-transparent"
                ></div>
              </>
            ) : (
              'Update Account'
            )}
          </Button>

          {isFormChanged && (
            <Button
              type="button"
              variant={'outline'}
              className="w-fit"
              onClick={handleCancel}
            >
              Cancel
            </Button>
          )}
        </div>
      </form>
    </Form>
  );
};

export default AccountForm;