import { useEffect, useRef } from 'react';
import { useLogto } from '@logto/react';
import { useNavigate } from 'react-router';
import { Spinner } from '@cameleer/design-system';

export function LoginPage() {
  const { signIn, isAuthenticated, isLoading } = useLogto();
  const navigate = useNavigate();
  const redirected = useRef(false);

  useEffect(() => {
    if (isAuthenticated) {
      navigate('/', { replace: true });
    }
  }, [isAuthenticated, navigate]);

  useEffect(() => {
    if (!isLoading && !isAuthenticated && !redirected.current) {
      redirected.current = true;
      signIn(`${window.location.origin}/platform/callback`);
    }
  }, [isLoading, isAuthenticated, signIn]);

  return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: '100vh' }}>
      <Spinner />
    </div>
  );
}
