import { type FormEvent, useRef, useState } from 'react';

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

const Login: React.FC<Props> = ({ onLogin }) => {
  const usernameRef = useRef<HTMLInputElement>(null);
  const passwordRef = useRef<HTMLInputElement>(null);

  const [errors, setErrors] = useState({ username: '', password: '' });

  function handleUsernameChange() {
    setErrors((prev) => ({
      ...prev,
      username:
        usernameRef.current?.value.trim() === ''
          ? 'Benutzername darf nicht leer sein'
          : '',
    }));
  }

  function handlePasswordChange() {
    setErrors((prev) => ({
      ...prev,
      password:
        (passwordRef.current?.value.length ?? 0) < 6
          ? 'Mindestens 6 Zeichen verwenden'
          : '',
    }));
  }

  function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    onLogin(usernameRef.current!.value, passwordRef.current!.value);
  }

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label>
          Benutzername:
          <input
            type="text"
            ref={usernameRef}
            onChange={handleUsernameChange}
          />
          {errors.username && <p>{errors.username}</p>}
        </label>
      </div>
      <div>
        <label>
          Passwort:
          <input
            type="password"
            ref={passwordRef}
            onChange={handlePasswordChange}
          />
          {errors.password && <p>{errors.password}</p>}
        </label>
      </div>
      <button type="submit">anmelden</button>
    </form>
  );
};

export default Login;
