"use client";

import styles from "./Newsletter.module.css";
import Badge from "@/components/Badge/Badge";
import { FormEvent, useRef, useState } from "react";
// @ts-ignore
import jsonp from "jsonp";

const Newsletter = () => {
  const formRef = useRef<HTMLFormElement>(null);
  const [email, setEmail] = useState<string>("");
  const [status, setStatus] = useState("");
  const [error, setError] = useState(false);
  const [value, setValue] = useState("");

  const Status = {
    idle: "IDLE",
    loading: "LOADING",
    success: "SUCCESS",
    error: "ERROR",
  };

  const toQueryString = (params: { [key: string]: any }) =>
    Object.keys(params)
      .map((key) => key + "=" + params[key])
      .join("&");

  const doSubmission = async () => {
    let payload = {
      EMAIL: email,
      subscribe: "Subscribe",
    };

    return jsonp(
      `${process.env.NEXT_PUBLIC_MAILCHIMP_LIST_URL}&${toQueryString(payload)}`,
      { param: "c" },
      // @ts-ignore
      (err, data) => {
        if (err) {
          setStatus(Status.error);
          setError(err);
        } else if (data.result !== "success") {
          setStatus(Status.error);
          setError(data.msg);
        } else {
          setStatus(Status.success);
          setValue(data.msg);
          setEmail("");
        }
      },
    );
  };

  const renderMessage = () => {
    let msg = "";

    if (status === Status.loading) return <></>;

    if (status === Status.error) {
      msg = "That didn't work, please try again later.";
    }

    if (value.toLowerCase().includes("already subscribed")) {
      msg = "It looks like you’re already subscribed with this email address.";
    }

    if (value) {
      msg =
        "Thank you for signing up. Almost finished, please click the link in the email we just sent you.";
    }

    if (!msg) return <></>;

    return <small className={styles.newsletter__msg}>{msg}</small>;
  };

  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault();

    if (!formRef.current) return;

    if (formRef.current.checkValidity()) {
      await doSubmission();
    } else {
      formRef.current.reportValidity();
    }
  };

  return (
    <>
      <form
        ref={formRef}
        method="POST"
        className={styles.newsletter}
        onSubmit={handleSubmit}
      >
        <input
          type="email"
          name="newsletter-email"
          autoComplete="off"
          autoCorrect="off"
          autoCapitalize="off"
          spellCheck={false}
          required
          inputMode="email"
          data-lpignore="true"
          data-form-type="other" // Helps with Safari
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          className={styles.newsletter__input}
          placeholder="Email address"
        />
        <button
          type="submit"
          className={styles.newsletter__submit}
          aria-label="Signup"
          disabled={status === Status.loading}
        >
          <Badge
            aria-label="Submit newsletter"
            onClick={async (e: MouseEvent) => {
              e.preventDefault();

              // @ts-ignore
              await handleSubmit(e);
            }}
          >
            <svg
              xmlns="http://www.w3.org/2000/svg"
              height="24"
              viewBox="0 -960 960 960"
              width="24"
            >
              <path d="M647-440H160v-80h487L423-744l57-56 320 320-320 320-57-56 224-224Z" />
            </svg>
          </Badge>
        </button>
      </form>
      {renderMessage()}
    </>
  );
};

export default Newsletter;
