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

import { AgencyLogo } from '../../components/AgencyLogo/AgencyLogo';


export function RequestCode() {
    const dispatch = useAppDispatch();
    const authStatus = useAppSelector((s) => s.auth.authStatus);
    const error = useAppSelector((s) => s.auth.error);
    const { verified } = useAppSelector((s) => s.auth);
    const [emailInput, setEmailInput] = useState('');
    const [localError, setLocalError] = useState<string | null>(null);
    console.log("*** RequestCode render, authStatus:", authStatus);

    const handleSubmit = (e: React.FormEvent) => {
        e.preventDefault();
        const ok = /\S+@\S+\.\S+/.test(emailInput);
        if (!ok) {
            setLocalError('Please enter a valid email address');
            return;
        }
        setLocalError(null);
        dispatch(setEmail(emailInput));
        console.log("*** 00 dispatching request code ***");
        dispatch(authRequestCode(emailInput));
    };


    return (
        <form onSubmit={handleSubmit} noValidate className={styles.requestCodeForm}>
            <h2 data-test="request-code-header">Start by entering your email</h2>
            <input
                type="email"
                required
                value={emailInput}
                onChange={(e) => setEmailInput(e.target.value)}
                placeholder="you@example.com"
            />
            <button className={styles.sendCode} type="submit" disabled={authStatus === 'loading'}>{authStatus === 'loading' ? (!verified ? 'Sending…' : '') : 'Send code'}</button>
            {(localError || error) && (
                <div className={styles.error} role="alert">
                    {localError || error}
                </div>
            )}
            {/* Helpful hint for throttling */}
            {error?.toLowerCase().includes('too many') && (
                <small>Tip: wait a minute before trying again.</small>
            )}

            <AgencyLogo className={styles.beforeValidation} />
        </form>
    );
}