import { useMemo, useState } from "react";

function ContactPage() {
  const [formData, setFormData] = useState({
    name: "",
    email: "",
    message: ""
  });
  const [submitted, setSubmitted] = useState(false);

  const errors = useMemo(() => {
    const validationErrors = {};

    if (!formData.name.trim()) {
      validationErrors.name = "A nev megadasa kotelezo.";
    }

    if (!formData.email.trim()) {
      validationErrors.email = "Az email cim megadasa kotelezo.";
    } else if (!/^\S+@\S+\.\S+$/.test(formData.email)) {
      validationErrors.email = "Adj meg ervenyes email cimet.";
    }

    if (formData.message.trim().length < 10) {
      validationErrors.message = "Az uzenet legalabb 10 karakter legyen.";
    }

    return validationErrors;
  }, [formData]);

  const isValid = Object.keys(errors).length === 0;

  function handleChange(event) {
    const { name, value } = event.target;
    setFormData((current) => ({ ...current, [name]: value }));
    setSubmitted(false);
  }

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

    if (!isValid) {
      return;
    }

    setSubmitted(true);
  }

  return (
    <section className="panel">
      <h2>Kapcsolat</h2>
      <p>Kontrollalt urlap peldaval, valos ideju validacioval.</p>

      <form className="contact-form" onSubmit={handleSubmit} noValidate>
        <label htmlFor="name">Nev</label>
        <input id="name" name="name" value={formData.name} onChange={handleChange} />
        {errors.name && <p className="error-message">{errors.name}</p>}

        <label htmlFor="email">Email</label>
        <input id="email" name="email" value={formData.email} onChange={handleChange} />
        {errors.email && <p className="error-message">{errors.email}</p>}

        <label htmlFor="message">Uzenet</label>
        <textarea id="message" name="message" rows="5" value={formData.message} onChange={handleChange} />
        {errors.message && <p className="error-message">{errors.message}</p>}

        <button type="submit" disabled={!isValid}>
          Kuldes
        </button>

        {submitted && <p className="success-message">Sikeres kuldes (demo).</p>}
      </form>
    </section>
  );
}

export default ContactPage;
