import { Box, Button, Stack, TextField, Typography } from '@mui/material'; import { useRef, useState, type Dispatch } from 'react'; import { useTranslation } from 'react-i18next'; import { CountryCodeSelector } from './CountryCodeSelector'; import { Google } from 'iconsax-reactjs'; import { isNumeric } from '@/utils/regexes/isNumeric'; import type { AuthMode, AuthType } from '../types/auth-types'; import { isEmail } from '@/utils/regexes/isEmail'; export interface LoginRegisterFormProps { authType: AuthType; setAuthType: Dispatch; onLoginRegisterSubmit: (value: string) => void; } export function LoginRegisterForm({ authType, setAuthType, }: LoginRegisterFormProps) { const { t, i18n } = useTranslation('authentication'); const [value, setValue] = useState(''); const [countryCode, setCountryCode] = useState('+98'); const textFieldRef = useRef(null); const inputRef = useRef(null); const dir = i18n.dir(); const [error, setError] = useState(); const [touched, setTouched] = useState(false); const inputError: boolean = touched && !!error; const handleInputChange = (event: React.ChangeEvent) => { const newValue = event.target.value; setValue(newValue); // If the new value contains only digits (or is empty), it's a phone number if (isNumeric(newValue)) { setAuthType('phone'); } else { setAuthType('email'); } }; const handleBlur = () => { setTouched(true); validateInput(value, authType); }; const validateInput = (value: string, authType: AuthType) => { if (!value) { setError(t('loginForm.thisFieldIsRequired')); } else if (authType === 'email' && !isEmail(value)) { setError(t('loginForm.emailIsInvalid')); } else if (authType === 'phone' && false /* TODO */) { setError(t('loginForm.emailIsInvalid')); } else { setError(undefined); } }; const isInputValid = (value: string, authType: AuthType): boolean => { if (!value) { return false; } if (authType === 'email' && !isEmail(value)) { return false; } if (authType === 'phone' && false /* TODO */) { return false; } return true; }; const handleSubmit = () => { if (isInputValid(value, authType)) { } else { inputRef.current?.focus(); validateInput(value, authType); } }; const showAdornment = authType === 'phone' && value.length > 0; return ( {t('loginForm.title')} {t('loginForm.description')} ), endAdornment: dir === 'rtl' && ( ), }, }} sx={{ my: 4 }} /> ); }