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

const USERNAME_POLICY = /^(?=.{3,24}$)[a-zA-Z0-9._-]+$/;

const ProfileSetup = () => {
  const { language } = useLanguage();
  const { user, loading, codeVerified, hasProfile, profileLoading, checkUsernameAvailability, registerProfile } = useAuth();
  const navigate = useNavigate();

  const [username, setUsername] = useState('');
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');

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

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

    const normalizedUsername = username.trim().toLowerCase();
    if (!USERNAME_POLICY.test(normalizedUsername)) {
      setError(
        language === 'fr'
          ? 'Pseudo invalide: 3 à 24 caractères, lettres/chiffres/._- uniquement.'
          : 'Invalid username: 3 to 24 chars, letters/numbers/._- only.'
      );
      return;
    }

    if (!user?.email) {
      setError(language === 'fr' ? 'Utilisateur non connecté.' : 'User is not signed in.');
      return;
    }

    try {
      setBusy(true);
      const available = await checkUsernameAvailability(normalizedUsername);
      if (!available) {
        setError(language === 'fr' ? 'Ce pseudo est déjà utilisé.' : 'This username is already taken.');
        return;
      }

      await registerProfile({
        email: user.email,
        firebaseUid: user.uid,
        username: normalizedUsername
      });

      setSuccess(language === 'fr' ? 'Profil enregistré.' : 'Profile saved.');
      navigate(`/${language}`, { replace: true });
    } catch (caught) {
      setError(caught instanceof Error ? caught.message : language === 'fr' ? 'Une erreur est survenue.' : 'Something went wrong.');
    } finally {
      setBusy(false);
    }
  };

  return (
    <section className="auth-page">
      <div className="auth-card">
        <h1>{language === 'fr' ? 'Choisis ton pseudo' : 'Choose your username'}</h1>
        <p>
          {language === 'fr'
            ? 'Ton pseudo doit être unique pour finaliser ton compte.'
            : 'Your username must be unique to complete your account.'}
        </p>

        <form className="auth-form" onSubmit={handleSubmit}>
          <label htmlFor="profile-username">{language === 'fr' ? 'Pseudo' : 'Username'}</label>
          <input
            id="profile-username"
            type="text"
            required
            minLength={3}
            maxLength={24}
            autoComplete="username"
            value={username}
            onChange={(event) => setUsername(event.target.value)}
          />
          <button type="submit" disabled={busy}>
            {busy ? (language === 'fr' ? 'Veuillez patienter...' : 'Please wait...') : language === 'fr' ? 'Valider' : 'Save'}
          </button>
        </form>

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

export default ProfileSetup;
