import React, { useState } from "react";
import emailjs from "@emailjs/browser";
import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import { useTranslation } from "react-i18next";
import PhoneInput, { formatPhoneNumber, parsePhoneNumber } from "react-phone-number-input";
import 'react-phone-number-input/style.css'
import "./ContactForm.css";

const ContactForm = () => {
  const { t } = useTranslation();
  const [phone, setPhone] = useState<string | undefined>(undefined);

  const notify = () => {
    toast.success(t("contact.toasts.success"));
  };

  const errorToast = () => {
    toast.error(t("contact.toasts.error"));
  };

  const emptyForm = () => {
    toast.warning(t("contact.toasts.empty"));
  };
  
  const invalidCountryCode = () => {
    toast.error(t("contact.toasts.invalidCountryCode"));
  };

  const sendEmail = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();

    let isEmpty = Array.from(e.currentTarget.elements).some(
      (input) =>
        (input as HTMLInputElement).type !== "submit" &&
        (input as HTMLInputElement).value.trim() === ""
    );

    if (isEmpty || !phone) { // Check if phone is also empty
      emptyForm();
      return;
    }

    let parsedPhone = parsePhoneNumber(phone);
    let countryCode = parsedPhone?.countryCallingCode;

    if (!countryCode) {
      invalidCountryCode();
      return;
    }

    // Append phone number to the form
    const phoneInput = document.createElement("input");
    phoneInput.setAttribute("type", "hidden");
    phoneInput.setAttribute("value", `+${countryCode} ${formatPhoneNumber(phone)}`);
    e.currentTarget.appendChild(phoneInput);

    emailjs
      .sendForm("service_o7kxotj", "template_f30zlog", e.currentTarget, {
        publicKey: "vcSOwPedqkRH3nmr9",
      })
      .then(
        (result) => {
          console.log(result.text);
          notify();
        },
        (error) => {
          console.log(error.text);
          errorToast();
        }
      );

    e.currentTarget.reset();
    setPhone(undefined); // Reset phone state
  };

  return (
    <div className="mt-10 mx-5 lg:mx-0 flex justify-center items-center">
      <form onSubmit={sendEmail} className="w-full md:w-auto">
        <div className="flex flex-col md:flex-row md:gap-3">
          <input
            className="form-input flex-1"
            type="text"
            name="user_name"
            placeholder={t("contact.form.name")}
          />
          <input
            className="form-input flex-1"
            type="email"
            name="user_email"
            placeholder={t("contact.form.email")}
          />
        </div>
        <div className="flex flex-col md:flex-row md:gap-3">
          <input
            className="form-input md:w-1/2"
            type="text"
            name="user_company"
            placeholder={t("contact.form.company")}
          />
          <div className="md:w-1/2 flex items-center">
            <PhoneInput 
              defaultCountry="PT"
              placeholder={t("contact.form.phone")}
              className="form-input placeholder-white w-full"
              value={phone}
              onChange={setPhone}
              inputProps={{
                name: "user_phone",
                required: true,
              }}
            />
          </div>
        </div>
        <div className="flex flex-col">
          <input
            className="form-input"
            type="text"
            name="user_question"
            placeholder={t("contact.form.question")}
          ></input>

          <input
            className="form-input"
            name="user_reference"
            placeholder={t("contact.form.reference")}
          ></input>
        </div>

        <div className="flex mt-5 mb-10 lg:mt-12 mx-10 sm:mx-40 rounded-full bg-gradient-to-br from-gold-light to-gold-dark p-0.5 shadow-lg">
          <button
            type="submit"
            className="flex-1 font-medium md:px-8 py-3 text-2xl md:text-3xl bg-gradient-to-br from-custom-bglight to-custom-bgdark rounded-full hover:bg-transparent hover:from-transparent hover:to-transparent transition duration-500"
          >
            {t("contact.form.button")}
          </button>
        </div>

        <ToastContainer
          position="top-center"
          autoClose={5000}
          hideProgressBar
          newestOnTop={false}
          closeOnClick
          rtl={false}
          pauseOnFocusLoss
          draggable
          pauseOnHover
          theme="dark"
        />
      </form>
    </div>
  );
};

export default ContactForm;
