import { useEffect, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { exchangeCode, loadVerifier, clearVerifier } from '../lib/oauth';
import { authApi } from '../api/endpoints';
import { useAuth } from '../context/AuthContext';

export function AuthCallback() {
  const navigate = useNavigate();
  const { refresh } = useAuth();
  const called = useRef(false);
  const [status, setStatus] = useState<'loading' | 'error'>('loading');
  const [errorMsg, setErrorMsg] = useState('');

  useEffect(() => {
    if (called.current) return;
    called.current = true;

    const params = new URLSearchParams(window.location.search);
    const code   = params.get('code');
    const error  = params.get('error');

    if (error) {
      setStatus('error');
      setErrorMsg(error);
      return;
    }

    if (!code) {
      navigate('/login?error=no_code', { replace: true });
      return;
    }

    const verifier = loadVerifier();
    if (!verifier) {
      navigate('/login?error=no_verifier', { replace: true });
      return;
    }

    const redirectUri = `${window.location.origin}/auth/callback`;

    exchangeCode(code, verifier, redirectUri)
      .then((tokens) => {
        clearVerifier();
        return authApi.setSession(tokens.access_token, tokens.refresh_token);
      })
      .then(() => refresh())
      .then(() => navigate('/dashboard', { replace: true }))
      .catch(() => {
        clearVerifier();
        navigate('/login?error=session_failed', { replace: true });
      });
  }, [navigate, refresh]);

  if (status === 'error') {
    return (
      <div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <div style={{ textAlign: 'center' }}>
          <div style={{ fontSize: 40, marginBottom: 16 }}>💀</div>
          <p style={{ color: '#ef4444', fontSize: 14, marginBottom: 8 }}>Erreur d'authentification</p>
          <p style={{ color: '#6b7a99', fontSize: 12 }}>{errorMsg}</p>
        </div>
      </div>
    );
  }

  return (
    <div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
      <div style={{ textAlign: 'center' }}>
        <div style={{ fontSize: 40, marginBottom: 16 }}>⚔️</div>
        <p style={{ color: '#6b7a99', fontSize: 14 }}>Connexion en cours…</p>
      </div>
    </div>
  );
}
