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

type Mode = 'login' | 'register';

const PASSWORD_POLICY = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^A-Za-z\d]).{12,}$/;
const USERNAME_POLICY = /^(?=.{3,24}$)[a-zA-Z0-9._-]+$/;

const toAuthMessage = (errorCode: string, language: 'fr' | 'en') => {
  if (language === 'fr') {
    switch (errorCode) {
      case 'auth/invalid-credential':
      case 'auth/wrong-password':
      case 'auth/user-not-found':
        return 'Identifiants invalides.';
      case 'auth/email-already-in-use':
        return 'Cet email est déjà utilisé.';
      case 'auth/invalid-email':
        return 'Adresse email invalide.';
      case 'auth/too-many-requests':
        return 'Trop de tentatives. Réessaie plus tard.';
      case 'auth/unauthorized-domain':
        return 'Domaine non autorisé dans Firebase Auth.';
      case 'auth/operation-not-allowed':
        return 'Connexion Google non activée dans Firebase.';
      case 'auth/popup-blocked':
        return 'Popup bloquée. Autorise les popups ou utilise la redirection.';
      case 'auth/popup-closed-by-user':
        return 'Connexion annulée.';
      case 'auth/network-request-failed':
        return 'Problème réseau. Vérifie ta connexion.';
      default:
        return 'Une erreur est survenue.';
    }
  }

  switch (errorCode) {
    case 'auth/invalid-credential':
    case 'auth/wrong-password':
    case 'auth/user-not-found':
      return 'Invalid credentials.';
    case 'auth/email-already-in-use':
      return 'This email is already in use.';
    case 'auth/invalid-email':
      return 'Invalid email address.';
    case 'auth/too-many-requests':
      return 'Too many attempts. Try again later.';
    case 'auth/unauthorized-domain':
      return 'Unauthorized domain in Firebase Auth.';
    case 'auth/operation-not-allowed':
      return 'Google sign-in is not enabled in Firebase.';
    case 'auth/popup-blocked':
      return 'Popup blocked. Allow popups or use redirect.';
    case 'auth/popup-closed-by-user':
      return 'Sign-in canceled.';
    case 'auth/network-request-failed':
      return 'Network issue. Check your connection.';
    default:
      return 'Something went wrong.';
  }
};

const Login = () => {
  const { language } = useLanguage();
  const {
    user,
    loading,
    codeVerified,
    verificationLoading,
    loginWithEmail,
    registerWithEmail,
    loginWithGoogle,
    checkUsernameAvailability,
    registerProfile
  } = useAuth();
  const navigate = useNavigate();

  const [mode, setMode] = useState<Mode>('login');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [username, setUsername] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');

  useEffect(() => {
    if (!loading && !verificationLoading && user) {
      navigate(codeVerified ? `/${language}` : `/${language}/verify-auth`, { replace: true });
    }
  }, [codeVerified, language, loading, navigate, user, verificationLoading]);

  const passwordValid = PASSWORD_POLICY.test(password);
  const usernameValid = USERNAME_POLICY.test(username);

  const submitEmailAuth = async (event: FormEvent) => {
    event.preventDefault();
    setError('');
    setSuccess('');

    if (mode === 'register' && !passwordValid) {
      setError(
        language === 'fr'
          ? 'Mot de passe invalide: min 12, 1 majuscule, 1 minuscule, 1 chiffre, 1 spécial.'
          : 'Invalid password: min 12, 1 uppercase, 1 lowercase, 1 number, 1 special.'
      );
      return;
    }

    if (mode === 'register' && !usernameValid) {
      setError(
        language === 'fr'
          ? 'Pseudo invalide: 3 à 24 caractères, lettres/chiffres/._- uniquement.'
          : 'Invalid username: 3 to 24 chars, letters/numbers/._- only.'
      );
      return;
    }

    try {
      setSubmitting(true);
      if (mode === 'login') {
        await loginWithEmail(email, password);
      } else {
        const normalizedUsername = username.trim().toLowerCase();
        const available = await checkUsernameAvailability(normalizedUsername);
        if (!available) {
          setError(language === 'fr' ? 'Ce pseudo est déjà utilisé.' : 'This username is already taken.');
          setSubmitting(false);
          return;
        }

        const credential = await registerWithEmail(email, password);
        await registerProfile({
          email: credential.user.email || email,
          firebaseUid: credential.user.uid,
          username: normalizedUsername
        });

        setSuccess(language === 'fr' ? 'Compte créé avec succès.' : 'Account created successfully.');
      }
    } catch (caught) {
      const errorCode = typeof caught === 'object' && caught !== null && 'code' in caught ? String((caught as { code?: string }).code) : '';
      if (errorCode) {
        setError(toAuthMessage(errorCode, language));
      } else {
        setError(caught instanceof Error ? caught.message : language === 'fr' ? 'Une erreur est survenue.' : 'Something went wrong.');
      }
    } finally {
      setSubmitting(false);
    }
  };

  const submitGoogle = async () => {
    try {
      setSubmitting(true);
      setError('');
      setSuccess('');
      await loginWithGoogle();
    } catch (caught) {
      const errorCode =
        typeof caught === 'object' && caught !== null && 'code' in caught ? String((caught as { code?: string }).code) : '';
      if (errorCode) {
        setError(toAuthMessage(errorCode, language));
      } else {
        setError(caught instanceof Error ? caught.message : toAuthMessage('', language));
      }
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <section className="auth-page">
      <div className="auth-card">
        <h1>{language === 'fr' ? 'Connexion' : 'Sign in'}</h1>
        <p>{language === 'fr' ? 'Connecte-toi à ton compte' : 'Sign in to your account'}</p>

        <div className="auth-tabs" role="tablist" aria-label="auth modes">
          <button type="button" className={mode === 'login' ? 'is-active' : ''} onClick={() => setMode('login')}>
            {language === 'fr' ? 'Se connecter' : 'Sign in'}
          </button>
          <button type="button" className={mode === 'register' ? 'is-active' : ''} onClick={() => setMode('register')}>
            {language === 'fr' ? 'Créer un compte' : 'Create account'}
          </button>
        </div>

        <form onSubmit={submitEmailAuth} className="auth-form">
          {mode === 'register' ? (
            <>
              <label htmlFor="auth-username">{language === 'fr' ? 'Pseudo' : 'Username'}</label>
              <input
                id="auth-username"
                type="text"
                autoComplete="username"
                required
                minLength={3}
                maxLength={24}
                value={username}
                onChange={(event) => setUsername(event.target.value)}
              />
            </>
          ) : null}

          <label htmlFor="auth-email">{language === 'fr' ? 'Email' : 'Email'}</label>
          <input
            id="auth-email"
            type="email"
            autoComplete="email"
            required
            value={email}
            onChange={(event) => setEmail(event.target.value)}
          />

          <label htmlFor="auth-password">{language === 'fr' ? 'Mot de passe' : 'Password'}</label>
          <input
            id="auth-password"
            type="password"
            autoComplete={mode === 'login' ? 'current-password' : 'new-password'}
            required
            value={password}
            onChange={(event) => setPassword(event.target.value)}
            minLength={mode === 'register' ? 12 : 1}
          />

          {mode === 'register' ? (
            <ul className="auth-rules">
              <li className={usernameValid ? 'ok' : ''}>
                {language === 'fr' ? 'Pseudo unique (3-24, lettres/chiffres/._-)' : 'Unique username (3-24, letters/numbers/._-)'}
              </li>
              <li className={password.length >= 12 ? 'ok' : ''}>{language === 'fr' ? '12+ caractères' : '12+ characters'}</li>
              <li className={/[A-Z]/.test(password) ? 'ok' : ''}>{language === 'fr' ? '1 majuscule' : '1 uppercase'}</li>
              <li className={/[a-z]/.test(password) ? 'ok' : ''}>{language === 'fr' ? '1 minuscule' : '1 lowercase'}</li>
              <li className={/\d/.test(password) ? 'ok' : ''}>{language === 'fr' ? '1 chiffre' : '1 number'}</li>
              <li className={/[^A-Za-z\d]/.test(password) ? 'ok' : ''}>
                {language === 'fr' ? '1 caractère spécial' : '1 special character'}
              </li>
            </ul>
          ) : null}

          <button type="submit" disabled={submitting}>
            {submitting
              ? language === 'fr'
                ? 'Veuillez patienter...'
                : 'Please wait...'
              : mode === 'login'
                ? language === 'fr'
                  ? 'Se connecter'
                  : 'Sign in'
                : language === 'fr'
                  ? 'Créer le compte'
                  : 'Create account'}
          </button>
        </form>

        <button type="button" className="google-auth google-auth--provider" onClick={submitGoogle} disabled={submitting}>
          <img src="/google.png" alt="" aria-hidden="true" className="google-auth__icon" />
          {language === 'fr' ? 'Continuer avec Google' : 'Continue with Google'}
        </button>

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

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

export default Login;
