import { Box, Button, TextField, Typography } from '@mui/material'; import parsePhoneNumberFromString from 'libphonenumber-js'; import { useRef, useState, type ChangeEvent, type Dispatch } from 'react'; import { useTranslation } from 'react-i18next'; import { AuthenticationCard } from '../AuthenticationCard'; import { CountryCodeSelector } from '../../../../components/CountryCodeSelector'; import { sendSmsCodeCompleteUserInforamation, sendSmsOtp, } from '../../api/authorizationAPI'; import type { CountryCode } from '@/types/commonTypes'; import { useApi } from '@/hooks/useApi'; import { replacePersianWithRealNumbers } from '@/utils/replacePersianWithRealNumbers'; import { useToast } from '@rkheftan/harmony-ui'; export interface CompleteSignUpProps { email: string; value: string; setValue: Dispatch; countryCode: CountryCode; setCountryCode: Dispatch; onCompleteSignUp: (countryCode: string, value: string) => void; setTimerValue: Dispatch; } export const CompleteSignUp = ({ email, value, setValue, countryCode, setCountryCode, onCompleteSignUp, setTimerValue, }: CompleteSignUpProps) => { const { t, i18n } = useTranslation('authentication'); const [error, setError] = useState(); const textFieldRef = useRef(null); const inputRef = useRef(null); const [touched, setTouched] = useState(false); const inputError: boolean = touched && !!error; const { loading: sendSmsLoading, execute: sendSmsCall } = useApi( sendSmsCodeCompleteUserInforamation, ); const toast = useToast(); const isPhoneValid = (code: string, phone: string) => { const phoneNumber = parsePhoneNumberFromString(code + phone); return phoneNumber && phoneNumber.isValid(); }; const handleBlur = () => { setTouched(true); handleValueError(); }; const handleChange = (event: ChangeEvent) => { const value = replacePersianWithRealNumbers(event.target.value); setValue(value); }; const handleValueError = () => { if (!value) { setError(t('loginForm.thisFieldIsRequired')); } if (!isPhoneValid(countryCode, value)) { setError(t('loginForm.phoneNumberIsInvalid')); } else { setError(undefined); } }; const handleCompleteSignUp = async () => { handleValueError(); if (!value || !isPhoneValid(countryCode, value)) { inputRef.current?.focus(); } else { let newValue = value; if (countryCode === '+98' && newValue.startsWith('09')) { newValue = newValue.substring(1); setValue(newValue); } const res = await sendSmsCall({ phoneNumber: countryCode + newValue }); if (!res) return; if (res.success) { onCompleteSignUp(countryCode, newValue); setTimerValue(res.totalSecondForCodeToExpire); } else { toast({ message: res.message, severity: 'error', }); setError(res.message); } } }; return ( { e.preventDefault(); e.stopPropagation(); if (!sendSmsLoading) void handleCompleteSignUp(); }} > {t('completeSignUp.completeSignUp')} {t( 'completeSignUp.emailHasBeenSuccessfullyVerifiedPleaseEnterYourContactNumberToContinue', { email }, )} ), startAdornment: i18n.dir() === 'ltr' && ( ), }, }} sx={{ my: 4 }} /> ); };