summaryrefslogtreecommitdiff
path: root/client/src/components/RsvpForm.tsx
blob: d9810538d925f8d6423f2fbbd125ff41129b05bd (plain)
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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
import React from 'react';
import { useRef } from 'react';
import { useNavigate, useOutletContext } from 'react-router-dom';
import {
  Alert,
  Button,
  Container,
  FormControl,
  FormControlLabel,
  FormLabel,
  Grid,
  Radio,
  RadioGroup,
  TextField,
} from '@mui/material';
import { useForm, Controller, useFieldArray } from 'react-hook-form';
import { useUpdateGuestMutation } from '../slices/apiSlice';
import type { Guest } from '../slices/apiSlice';

function RsvpForm() {
  const [updateGuest, { isSuccess: success, isError: error }] =
    useUpdateGuestMutation();
  const guest: Guest = useOutletContext();
  const previousPartySize = useRef(guest?.partySize - 1);
  const navigate = useNavigate();

  const {
    register,
    handleSubmit,
    control,
    watch,
    formState: { errors },
  } = useForm<Guest>({
    defaultValues: {
      id: guest?.id,
      firstName: guest?.firstName,
      lastName: guest?.lastName,
      attendance: guest?.attendance,
      email: guest?.email,
      message: guest?.message,
      partySize: guest?.partySize,
      partyList: guest?.partyList,
    },
  });

  const onSubmit = async (data: Guest) => {
    updateGuest({ ...data });
  };

  const { fields, append, remove } = useFieldArray({
    control,
    name: 'partyList',
  });

  const handleParty = () => {
    const partySize = Number(watch('partySize')) - 1;
    if (
      partySize > previousPartySize.current &&
      partySize > 0 &&
      partySize < 10
    ) {
      append(
        new Array(partySize - previousPartySize.current).fill({
          firstName: '',
          lastName: '',
        })
      );
      previousPartySize.current = partySize;
    } else if (partySize < previousPartySize.current && partySize >= 0) {
      remove(
        [...Array(previousPartySize.current - partySize).keys()].map(
          (_, i) => partySize - 1 + i
        )
      );
      previousPartySize.current = partySize;
    }
  };

  return (
    <Container
      component="form"
      maxWidth="sm"
      noValidate
      onSubmit={handleSubmit(onSubmit)}
    >
      <Grid container spacing={2} sx={{ mt: 8 }}>
        <Grid item xs={12}>
          <p>
            Please RSVP for the wedding by March 10, 2025. The ceremony will
            commence at 3 PM on April 26 in Divine Shepherd. The reception will
            follow at 5 PM in A Venue on the Ridge.
          </p>
        </Grid>
        <Grid item xs={12}>
          <div style={{ display: 'flex', justifyContent: 'center' }}>
            <FormControl>
              <div style={{ display: 'flex', alignItems: 'center' }}>
                <FormLabel sx={{ mr: 2 }} error={!!errors.attendance} required>
                  Attendance
                </FormLabel>
                <Controller
                  name="attendance"
                  control={control}
                  rules={{ required: true }}
                  render={({ field }) => (
                    <RadioGroup {...field} row>
                      <FormControlLabel
                        value="accept"
                        control={<Radio />}
                        label="Accept"
                      />
                      <FormControlLabel
                        value="decline"
                        control={<Radio />}
                        label="Decline"
                      />
                    </RadioGroup>
                  )}
                />
              </div>
            </FormControl>
          </div>
        </Grid>
        <Grid item xs={8}>
          <TextField
            label="Email"
            type="email"
            variant="outlined"
            fullWidth
            error={!!errors.email}
            helperText={errors.email?.message}
            required
            {...register('email', {
              required: 'This field is required',
              pattern: {
                value: /\S+@\S+\.\S+/,
                message: 'Please enter a valid email address',
              },
            })}
          />
        </Grid>
        <Grid item xs={4}>
          <TextField
            label="Party Size"
            type="number"
            variant="outlined"
            fullWidth
            onWheel={(event) => {
              event.currentTarget.blur();
            }}
            error={!!errors.partySize}
            helperText={errors.partySize?.message}
            required
            {...register('partySize', {
              valueAsNumber: true,
              onChange: handleParty,
              required: 'This field is required',
              min: { value: 1, message: 'Please enter a positive integer' },
              max: {
                value: 9,
                message: 'Please enter an integer less than 10',
              },
            })}
          />
        </Grid>
        <Grid item xs={12}>
          <TextField
            label="Message to the couple"
            variant="outlined"
            fullWidth
            multiline
            rows={3}
            {...register('message')}
          />
        </Grid>
        {fields.map((field, index) => {
          return (
            <Grid
              container
              item
              columnSpacing={2}
              rowSpacing={{ xs: 1 }}
              key={field.id}
            >
              <Grid item xs={6}>
                <TextField
                  label="First Name"
                  variant="outlined"
                  fullWidth
                  error={!!errors.partyList?.[index]?.firstName}
                  helperText={errors.partyList?.[index]?.firstName?.message}
                  required
                  {...register(`partyList.${index}.firstName`, {
                    required: 'This field is required',
                  })}
                />
              </Grid>
              <Grid item xs={6}>
                <TextField
                  label="Last Name"
                  variant="outlined"
                  fullWidth
                  error={!!errors.partyList?.[index]?.lastName}
                  helperText={errors.partyList?.[index]?.lastName?.message}
                  required
                  {...register(`partyList.${index}.lastName`, {
                    required: 'This field is required',
                  })}
                />
              </Grid>
            </Grid>
          );
        })}
        <Grid item xs={12}>
          <div
            style={{
              display: 'flex',
              flexDirection: 'column',
              alignItems: 'center',
            }}
          >
            <Button type="submit" variant="contained">
              RSVP
            </Button>
          </div>
          <div
            style={{ marginTop: 16, display: 'flex', justifyContent: 'center' }}
          >
            <div style={{ width: 180 }}>
              {success && <Alert severity="success">RSVP updated</Alert>}
              {error && <Alert severity="error">RSVP failed</Alert>}
            </div>
          </div>
        </Grid>
      </Grid>
    </Container>
  );
}

export default RsvpForm;