import { type FormEvent, useEffect, useState } from 'react';
import { Navigate } from 'react-router';
import { useAuthStore } from './auth-store';
import { api } from '../api/client';
import styles from './LoginPage.module.css';

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 className={styles.page}>
      <form className={styles.card} onSubmit={handleSubmit}>
        <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>
        <div className={styles.subtitle}>Sign in to access the observability dashboard</div>

        {oidc && (
          <>
            <button
              className={styles.ssoButton}
              type="button"
              onClick={handleOidcLogin}
              disabled={oidcLoading}
            >
              {oidcLoading ? 'Redirecting...' : 'Sign in with SSO'}
            </button>
            <div className={styles.divider}>
              <span className={styles.dividerText}>or</span>
            </div>
          </>
        )}

        <div className={styles.field}>
          <label className={styles.label}>Username</label>
          <input
            className={styles.input}
            type="text"
            value={username}
            onChange={(e) => setUsername(e.target.value)}
            autoFocus
            autoComplete="username"
          />
        </div>

        <div className={styles.field}>
          <label className={styles.label}>Password</label>
          <input
            className={styles.input}
            type="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            autoComplete="current-password"
          />
        </div>

        <button className={styles.submit} type="submit" disabled={loading || !username || !password}>
          {loading ? 'Signing in...' : 'Sign In'}
        </button>

        {error && <div className={styles.error}>{error}</div>}
      </form>
    </div>
  );
}
