Use HOC for login and register components

1. Before, login and register UI shared the same route and used the same parent component, which was under an inaccurate name.
Now, the login and register have their dedicated routes and utilize the HOC to abstract the common logics and UI for better maintain
2. Gave the files more descriptive names

Change-Id: Ibbc4a74a9c0515b6fff8dcab426ee538183e99ad
diff --git a/client/src/pages/Registration.tsx b/client/src/pages/Registration.tsx
new file mode 100644
index 0000000..acbf8f9
--- /dev/null
+++ b/client/src/pages/Registration.tsx
@@ -0,0 +1,251 @@
+/*
+ * Copyright (C) 2022 Savoir-faire Linux Inc.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation; either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public
+ * License along with this program.  If not, see
+ * <https://www.gnu.org/licenses/>.
+ */
+import {
+  Box,
+  Button,
+  FormControl,
+  FormControlLabel,
+  Radio,
+  RadioGroup,
+  Stack,
+  Typography,
+  useMediaQuery,
+} from '@mui/material';
+import { Theme, useTheme } from '@mui/material/styles';
+import { ChangeEvent, FormEvent, ReactNode, useEffect, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Form, Link, useNavigate } from 'react-router-dom';
+
+import { AlertSnackbar } from '../components/AlertSnackbar';
+import { NameStatus, PasswordInput, PasswordStatus, UsernameInput } from '../components/Input';
+import ProcessingRequest from '../components/ProcessingRequest';
+import withAuthUI from '../components/WithAuthUI';
+import { checkPasswordStrength, isNameRegistered, loginUser, registerUser, setAccessToken } from '../utils/auth';
+import { inputWidth, jamiUsernamePattern } from '../utils/constants';
+import { InvalidCredentials, InvalidPassword, UsernameNotFound } from '../utils/errors';
+
+function RegistrationForm() {
+  const theme: Theme = useTheme();
+  const navigate = useNavigate();
+  const { t } = useTranslation();
+
+  const [isCreatingUser, setIsCreatingUser] = useState(false);
+
+  const [username, setUsername] = useState('');
+  const [password, setPassword] = useState('');
+  const [isJams, setIsJams] = useState(false);
+
+  const [usernameStatus, setUsernameStatus] = useState<NameStatus>('default');
+  const [passwordStatus, setPasswordStatus] = useState<PasswordStatus>('default');
+
+  const [errorAlertContent, setErrorAlertContent] = useState<ReactNode>(undefined);
+  const [successAlertContent, setSuccessAlertContent] = useState<ReactNode>(undefined);
+
+  const usernameError = usernameStatus !== 'success' && usernameStatus !== 'default';
+  const usernameSuccess = usernameStatus === 'success';
+  const passwordError = passwordStatus !== 'strong' && passwordStatus !== 'default';
+  const passwordSuccess = passwordStatus === 'strong';
+
+  useEffect(() => {
+    // To prevent lookup if field is empty, in error state or lookup already done
+    if (username.length > 0 && usernameStatus === 'default') {
+      const validateUsername = async () => {
+        if (await isNameRegistered(username)) {
+          setUsernameStatus('taken');
+        } else {
+          setUsernameStatus('success');
+        }
+      };
+      const timeout = setTimeout(validateUsername, 1000);
+
+      return () => clearTimeout(timeout);
+    }
+  }, [username, usernameStatus]);
+
+  const firstUserLogin = async () => {
+    try {
+      const accessToken = await loginUser(username, password, isJams);
+      setAccessToken(accessToken);
+      navigate('/conversation', { replace: true });
+    } catch (e) {
+      setIsCreatingUser(false);
+      if (e instanceof UsernameNotFound) {
+        setErrorAlertContent(t('login_username_not_found'));
+      } else if (e instanceof InvalidPassword) {
+        setErrorAlertContent(t('login_invalid_password'));
+      } else {
+        throw e;
+      }
+    }
+  };
+
+  const createAccount = async () => {
+    try {
+      await registerUser(username, password, isJams);
+      setSuccessAlertContent(t('registration_success'));
+      await firstUserLogin();
+    } catch (e) {
+      setIsCreatingUser(false);
+      if (e instanceof UsernameNotFound) {
+        setErrorAlertContent(t('login_username_not_found'));
+      } else if (e instanceof InvalidPassword) {
+        setErrorAlertContent(t('login_invalid_password'));
+      } else if (e instanceof InvalidCredentials) {
+        setErrorAlertContent(t('login_invalid_credentials'));
+      } else {
+        throw e;
+      }
+    }
+  };
+
+  const handleUsername = async (event: ChangeEvent<HTMLInputElement>) => {
+    const usernameValue: string = event.target.value;
+    setUsername(usernameValue);
+
+    if (usernameValue.length > 0 && !jamiUsernamePattern.test(usernameValue)) {
+      setUsernameStatus('invalid');
+    } else {
+      setUsernameStatus('default');
+    }
+  };
+
+  const handlePassword = (event: ChangeEvent<HTMLInputElement>) => {
+    const passwordValue: string = event.target.value;
+    setPassword(passwordValue);
+
+    if (passwordValue.length > 0) {
+      const checkResult = checkPasswordStrength(passwordValue);
+      setPasswordStatus(checkResult.valueCode);
+    } else {
+      setPasswordStatus('default');
+    }
+  };
+
+  const handleIsJams = (event: ChangeEvent<HTMLInputElement>) => {
+    setIsJams(event.target.value === 'true');
+  };
+
+  const handleSubmit = async (event: FormEvent) => {
+    event.preventDefault();
+    const canCreate = usernameSuccess && passwordSuccess;
+
+    if (canCreate) {
+      setIsCreatingUser(true);
+      await createAccount();
+    } else {
+      if (usernameError || username.length === 0) {
+        setUsernameStatus('registration_failed');
+      }
+      if (!passwordSuccess) {
+        setPasswordStatus('registration_failed');
+      }
+    }
+  };
+
+  const isMobile: boolean = useMediaQuery(theme.breakpoints.only('xs'));
+
+  return (
+    <>
+      <ProcessingRequest open={isCreatingUser} />
+
+      <AlertSnackbar
+        severity={'success'}
+        open={!!successAlertContent}
+        onClose={() => setSuccessAlertContent(undefined)}
+      >
+        {successAlertContent}
+      </AlertSnackbar>
+
+      <AlertSnackbar severity={'error'} open={!!errorAlertContent} onClose={() => setErrorAlertContent(undefined)}>
+        {errorAlertContent}
+      </AlertSnackbar>
+
+      <Stack
+        sx={{
+          minHeight: `${isMobile ? 'auto' : '100%'}`,
+          display: 'flex',
+          alignItems: 'center',
+          justifyContent: 'center',
+        }}
+      >
+        <Box sx={{ mt: theme.typography.pxToRem(50), mb: theme.typography.pxToRem(20) }}>
+          <Typography component={'span'} variant="h2">
+            {t('registration_form_title')}
+          </Typography>
+        </Box>
+
+        <Form method="post" id="register-form">
+          <div>
+            <UsernameInput
+              value={username}
+              onChange={handleUsername}
+              error={usernameError}
+              success={usernameSuccess}
+              status={usernameStatus}
+              sx={{ width: theme.typography.pxToRem(inputWidth) }}
+              tooltipTitle={t('registration_form_username_tooltip')}
+            />
+          </div>
+          <div>
+            <PasswordInput
+              value={password}
+              onChange={handlePassword}
+              error={passwordError}
+              success={passwordSuccess}
+              status={passwordStatus}
+              sx={{ width: theme.typography.pxToRem(inputWidth) }}
+              tooltipTitle={t('registration_form_password_tooltip')}
+            />
+          </div>
+          <div>
+            <FormControl
+              sx={{
+                width: theme.typography.pxToRem(inputWidth),
+                alignItems: 'center',
+                justifyContent: 'space-between',
+              }}
+            >
+              <RadioGroup row onChange={handleIsJams} value={isJams}>
+                <FormControlLabel value="false" control={<Radio />} label={t('jami')} />
+                <FormControlLabel value="true" control={<Radio />} label={t('jams')} />
+              </RadioGroup>
+            </FormControl>
+          </div>
+
+          <Button
+            variant="contained"
+            type="submit"
+            onClick={handleSubmit}
+            sx={{ width: theme.typography.pxToRem(inputWidth), mt: theme.typography.pxToRem(20) }}
+          >
+            {t('registration_form_submit_button')}
+          </Button>
+        </Form>
+
+        <Box sx={{ mt: theme.typography.pxToRem(50), mb: theme.typography.pxToRem(50) }}>
+          <Typography variant="body1">
+            {t('registration_form_to_login_text')} &nbsp;
+            <Link to={'/login'}>{t('registration_form_to_login_link')}</Link>
+          </Typography>
+        </Box>
+      </Stack>
+    </>
+  );
+}
+
+export default withAuthUI(RegistrationForm);