import React from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../auth/context';
import { isAuthError } from '../auth/tokens';
import { ADMIN_HOME_PATH } from '../constants';

export default function AuthCallbackPage() {
  const { completeLogin } = useAuth();
  const navigate = useNavigate();
  const [error, setError] = React.useState<string | null>(null);

  React.useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    completeLogin(params)
      .then((redirectTo) => {
        navigate(redirectTo ?? ADMIN_HOME_PATH, { replace: true });
      })
      .catch((err) => {
        console.error('[Auth] Callback processing failed', err);
        if (isAuthError(err) && err.code === 'token_exchange_failed') {
          setError('Anmeldung fehlgeschlagen. Bitte versuche es erneut.');
        } else if (isAuthError(err) && err.code === 'invalid_state') {
          setError('Ungueltiger Login-Vorgang. Bitte starte die Anmeldung erneut.');
        } else {
          setError('Unbekannter Fehler beim Login.');
        }
      });
  }, [completeLogin, navigate]);

  return (
    <div className="flex min-h-screen flex-col items-center justify-center gap-3 p-6 text-center text-sm text-muted-foreground">
      <span className="text-base font-medium text-foreground">Anmeldung wird verarbeitet ...</span>
      {error && <div className="max-w-sm rounded border border-red-300 bg-red-50 p-3 text-sm text-red-700">{error}</div>}
    </div>
  );
}

