import React, { useEffect } from "react";
import classes from "./classes.module.scss";
import Typography, { ITypo, ITypoColor } from "@Front/Components/DesignSystem/Typography";
import Form from "@Front/Components/DesignSystem/Form";
import TextField from "@Front/Components/DesignSystem/Form/TextField";
import Button, { EButtonVariant } from "@Front/Components/DesignSystem/Button";
import { ValidationError } from "class-validator";
type IProps = {
	onSubmit: (e: React.FormEvent<HTMLFormElement> | null, values: { [key: string]: string }) => void;
	validationErrors: ValidationError[];
	partialPhoneNumber: string;
	onSendAnotherCode: () => void;
};

export default function StepTotp(props: IProps) {
	const { onSubmit, validationErrors, partialPhoneNumber, onSendAnotherCode } = props;
	const [disableNewCodeButton, setDisableNewCodeButton] = React.useState(false);
	const [secondsBeforeNewCode, setSecondsBeforeNewCode] = React.useState(0);

	useEffect(() => {
		const interval = setInterval(() => {
			if (secondsBeforeNewCode > 0) {
				setSecondsBeforeNewCode(secondsBeforeNewCode - 1);
				if (secondsBeforeNewCode === 1) {
					setDisableNewCodeButton(false);
				}
			}
		}, 1000);
		return () => clearInterval(interval);
	}, [secondsBeforeNewCode]);

	const sendAnotherCode = () => {
		onSendAnotherCode();
		setDisableNewCodeButton(true);
		setSecondsBeforeNewCode(30);
	};

	return (
		<div className={classes["root"]}>
			<Typography typo={ITypo.DISPLAY_LARGE}>
				<div className={classes["title"]}>
					Votre code a été envoyé par SMS au ** ** ** {partialPhoneNumber.replace(/(.{2})/g, "$1 ")}
				</div>
			</Typography>
			<Form className={classes["form"]} onSubmit={onSubmit}>
				<TextField
					placeholder="Code à usage unique"
					name="totpCode"
					validationError={validationErrors.find((error) => error.property === "totpCode")}
				/>
				<Button type="submit" variant={EButtonVariant.PRIMARY} className={classes["submit_button"]}>
					Suivant
				</Button>
			</Form>
			<div className={classes["ask-another-code"]}>
				<Typography typo={ITypo.TEXT_MD_REGULAR}>Vous n'avez rien reçu ?</Typography>
				<Button
					variant={EButtonVariant.LINE}
					disabled={disableNewCodeButton}
					data-disabled={disableNewCodeButton.toString()}
					onClick={sendAnotherCode}
					className={classes["new-code-button"]}>
					Envoyer un nouveau code
				</Button>
				{secondsBeforeNewCode !== 0 && (
					<Typography typo={ITypo.TEXT_MD_SEMIBOLD} className={classes["new-code-timer"]}>
						Redemandez un code dans
						<Typography typo={ITypo.TEXT_MD_REGULAR} color={ITypoColor.COLOR_SECONDARY_500}>
							00:{secondsBeforeNewCode < 10 ? `0${secondsBeforeNewCode}` : secondsBeforeNewCode}
						</Typography>
					</Typography>
				)}
			</div>
		</div>
	);
}
