"use client";

import { useState } from "react";
import { formDataToObject, useFormSubmit } from "@/lib/forms";

export interface SubscribeText {
  emailLabel: string;
  emailPlaceholder: string;
  phoneLabel: string;
  phonePlaceholder: string;
  orLabel: string;
  stateLabel: string;
  nationwideLabel: string;
  pickStatesText: string;
  needStateText: string;
  submitLabel: string;
  sendingLabel: string;
  needOneText: string;
  noteHtml: string;
  successText: string;
  source: string;
}

/**
 * "Subscribe to notices": a reader leaves an email address, a phone number,
 * or both, and chooses the whole country or one or more states, to hear
 * about new Certificate of Need notices. At least one way to reach them is
 * required. Posts to the CMS form given by `formKey`; Aggie lists the
 * subscribers under Website, Subscribers. On a statewide edition that state
 * starts ticked. Sends `scope` ("Nationwide" or "States") and `states`
 * (the ticked names, comma separated).
 */
export default function SubscribeForm({
  formKey,
  text,
  states,
  defaultState
}: {
  formKey: string;
  text: SubscribeText;
  states: string[];
  defaultState?: string;
}) {
  const { state, error, send } = useFormSubmit(formKey);
  const [missing, setMissing] = useState(false);
  const [nationwide, setNationwide] = useState(!defaultState);
  const [picked, setPicked] = useState<string[]>(defaultState ? [defaultState] : []);
  const [noState, setNoState] = useState(false);
  const toggle = (name: string) => setPicked((p) => (p.includes(name) ? p.filter((x) => x !== name) : [...p, name]));

  if (state === "done") {
    return (
      <div className="subscribe-success" role="status">
        {text.successText}
      </div>
    );
  }

  const onSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const data = formDataToObject(e.currentTarget);
    if (data._hp) return; // honeypot
    delete data._hp;
    data.email = (data.email || "").trim();
    data.phone = (data.phone || "").trim();
    if (!data.email && !data.phone) {
      setMissing(true);
      e.currentTarget.querySelector<HTMLInputElement>("input[name=email]")?.focus();
      return;
    }
    setMissing(false);
    if (!nationwide && picked.length === 0) {
      setNoState(true);
      return;
    }
    setNoState(false);
    delete data.pick;
    delete data.nationwide;
    const chosen = states.filter((n) => picked.includes(n));
    await send({ ...data, scope: nationwide ? "Nationwide" : "States", states: nationwide ? "All states and territories" : chosen.join(", "), source: text.source });
  };

  return (
    <form className="subscribe-form" onSubmit={onSubmit} noValidate={false}>
      <input type="text" name="_hp" tabIndex={-1} autoComplete="off" style={{ position: "absolute", left: -9999 }} aria-hidden="true" />
      <div className="subscribe-ways">
        <label className="subscribe-field">
          <span>{text.emailLabel}</span>
          <input type="email" name="email" autoComplete="email" placeholder={text.emailPlaceholder} aria-describedby="subscribe-need" />
        </label>
        <span className="subscribe-or" aria-hidden="true">
          {text.orLabel}
        </span>
        <label className="subscribe-field">
          <span>{text.phoneLabel}</span>
          <input type="tel" name="phone" autoComplete="tel" placeholder={text.phonePlaceholder} aria-describedby="subscribe-need" />
        </label>
      </div>
      <fieldset className="subscribe-scope">
        <legend>{text.stateLabel}</legend>
        <label className="subscribe-check subscribe-nationwide">
          <input type="checkbox" name="nationwide" checked={nationwide} onChange={(e) => setNationwide(e.target.checked)} />
          <span>{text.nationwideLabel}</span>
        </label>
        {!nationwide && (
          <>
            <p className="subscribe-pick-text">{text.pickStatesText}</p>
            <div className="subscribe-states">
              {states.map((n) => (
                <label key={n} className="subscribe-check">
                  <input type="checkbox" name="pick" value={n} checked={picked.includes(n)} onChange={() => toggle(n)} />
                  <span>{n}</span>
                </label>
              ))}
            </div>
            {noState && (
              <p className="subscribe-need is-missing" role="alert">
                {text.needStateText}
              </p>
            )}
          </>
        )}
      </fieldset>
      <p id="subscribe-need" className={`subscribe-need${missing ? " is-missing" : ""}`} role={missing ? "alert" : undefined}>
        {text.needOneText}
      </p>
      <button type="submit" className="btn-primary" disabled={state === "sending"}>
        {state === "sending" ? text.sendingLabel : text.submitLabel}
      </button>
      {text.noteHtml && <p className="subscribe-note" dangerouslySetInnerHTML={{ __html: text.noteHtml }} />}
      {state === "error" && error && (
        <p className="subscribe-error" role="alert">
          {error}
        </p>
      )}
    </form>
  );
}
