import { useState } from 'react';

function Form() {
  const [enteredEmail, setEnteredEmail] = useState('');
  const [emailIsValid, setEmailIsValid] = useState(true);
  const [enteredPassword, setEnteredPassword] = useState('');
  const [passwordIsValid, setPasswordIsValid] = useState(true);

  function changeEmailHandler(event) {
    setEnteredEmail(event.target.value);
  }
  function changePasswordHandler(event) {
    setEnteredPassword(event.target.value);
  }

  function submitFormHandler(event) {
    event.preventDefault();

    const emailIsValid = enteredEmail.includes('@');
    const passwordIsValid = enteredPassword.trim().length >= 6;

    setEmailIsValid(emailIsValid);
    setPasswordIsValid(passwordIsValid);

    if (!emailIsValid || !passwordIsValid) {
      return;
    }

    // Wykonywanie operacji.
    console.log('Dane wejściowe są poprawne, formularz został wysłany!');
  }

  return (
    <form onSubmit={submitFormHandler}>
      <div>
        <label htmlFor="email" className={!emailIsValid && 'invalid'}>
          Adres e-mail
        </label>
        <input
          id="email"
          type="email"
          onChange={changeEmailHandler}
          className={!emailIsValid && 'invalid'}
        />
      </div>
      <div>
        <label htmlFor="password" className={!passwordIsValid && 'invalid'}>
          Hasło
        </label>
        <input
          id="password"
          type="password"
          onChange={changePasswordHandler}
          className={!passwordIsValid && 'invalid'}
        />
      </div>
      <button>Wyślij</button>
    </form>
  );
}

export default Form;
