import { useEffect, useRef, useState } from 'react';
import { useLogto } from '@logto/react';
import { useNavigate } from 'react-router';
import { Button, Card, Spinner } from '@cameleer/design-system';
import cameleerLogo from '@cameleer/design-system/assets/cameleer-logo.svg';

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

  // Check if we arrived here from a logout redirect (set by useAuth before signOut)
  const [signedOut] = useState(() => {
    const flag = sessionStorage.getItem('cameleer:signed_out');
    if (flag) sessionStorage.removeItem('cameleer:signed_out');
    return !!flag;
  });

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

  useEffect(() => {
    // Don't auto-redirect after logout — show the signed-out state instead
    if (signedOut) return;
    if (!isLoading && !isAuthenticated && !redirected.current) {
      redirected.current = true;
      signIn(`${window.location.origin}/platform/callback`);
    }
  }, [isLoading, isAuthenticated, signIn, signedOut]);

  if (signedOut && !isAuthenticated) {
    return (
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        minHeight: '100vh', background: 'var(--bg-base)',
      }}>
        <Card className="signed-out-card">
          <div style={{
            display: 'flex', flexDirection: 'column', alignItems: 'center',
            width: '100%', fontFamily: 'var(--font-body)',
          }}>
            <div style={{
              display: 'flex', alignItems: 'center', gap: 10,
              marginBottom: 8, fontSize: 24, fontWeight: 700, color: 'var(--text-primary)',
            }}>
              <img src={cameleerLogo} alt="" width="36" height="36" />
              Cameleer
            </div>
            <p style={{ fontSize: 13, color: 'var(--text-muted)', margin: '0 0 24px' }}>
              You have been signed out successfully.
            </p>
            <Button
              variant="primary"
              onClick={() => {
                window.location.href = window.location.origin + '/platform/login';
              }}
              style={{ width: '100%' }}
            >
              Sign in again
            </Button>
          </div>
        </Card>
        <style>{`.signed-out-card { width: 100%; max-width: 400px; padding: 32px; }`}</style>
      </div>
    );
  }

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