import { type FormEvent, useRef, useState } from 'react';
import './Login.css';

type Props = {
  onLogin: (username: string, password: string) => void;
  loginError?: string;
};

const Login: React.FC<Props> = ({ onLogin, loginError }) => {
  const [validationError, setValidationError] = useState<string>('');

  const usernameRef = useRef<HTMLInputElement>(null);
  const passwordRef = useRef<HTMLInputElement>(null);

  function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    let error = 'Bitte geben Sie einen Benutzernamen und ein Passwort ein.';
    const username = usernameRef.current!.value;
    const password = passwordRef.current!.value;
    if (username && password) {
      error = '';
      onLogin(username, password);
    }
    setValidationError(error);
  }

  return (
    <form onSubmit={handleSubmit} className="Login">
      {loginError && <div className="error">{loginError}</div>}
      {validationError && <div className="error">{validationError}</div>}
      <div>
        <label>
          Benutzername:
          <input type="text" ref={usernameRef} />
        </label>
      </div>
      <div>
        <label>
          Passwort:
          <input type="password" ref={passwordRef} />
        </label>
      </div>
      <button type="submit">anmelden</button>
    </form>
  );
};

export default Login;
