import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { apiFetch } from '../lib/api';
import { exchangeCode, loadVerifier } from '../lib/oauth';
import { useAuthContext } from '../context/AuthContext';
import type { User } from '../context/AuthContext';

interface SessionResponse {
  success: boolean;
  data: { user: User };
}

type PendingState =
  | { kind: 'verification_pending'; email: string }
  | { kind: 'merge_pending'; email: string; provider: string };

export default function CallbackPage() {
  const navigate = useNavigate();
  const { setUser } = useAuthContext();
  const [error, setError] = useState<string | null>(null);
  const [pending, setPending] = useState<PendingState | null>(null);

  useEffect(() => {
    const params = new URLSearchParams(window.location.search);

    // --- Erreur OAuth explicite ---
    const oauthError = params.get('error');
    if (oauthError) {
      const desc = params.get('error_description') ?? oauthError;
      setError(`Erreur OAuth : ${desc}`);
      return;
    }

    // --- Pending states (verification / merge) ---
    const status = params.get('status');
    if (status === 'verification_pending') {
      setPending({ kind: 'verification_pending', email: params.get('email') ?? '' });
      return;
    }
    if (status === 'merge_pending') {
      setPending({
        kind: 'merge_pending',
        email: params.get('email') ?? '',
        provider: params.get('provider') ?? '',
      });
      return;
    }

    // --- Flow PKCE : ?code= présent ---
    const code = params.get('code');
    if (code) {
      const verifier = loadVerifier();
      if (!verifier) {
        setError('Session PKCE expirée. Recommence la connexion.');
        return;
      }
      const redirectUri = `${window.location.origin}/callback`;

      exchangeCode(code, verifier, redirectUri)
        .then((tokens) => {
          return apiFetch<SessionResponse>('/auth/session', {
            method: 'POST',
            body: JSON.stringify({
              token: tokens.access_token,
              refreshToken: tokens.refresh_token,
            }),
          });
        })
        .then((res) => {
          setUser(res.data.user);
          navigate('/', { replace: true });
        })
        .catch(() => setError("Échec de l'échange de code OAuth. Réessaie."));
      return;
    }

    // --- Flow session (token JWT en query param) ---
    const token = params.get('token');
    if (token) {
      apiFetch<SessionResponse>('/auth/session', {
        method: 'POST',
        body: JSON.stringify({ token }),
      })
        .then((res) => {
          setUser(res.data.user);
          navigate('/', { replace: true });
        })
        .catch(() => setError("Échec de l'authentification. Réessaie."));
      return;
    }

    // Aucun paramètre reconnu → retour accueil
    navigate('/', { replace: true });
  }, [navigate, setUser]);

  // --- Pending UI ---
  if (pending) {
    return (
      <div className="flex flex-col items-center gap-6 pt-20 max-w-md mx-auto text-center">
        {pending.kind === 'verification_pending' ? (
          <>
            <div className="text-4xl">📧</div>
            <h2 className="text-lg font-semibold text-od-text">Vérifie ton email</h2>
            <p className="text-sm text-od-muted">
              Un email de vérification a été envoyé à{' '}
              <span className="text-od-text font-mono">{pending.email}</span>.
              <br />
              Clique sur le lien pour activer ton compte.
            </p>
          </>
        ) : (
          <>
            <div className="text-4xl">🔗</div>
            <h2 className="text-lg font-semibold text-od-text">Fusion de compte</h2>
            <p className="text-sm text-od-muted">
              Un compte existe déjà avec l'email{' '}
              <span className="text-od-text font-mono">{pending.email}</span>.
              <br />
              Un email a été envoyé pour fusionner ton compte{' '}
              <span className="text-od-accent capitalize">{pending.provider}</span>.
              <br />
              Clique sur le lien dans l'email pour confirmer.
            </p>
          </>
        )}
        <a
          href="/login"
          className="font-mono text-xs text-od-muted hover:text-od-text transition-colors"
        >
          ← Retour à la connexion
        </a>
      </div>
    );
  }

  // --- Error UI ---
  if (error) {
    return (
      <div className="flex flex-col items-center gap-4 pt-20">
        <p className="text-od-crit">{error}</p>
        <a
          href="/"
          className="font-mono text-xs text-od-muted hover:text-od-text transition-colors"
        >
          ← Retour à l'accueil
        </a>
      </div>
    );
  }

  return (
    <div className="flex items-center justify-center pt-20">
      <p className="font-mono text-sm text-od-muted">Connexion en cours…</p>
    </div>
  );
}
