const ReservationWidget = () => {

  const [formData, setFormData] = React.useState({
    name: "",
    contact: "",
    people: 2,
    date: "",
    time: "",
    sector: "vereda",
    comments: "",
  });
  const [errors, setErrors] = React.useState({});

  const validators = {
    name: (value) => (value.trim().length < 3 ? "Ingresá un nombre válido" : ""),
    contact: (value) =>
      /@/.test(value)
        ? /.+@.+\..+/.test(value)
          ? ""
          : "Email inválido"
        : value.replace(/[^0-9+ ]/g, "").length < 8
          ? "Ingresá un teléfono o email válido"
          : "",
    people: (value) => (value < 1 ? "Debe ser al menos 1" : value > 12 ? "Consultanos por grupos grandes" : ""),
    date: (value) => (!value ? "Seleccioná una fecha" : ""),
    time: (value) => (!value ? "Seleccioná un horario" : ""),
  };

  function handleChange(event) {
    const { name, value } = event.target;
    const newValue = name === "people" ? Number(value) : value;
    setFormData((prev) => ({ ...prev, [name]: newValue }));
    if (validators[name]) {
      setErrors((prev) => ({ ...prev, [name]: validators[name](newValue) }));
    }
  }

  function validateForm() {
    const nextErrors = {};
    Object.entries(validators).forEach(([field, validate]) => {
      const result = validate(formData[field]);
      if (result) {
        nextErrors[field] = result;
      }
    });
    setErrors(nextErrors);
    return Object.keys(nextErrors).length === 0;
  }

  function handleSubmit(event) {
    event.preventDefault();
    if (!validateForm()) return;
    // Formatear la fecha en formato argentino (dd/mm/aaaa)
    let fechaArg = formData.date;
    if (fechaArg && /^\d{4}-\d{2}-\d{2}$/.test(fechaArg)) {
      const [a, m, d] = fechaArg.split("-");
      fechaArg = `${d}/${m}/${a}`;
    } else {
      fechaArg = "[fecha]";
    }
    // Generar el mensaje de WhatsApp
    const message = `Hola Parrilla La Nueva Adelina, quiero reservar para ${formData.people} personas el ${fechaArg} a las ${formData.time || "[hora]"} en el sector ${formData.sector}.\nNombre: ${formData.name}\nContacto: ${formData.contact}\nComentarios: ${formData.comments}`;
    const url = `https://wa.me/5491132907617?text=${encodeURIComponent(message)}`;
    window.open(url, "_blank");
  }

  return (
    <div className="reservation-widget">
      <form className="reservation-widget__form" onSubmit={handleSubmit} noValidate>
        <div className="reservation-widget__grid">
          <div>
            <label htmlFor="reservation-name" className="form-label">Nombre completo*</label>
            <input
              id="reservation-name"
              className="form-control"
              name="name"
              value={formData.name}
              onChange={handleChange}
              placeholder="Ej. Juan Pérez"
              autoComplete="name"
              required
            />
            {errors.name && <p className="error-text mt-1">{errors.name}</p>}
          </div>
          <div>
            <label htmlFor="reservation-contact" className="form-label">Teléfono o email*</label>
            <input
              id="reservation-contact"
              className="form-control"
              name="contact"
              value={formData.contact}
              onChange={handleChange}
              placeholder="Ej. 11 3290 7617"
              autoComplete="tel"
              required
            />
            {errors.contact && <p className="error-text mt-1">{errors.contact}</p>}
          </div>
          <div>
            <label htmlFor="reservation-people" className="form-label">Personas*</label>
            <input
              id="reservation-people"
              className="form-control"
              name="people"
              type="number"
              min="1"
              max="12"
              value={formData.people}
              onChange={handleChange}
              required
            />
            {errors.people && <p className="error-text mt-1">{errors.people}</p>}
          </div>
          <div>
            <label htmlFor="reservation-date" className="form-label">Fecha*</label>
            <input
              id="reservation-date"
              className="form-control"
              name="date"
              type="date"
              value={formData.date}
              onChange={handleChange}
              required
            />
            {errors.date && <p className="error-text mt-1">{errors.date}</p>}
          </div>
          <div>
            <label htmlFor="reservation-time" className="form-label">Horario*</label>
            <input
              id="reservation-time"
              className="form-control"
              name="time"
              type="time"
              value={formData.time}
              onChange={handleChange}
              required
            />
            {errors.time && <p className="error-text mt-1">{errors.time}</p>}
          </div>
          <div>
            <label htmlFor="reservation-sector" className="form-label">Sector*</label>
            <select
              id="reservation-sector"
              className="form-select"
              name="sector"
              value={formData.sector}
              onChange={handleChange}
            >
              <option value="vereda">Vereda</option>
              <option value="salon">Salón</option>
              <option value="deck">Deck</option>
              <option value="patio">Patio</option>
            </select>
          </div>
        </div>

        <div>
          <label htmlFor="reservation-comments" className="form-label">Comentarios</label>
          <textarea
            id="reservation-comments"
            className="form-control"
            name="comments"
            rows="3"
            placeholder="Ej. Cumpleaños, celíacos, carro de bebé"
            value={formData.comments}
            onChange={handleChange}
          />
        </div>

        <div className="reservation-widget__actions">
          <button type="submit" className="btn btn-primary">
            Enviar por WhatsApp
          </button>
        </div>
      </form>
    </div>
  );
};

const reservationRoot = document.getElementById("reservation-widget-root");

if (reservationRoot) {
  const root = ReactDOM.createRoot(reservationRoot);
  root.render(<ReservationWidget />);
}

