<reponame>HMS-SE/hms<filename>frontend/src/components/AuthForm.js<gh_stars>0import React, { useState } from "react";
import { useForm } from "@mantine/hooks";
import { EnvelopeClosedIcon, LockClosedIcon } from "@modulz/radix-icons";
import {
  TextInput,
  PasswordInput,
  Group,
  Button,
  Paper,
  Text,
  LoadingOverlay,
  Anchor,
  useMantineTheme,
} from "@mantine/core";
import api from "../api";

export const AuthForm = ({ noShadow, noPadding, noSubmit, style }) => {
  const [formType, setFormType] = useState("register");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const theme = useMantineTheme();

  const toggleFormType = () => {
    setFormType((current) => (current === "register" ? "login" : "register"));
    setError(null);
  };

  const form = useForm({
    initialValues: {
      name: "",
      email: "",
      password: "",
      confirmPassword: "",
    },

    validationRules: {
      name: (value) => formType === "login" || value.trim().length >= 2,
      email: (value) => /^\S+@\S+$/.test(value),
      password: (value) => /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,}$/.test(value),
      confirmPassword: (val, values) =>
        formType === "login" || val === values.password,
    },

    errorMessages: {
      name: "Name must be atleast 2 characters long",
      email: "Invalid email",
      password:
        "Password should contain 1 number, 1 letter and at least 6 characters",
      confirmPassword: "Passwords don't match. Try again",
    },
  });

  const handleSubmit = async (values) => {
    // setLoading(true);
    setError(null);
    try {
      const resp = await api.post("/users/", {
        name: values.name,
        email: values.email,
        password: values.password,
        user_type: "patient",
      });
    } catch (err) {
      console.error(err);
      setError(err.message);
    }
  };

  return (
    <Paper
      p={noPadding ? 0 : "lg"}
      shadow={noShadow ? null : "sm"}
      style={{
        position: "relative",
        backgroundColor:
          theme.colorScheme === "dark" ? theme.colors.dark[7] : theme.white,
        ...style,
      }}
    >
      <form onSubmit={form.onSubmit(handleSubmit)}>
        <LoadingOverlay visible={loading} />
        {formType === "register" && (
          <TextInput
            data-autofocus
            required
            placeholder="John Doe"
            label="Name"
            {...form.getInputProps("name")}
          />
        )}

        <TextInput
          mt="md"
          required
          placeholder="hzdkv@example.com"
          label="Email"
          icon={<EnvelopeClosedIcon />}
          {...form.getInputProps("email")}
        />

        <PasswordInput
          mt="md"
          required
          placeholder="Password"
          label="Password"
          icon={<LockClosedIcon />}
          {...form.getInputProps("password")}
        />

        {formType === "register" && (
          <PasswordInput
            mt="md"
            required
            label="Confirm Password"
            placeholder="Confirm password"
            icon={<LockClosedIcon />}
            {...form.getInputProps("confirmPassword")}
          />
        )}

        {error && (
          <Text color="red" size="sm" mt="sm">
            {error}
          </Text>
        )}

        {!noSubmit && (
          <Group position="apart" mt="xl">
            <Anchor
              component="button"
              type="button"
              color="gray"
              onClick={toggleFormType}
              size="sm"
            >
              {formType === "register"
                ? "Already a patient? Login"
                : "New patient? Register"}
            </Anchor>

            <Button color="blue" type="submit">
              {formType === "register" ? "Register" : "Login"}
            </Button>
          </Group>
        )}
      </form>
    </Paper>
  );
};
