import React, { useState } from 'react';
import { useAppDispatch, useAppSelector } from '../../hooks/hooks';
import { authRequestCode, authVerifyCode, changeEmail } from './authSlice';
import styles from './VerifyCode.module.scss';


export function VerifyCode() {
    const dispatch = useAppDispatch();
    const authStatus = useAppSelector((s) => s.auth.authStatus);
    const error = useAppSelector((s) => s.auth.error);
    const email = useAppSelector((s) => s.auth.email);
    const [code, setCode] = useState('');
    const [localError, setLocalError] = useState<string | null>(null);


    const handleSubmit = (e: React.FormEvent) => {
        e.preventDefault();
        if (!/^\d{6}$/.test(code)) {
            setLocalError('Enter the 6-digit code');
            return;
        }
        if (!email) return;
        dispatch(authVerifyCode({ email, code }));
    };

    const resend = () => {
        if (!email) return;
        dispatch(authRequestCode(email));
    };

    return (
        <form onSubmit={handleSubmit} noValidate>
            <h2>Enter the 6-digit code</h2>
            <p>We sent a code to <strong>{email}</strong></p>
            <div className={styles.validationActions}>
                <input
                    type="text"
                    pattern="[0-9]{6}"
                    inputMode="numeric"
                    placeholder="123456"
                    maxLength={6}
                    autoComplete="one-time-code"  //  enables OTP autofill UX
                    value={code}
                    onChange={(e) => setCode(e.target.value.replace(/\D+/g, ''))}
                />
                <button type="submit" disabled={authStatus === 'loading'}>Verify</button>
            </div>

            <div className={styles.validationActions}>
                <button type="button" onClick={resend} disabled={authStatus === 'loading'}>
                    Resend code
                </button>
                <button type="button" onClick={() => dispatch(changeEmail())} disabled={authStatus === 'loading'}>
                    Change email
                </button>
            </div>

            {(error || localError) && (
                <div className={styles.error} role="alert" style={{ marginTop: 8 }}>
                    {error || localError}
                </div>
            )}
        </form >
    );
}