import { useEffect, useState, type FormEvent } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';
import { useLanguage } from '../contexts/LanguageContext';

const VerifyAuthCode = () => {
  const { language } = useLanguage();
  const { user, loading, codeVerified, sendLoginCode, verifyLoginCode, logout } = useAuth();
  const navigate = useNavigate();
  const isGoogleOnlyUser = Boolean(
    user?.providerData.some((entry) => entry.providerId === 'google.com') &&
      !user?.providerData.some((entry) => entry.providerId === 'password')
  );

  const [code, setCode] = useState('');
  const [busy, setBusy] = useState(false);
  const [message, setMessage] = useState('');
  const [error, setError] = useState('');

  useEffect(() => {
    if (!loading && !user) {
      navigate(`/${language}/login`, { replace: true });
      return;
    }
    if (!loading && codeVerified) {
      navigate(`/${language}`, { replace: true });
    }
    if (!loading && user && isGoogleOnlyUser) {
      navigate(`/${language}`, { replace: true });
    }
  }, [codeVerified, isGoogleOnlyUser, language, loading, navigate, user]);

  useEffect(() => {
    const autoSendCode = async () => {
      if (!user || codeVerified || isGoogleOnlyUser) return;
      try {
        await sendLoginCode();
        setMessage(language === 'fr' ? 'Code envoyé par email.' : 'Code sent by email.');
      } catch (caught) {
        const fallback = language === 'fr' ? 'Impossible d’envoyer le code.' : 'Unable to send code.';
        setError(caught instanceof Error ? caught.message : fallback);
      }
    };

    void autoSendCode();
  }, [codeVerified, isGoogleOnlyUser, language, sendLoginCode, user]);

  const handleResend = async () => {
    try {
      setBusy(true);
      setError('');
      setMessage('');
      if (isGoogleOnlyUser) {
        navigate(`/${language}`, { replace: true });
        return;
      }
      await sendLoginCode();
      setMessage(language === 'fr' ? 'Nouveau code envoyé.' : 'New code sent.');
    } catch (caught) {
      const fallback = language === 'fr' ? 'Impossible d’envoyer le code.' : 'Unable to send code.';
      setError(caught instanceof Error ? caught.message : fallback);
    } finally {
      setBusy(false);
    }
  };

  const handleVerify = async (event: FormEvent) => {
    event.preventDefault();
    try {
      setBusy(true);
      setError('');
      setMessage('');
      await verifyLoginCode(code.trim());
      setMessage(language === 'fr' ? 'Connexion vérifiée.' : 'Login verified.');
      navigate(`/${language}`, { replace: true });
    } catch (caught) {
      const fallback = language === 'fr' ? 'Code invalide ou expiré.' : 'Invalid or expired code.';
      setError(caught instanceof Error ? caught.message : fallback);
    } finally {
      setBusy(false);
    }
  };

  return (
    <section className="auth-page">
      <div className="auth-card">
        <h1>{language === 'fr' ? 'Vérification de connexion' : 'Login verification'}</h1>
        <p>
          {language === 'fr'
            ? 'Entre le code reçu par email pour terminer la connexion.'
            : 'Enter the code sent by email to complete sign in.'}
        </p>

        <form className="auth-form" onSubmit={handleVerify}>
          <label htmlFor="verification-code">{language === 'fr' ? 'Code à 6 chiffres' : '6-digit code'}</label>
          <input
            id="verification-code"
            type="text"
            inputMode="numeric"
            pattern="[0-9]{6}"
            maxLength={6}
            required
            value={code}
            onChange={(event) => setCode(event.target.value.replace(/\D/g, '').slice(0, 6))}
          />
          <button type="submit" disabled={busy || code.length !== 6}>
            {busy ? (language === 'fr' ? 'Veuillez patienter...' : 'Please wait...') : language === 'fr' ? 'Vérifier' : 'Verify'}
          </button>
        </form>

        <button type="button" className="google-auth" onClick={handleResend} disabled={busy}>
          {language === 'fr' ? 'Renvoyer un code' : 'Resend code'}
        </button>

        <button type="button" className="google-auth" onClick={() => void logout()} disabled={busy}>
          {language === 'fr' ? 'Se déconnecter' : 'Sign out'}
        </button>

        {error ? <p className="auth-message auth-message--error">{error}</p> : null}
        {message ? <p className="auth-message auth-message--success">{message}</p> : null}

        <Link to={`/${language}`} className="auth-back-link">
          {language === 'fr' ? 'Retour à l’accueil' : 'Back to home'}
        </Link>
      </div>
    </section>
  );
};

export default VerifyAuthCode;
