import { useState, FormEvent } from 'react';
import { useAuth } from '../hooks/useAuth';
import { sendAuthResponse } from '../utils/iframe';

export function LoginForm(): JSX.Element {
  const { keyPair, isLoading, createAuthResponse } = useAuth();
  const [isAuthenticating, setIsAuthenticating] = useState(false);

  const handleSubmit = (e: FormEvent<HTMLFormElement>): void => {
    e.preventDefault();
    void (async (): Promise<void> => {
      if (keyPair === null || isLoading) {
        return;
      }

      setIsAuthenticating(true);
      try {
        const response = createAuthResponse();
        if (response !== null) {
          sendAuthResponse(response);
        } else {
          console.error('Failed to create auth response');
        }
      } catch (error) {
        console.error('Authentication error:', error);
      } finally {
        setIsAuthenticating(false);
      }
    })();
  };

  if (isLoading) {
    return (
      <div role="status" aria-live="polite" aria-busy="true">
        Chargement...
      </div>
    );
  }

  return (
    <form onSubmit={handleSubmit} aria-label="Formulaire de connexion">
      <button
        type="submit"
        disabled={isAuthenticating || keyPair === null}
        aria-busy={isAuthenticating}
      >
        {isAuthenticating ? 'Authentification...' : 'Se connecter'}
      </button>
    </form>
  );
}
