import { useEffect, useRef } from 'react';
import { Navigate, useNavigate } from 'react-router';
import { useAuthStore } from './auth-store';
import styles from './LoginPage.module.css';

export function OidcCallback() {
  const { isAuthenticated, loading, error, loginWithOidcCode } = useAuthStore();
  const navigate = useNavigate();
  const exchanged = useRef(false);

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

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

    if (errorParam) {
      useAuthStore.setState({
        error: params.get('error_description') || errorParam,
        loading: false,
      });
      return;
    }

    if (!code) {
      useAuthStore.setState({ error: 'No authorization code received', loading: false });
      return;
    }

    const redirectUri = `${window.location.origin}/oidc/callback`;
    loginWithOidcCode(code, redirectUri);
  }, [loginWithOidcCode]);

  if (isAuthenticated) return <Navigate to="/" replace />;

  return (
    <div className={styles.page}>
      <div className={styles.card}>
        <div className={styles.logo}>
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <path d="M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10 10-4.5 10-10S17.5 2 12 2" />
            <path d="M12 6v6l4 2" />
          </svg>
          cameleer3
        </div>
        {loading && <div className={styles.subtitle}>Completing sign-in...</div>}
        {error && (
          <>
            <div className={styles.error}>{error}</div>
            <button
              className={styles.submit}
              style={{ marginTop: 16 }}
              onClick={() => navigate('/login')}
            >
              Back to Login
            </button>
          </>
        )}
      </div>
    </div>
  );
}
