import type { FC, ReactNode } from "react"; import { zodResolver } from "@hookform/resolvers/zod"; import { Alert, Button, Fieldset, PasswordInput, Stack, TextInput } from "@mantine/core"; import { useState } from "react"; import { FormProvider, useForm } from "react-hook-form"; import { useTranslation } from "react-i18next"; import { Link } from "react-router"; import { type AuthFormValues, loginSchema, registerSchema, } from "../../model/auth.schema"; type AuthFormProps = { onSubmit: (email: string, password: string) => Promise; register?: boolean; }; const AuthForm: FC = (props) => { const { onSubmit, register } = props; const { t } = useTranslation(); const schema = register ? registerSchema : loginSchema; const methods = useForm({ resolver: zodResolver(schema), }); const { formState: { errors, isSubmitting }, } = methods; const [submitError, setSubmitError] = useState(null); const submit = methods.handleSubmit(async (values) => { setSubmitError(null); try { await onSubmit(values.email, values.password); } catch { setSubmitError(t("auth.requestError")); } }); const to = register ? "/login" : "/register"; const switchLabel = t(register ? "auth.haveAccount" : "auth.noAccount"); let switchLink: ReactNode; if (isSubmitting) { switchLink = ( ); } else { switchLink = ( ); } return (
{register && ( )} {submitError && {submitError}} {switchLink}
); }; export { AuthForm };