import { useState } from "react";
import style from "./ThreeFormFields.module.css";
import PhoneInput from "react-phone-input-2";
import "react-phone-input-2/lib/style.css";

// Four field form with welcome mail
const ThreeFormFields = (props) => {
  let [name, setName] = useState(props.name);
  let [email, setEmail] = useState("");
  let [contact, setContact] = useState("");
  let [err, setErr] = useState("");
  let [success, setSuccess] = useState("");
  let [message, setMessage] = useState("");
  let [city, setCity] = useState("");
  let formName = props.formName;

  const handlePhoneChange = (value, country) => {
    setContact(
      `${country.dialCode}-${value.replace(`${country.dialCode}`, "")}`
    );
  };

  let handleSubmitMain = (e) => {
    e.preventDefault();
    saveForm(formName, name, email, contact, city, message);
  };
  function saveForm(formName, name, email, contact, city, message) {
    if (
      name === "" ||
      email === "" ||
      contact === "" ||
      city === "" ||
      message === ""
    ) {
      setErr("Fill all the fields!");
    } else {
      let reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
      //   let mobile = /^\d{10}$/;
      if (reg.test(email) === false) {
        // console.log('error')
      } else {
        let formData = new FormData();
        formData.append("formName", "Akademy_Website");
        // formData.append("business_type", "Teenybeans");
        formData.append("Name", name);
        formData.append("Email", email);
        formData.append("Phone", contact && contact.split("-")[1]);
        formData.append("country_code", contact && contact.split("-")[0]);
        formData.append("Details", city);
        formData.append("MessageDetails", message);
        formData.append("formName", formName);
        formData.append("business_type", "akademy");
        fetch("https://api.teenybeans.in/API/contactFormProcessor/v1/", {
          method: "POST",
          body: formData,
        })
          .then((res) => res.json())
          .then((json) => {
            // console.log(json);
            sendMail(
              "enquiry@beanstalkedu.com",
              formName,
              name,
              email,
              contact,
              city,
              message
            );
            sendMail(
              "teenybeans.info@gmail.com",
              formName,
              name,
              email,
              contact,
              city,
              message
            );
            sendWelcomeMail(email, name);
            setSuccess("Thank you for the information.");
            setName("");
            setEmail("");
            setCity("");
            setMessage("");
            setContact("");
            setErr("");
            props.setMsg(true);
          });
      }
    }
  }

  // Mailing functions
  function sendMail(sendEmail, formName, name, email, contact, city, message) {
    // ---------Mail sent-----------------
    let formData = new FormData();
    formData.append("sendMail", "true");
    formData.append("reciever", sendEmail);
    formData.append("sender", "aKadmy");
    formData.append("senderMail", "no-reply@teenybeans.in");
    formData.append(
      "subject",
      `aKadmy Website ${formName} Page Contact form fillup`
    );
    formData.append(
      "message",
      `<html><body><p>New aKadmy Website ${formName} page form is filled up.</p><br><p>User Details:-</p><table><tr><th>Name:- </th><td>:- ${name} </td></tr><tr><th>Email:- </th><td>:- ${email} </td></tr><tr><th>Phone:- </th><td>:- ${contact} </td></tr><tr><th>City:- </th><td>:- ${city} </td></tr><tr><th>Message:- </th><td>:- ${message} </td></tr></table></body></html>`
    );
    fetch("https://mailapi.teenybeans.in/009/", {
      method: "POST",
      body: formData,
    })
      .then(function (response) {
        response.json().then(function (data) {});
      })
      .catch(function (err) {
        // console.log('Fetch Error :-S', err)
      });
  }

  function sendWelcomeMail(sendEmail, name) {
    // ---------Mail sent-----------------
    let formData = new FormData();
    formData.append("sendMail", "true");
    formData.append("reciever", sendEmail);
    formData.append("sender", "aKadmy");
    formData.append("senderMail", "no-reply@teenybeans.in");
    formData.append("subject", "Thanks for showing interest");
    formData.append(
      "message",
      `<html>
      <body style="background-color:#f5f8f5;padding:16px;">
      <div style="text-align:center">
        <a href="#"><img style="width:150px;" src="https://akadmyapp.com/assets/akademy_Logo.png"></a>
      </div>
      <div style="padding-top:16px;">Hey ${name}!</div>
      <div style="padding-top:16px;">Thank you for reaching out to us. We appreciate your interest in our platform and are excited to assist you with your inquiry.</div>
      <div style="padding-top:16px;">We are committed to empowering preschool educators by offering advanced AI-powered tools that improves learning outcomes of young learners.</div>
      <div style="padding-top:16px;">Please feel free to explore more about our offerings on our website or follow us on social media to stay updated on the latest from aKadmy. Our team will be in touch with you shortly.<div>
      <div style="padding-top:16px;">The future of early childhood education is here!</div>
      <div style="padding-top:16px;">Warm Regards,<br/>Team aKadmy</div>
      <div style="text-align:center"><p><b>Follow us</b><br><a href="https://www.facebook.com/get.aKadmy/" target="_blank"><img style="width:26px;margin-right:10px" src="https://iimtt.org/assets/img/fb.png" alt="Logo"></a><a href="https://www.instagram.com/akadmy.app/" target="_blank"><img style="width:26px;margin-right:10px" src="https://iimtt.org/assets/img/insta.png" alt="Logo"></a>
      <a href="https://www.linkedin.com/showcase/akadmyapp/" target="_blank"><img style="width:30px;" src="https://iimtt.org/assets/img/linkedin.png" alt="Logo"></a><br><hr><b>aKadmy</b><br>Buzzapp Technologies Sdn Bhd, 38, 3rd Floor, Jalan Radin Anum<br>Bandar Baru Sri Petaling, Kuala Lumpur, Wilayah Persekutuan, 57000<br>Malaysia<br/>© 2024 aKadmy All rights reserved.</p></div>
      </body>
      <html>
      `
    );
    fetch("https://mailapi.teenybeans.in/009/", {
      method: "POST",
      body: formData,
    })
      .then(function (response) {
        response.json().then(function (data) {});
      })
      .catch(function (err) {
        // console.log('Fetch Error :-S', err)
      });
  }

  return (
    <div className={style.form}>
      <form action="" onSubmit={handleSubmitMain}>
        {success ? (
          <div>
            <div>
              <img
                src="/assets/thank-you.webp"
                width={"100%"}
                height={"100%"}
                loading="lazy"
              />
            </div>
            <div>
              <h2 variant="heading3">Thank You !</h2>
              <p>Thank you for the information. Please check your mail!</p>
            </div>
          </div>
        ) : (
          <>
            {err && <p className={style.err_msg}>{err}</p>}
            <input
              type="text"
              placeholder="Your name"
              value={name}
              onChange={(e) => setName(e.target.value)}
            />
            <input
              type="text"
              placeholder="Email ID"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
            />
            <PhoneInput
              country={"my"}
              enableSearch={true}
              value={contact}
              onChange={handlePhoneChange}
              inputProps={{
                name: "phone",
                required: true,
              }}
              inputStyle={{ width: "100%" }}
              isValid={(value, country) => {
                // console.log({ value: value.length, country });
                if (value.length < 3) {
                  return true;
                } else if (value.length <= 9 || value.length > 14) {
                  return "Provide a valid phone number"; //  + value + ', ' + country.name;
                } else {
                  return true;
                }
              }}
              className={style.phn}
            />
            <input
              type="text"
              placeholder="City"
              value={city}
              onChange={(e) => setCity(e.target.value)}
            />
            <textarea
              type="text"
              placeholder="How can we help?"
              value={message}
              onChange={(e) => setMessage(e.target.value)}
            />
            <button type="submit" className="btn">
              submit
            </button>
          </>
        )}
      </form>
    </div>
  );
};

export default ThreeFormFields;
