import { type FormEvent, useEffect, useState } from 'react';
import { Navigate } from 'react-router';
import { useAuthStore } from './auth-store';
import { api } from '../api/client';
import { Card, Input, Button, Alert, FormField } from '@cameleer/design-system';

interface OidcInfo {
  clientId: string;
  authorizationEndpoint: string;
}

export function LoginPage() {
  const { isAuthenticated, login, loading, error } = useAuthStore();
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [oidc, setOidc] = useState<OidcInfo | null>(null);
  const [oidcLoading, setOidcLoading] = useState(false);

  useEffect(() => {
    api.GET('/auth/oidc/config')
      .then(({ data }) => {
        if (data?.authorizationEndpoint && data?.clientId) {
          setOidc({ clientId: data.clientId, authorizationEndpoint: data.authorizationEndpoint });
          if (data.endSessionEndpoint) {
            localStorage.setItem('cameleer-oidc-end-session', data.endSessionEndpoint);
          }
        }
      })
      .catch(() => {});
  }, []);

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

  const handleSubmit = (e: FormEvent) => {
    e.preventDefault();
    login(username, password);
  };

  const handleOidcLogin = () => {
    if (!oidc) return;
    setOidcLoading(true);
    const redirectUri = `${window.location.origin}/oidc/callback`;
    const params = new URLSearchParams({
      response_type: 'code',
      client_id: oidc.clientId,
      redirect_uri: redirectUri,
      scope: 'openid email profile',
    });
    window.location.href = `${oidc.authorizationEndpoint}?${params}`;
  };

  return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: '100vh', background: 'var(--surface-ground)' }}>
      <Card>
        <form onSubmit={handleSubmit} style={{ padding: '2rem', minWidth: 360 }}>
          <div style={{ textAlign: 'center', marginBottom: '1.5rem' }}>
            <h1 style={{ fontSize: '1.5rem', fontWeight: 600 }}>cameleer3</h1>
            <p style={{ color: 'var(--text-secondary)', marginTop: '0.25rem', fontSize: '0.875rem' }}>
              Sign in to access the observability dashboard
            </p>
          </div>

          {oidc && (
            <>
              <Button variant="secondary" onClick={handleOidcLogin} disabled={oidcLoading} style={{ width: '100%', marginBottom: '1rem' }}>
                {oidcLoading ? 'Redirecting...' : 'Sign in with SSO'}
              </Button>
              <div style={{ display: 'flex', alignItems: 'center', gap: '0.75rem', margin: '1rem 0' }}>
                <hr style={{ flex: 1, border: 'none', borderTop: '1px solid var(--border)' }} />
                <span style={{ color: 'var(--text-tertiary)', fontSize: '0.75rem' }}>or</span>
                <hr style={{ flex: 1, border: 'none', borderTop: '1px solid var(--border)' }} />
              </div>
            </>
          )}

          <FormField label="Username">
            <Input
              value={username}
              onChange={(e) => setUsername(e.target.value)}
              autoFocus
              autoComplete="username"
            />
          </FormField>

          <FormField label="Password">
            <Input
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              autoComplete="current-password"
            />
          </FormField>

          <Button variant="primary" disabled={loading || !username || !password} style={{ width: '100%', marginTop: '0.5rem' }}>
            {loading ? 'Signing in...' : 'Sign In'}
          </Button>

          {error && <div style={{ marginTop: '1rem' }}><Alert variant="error">{error}</Alert></div>}
        </form>
      </Card>
    </div>
  );
}
