import styles from '@/app/styles/module/login.module.scss';
import { useTranslations } from 'next-intl';
import { ChangeEvent, MouseEvent, useState, useEffect } from 'react';
import { resendConfirmEmail, confirmEmail } from '@/app/actions/auth';
import { IconRefresh } from '@/app/ui/icons/icons';

export default function ConfirmMailModalWindow({ userId, email, onClose }: { userId: number | undefined, email: string | undefined, onClose?: () => void }) {
	const [error, setError] = useState<string | null>(null);
	const [isPending, setIsPending] = useState(false);
	const [confirmCodeValue, setConfirmCodeValue] = useState('');
	const [isInputDisabled, setIsInputDisabled] = useState(true);
	const [timer, setTimer] = useState(30);
	const t = useTranslations('Login-register-form');

	async function handleConfirmEmail(e: React.FormEvent) {
		e.preventDefault();

		if (!userId || confirmCodeValue.length !== 6) {
			return;
		}

		setIsPending(true);
		setError(null);

		try {
			const result = await confirmEmail(userId, confirmCodeValue);

			if (result.error) {
				setError(t(result.error));

			} else {
				if (onClose) {
					setTimeout(() => onClose(), 1500);
				}
			}
		} catch (err) {
			setError(t('entered-code-is-incorrect'));
		} finally {
			setIsPending(false);
		}
	}

	async function reSendEmailConfirmCode(e: MouseEvent) {
		e.preventDefault();
		if (userId) {
			setIsInputDisabled(true);
			await resendConfirmEmail(userId);
			setTimer(30);
		}
	}

	function onChangeHandler(e: ChangeEvent<HTMLInputElement>) {
		const newValue = e.target.value.replace(/([^0-9])/g, '');
		if (newValue.length <= 6) {
			setConfirmCodeValue(newValue);
		}
	}

	useEffect(() => {
		let interval: NodeJS.Timeout;

		if (timer > 0 && isInputDisabled) {
			interval = setInterval(() => {
				setTimer(prev => {
					if (prev <= 1) {
						setIsInputDisabled(false);
						return 0;
					}
					return prev - 1;
				});
			}, 1000);
		}

		return () => {
			if (interval) clearInterval(interval);
		};
	}, [timer, isInputDisabled]);

	return (
		<div
			className="modal-window"
			onClick={(e) => e.stopPropagation()}
		>
			<div className={`${styles['form-group']} ${styles['form-group-confrim-window']}`}>
				<form onSubmit={handleConfirmEmail}>
					<div className={`${styles['form-group']}`}>
						<h4>
							{t('enter-confirmation-code')}
							<br />
						</h4>
						<p className="mb-6">
							{email}
						</p>
						<input
							type="text"
							id="emailConfirm"
							name="emailConfirm"
							className={`${styles['form-input']}`}
							placeholder={t('confirmation-code')}
							value={confirmCodeValue}
							onChange={onChangeHandler}
							disabled={isPending}
						/>

						{error && (
							<p className="text-sm text-red-500">
								{error}
							</p>
						)}
					</div>

					<div className={`${styles['form-group-confrim-window-button-group']}`}>
						<button
							type="submit"
							className={`${styles['btn']}`}
							disabled={confirmCodeValue.length !== 6 || isPending}
						>
							{isPending ? t('confirming') : t('confirm')}
						</button>

						<button
							className={`${styles['btn'] + ' ' + styles['refresh']}`}
							disabled={isInputDisabled || isPending}
							onClick={reSendEmailConfirmCode}
							title={t('resend-code')}
							type="button"
						>
							<IconRefresh />
							<div>
								{t('resend-code')}
							</div>
							{timer !== 0 ? timer : ''}
						</button>
					</div>
				</form>
			</div>
		</div>
	);
}