"use client";

/**
 * The website's inquiry forms (Contact page, Home page, Media & Insights): the same
 * <form> markup as before, now sent to POST /public/inquiries (API reference: "How
 * inquiry forms work"). The fields stay server-rendered children; this only reads them.
 *
 * - Sending keeps the design's feedback: the button says "Sending…", then
 *   "✓ Message Sent" for 3 seconds, and the form is cleared.
 * - Problems are listed under the button and the fields concerned are outlined.
 * - Requests go through this site's /api/v1 proxy, which passes the visitor's IP on
 *   (X-Forwarded-For), so the API's limit of 5 per 10 minutes is per visitor.
 */
import { useRef, useState, type FormEvent, type ReactNode } from "react";

export type InquiryPage = "contact" | "home" | "media-insights";

/** API field → the form's input name, per form. */
const FIELDS: Record<InquiryPage, Record<string, string>> = {
  contact: { name: "name", email: "email", inquiryType: "inquiry_type", meetingDate: "meeting_date", meetingTime: "meeting_time" },
  home: { name: "name", email: "email", phone: "phone", message: "message" },
  // The design asks for the media outlet / company only: it is sent as the name too.
  "media-insights": { name: "company", company: "company", email: "email", inquiryType: "inquiry", message: "message" },
};

const MESSAGES: Record<string, string> = {
  name: "Please enter your name (at least 2 characters).",
  company: "Please enter your media outlet or company name (at least 2 characters).",
  email: "Please enter a valid email address.",
  phone: "Please enter a valid phone number.",
  inquiryType: "Please choose an inquiry type.",
  meetingDate: "Please pick a meeting date from the list.",
  meetingTime: "Please pick a meeting time from the list.",
  message: "Your message is too long (3000 characters at most).",
};
const GENERIC = "Something went wrong. Please try again.";
const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

type Problem = { field: string | null; text: string };

export function InquiryForm({ page, className, children }: { page: InquiryPage; className: string; children: ReactNode }) {
  const ref = useRef<HTMLFormElement>(null);
  const [problems, setProblems] = useState<string[]>([]);
  const sending = useRef(false);

  const input = (name: string) => ref.current?.elements.namedItem(name) as HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement | null;
  const value = (name: string) => input(name)?.value.trim() ?? "";

  /** Outline the fields concerned (cleared when the visitor edits them) and list the messages. */
  const show = (list: Problem[]) => {
    const form = ref.current;
    if (!form) return;
    form.querySelectorAll("[aria-invalid]").forEach((el) => el.removeAttribute("aria-invalid"));
    let first: HTMLElement | null = null;
    for (const p of list) {
      const el = p.field ? input(FIELDS[page][p.field] ?? "") : null;
      if (!el) continue;
      el.setAttribute("aria-invalid", "true");
      el.addEventListener("input", () => el.removeAttribute("aria-invalid"), { once: true });
      el.addEventListener("change", () => el.removeAttribute("aria-invalid"), { once: true });
      first ??= el;
    }
    setProblems([...new Set(list.map((p) => p.text))]);
    first?.focus();
  };

  /** The body for POST /public/inquiries, or the problems found before sending. */
  const read = (): { body: Record<string, unknown> } | { problems: Problem[] } => {
    const f = FIELDS[page];
    const found: Problem[] = [];
    const name = value(f.name);
    const email = value(f.email);
    if (name.length < 2) found.push({ field: "name", text: page === "media-insights" ? MESSAGES.company : MESSAGES.name });
    if (!EMAIL.test(email)) found.push({ field: "email", text: MESSAGES.email });
    // A dropdown shows only when the page has options; it is required when shown.
    if (f.inquiryType && input(f.inquiryType) && !value(f.inquiryType)) found.push({ field: "inquiryType", text: MESSAGES.inquiryType });
    if (found.length) return { problems: found };

    const body: Record<string, unknown> = { page, name, email };
    for (const key of ["company", "inquiryType", "meetingDate", "meetingTime", "message"]) {
      const v = f[key] ? value(f[key]) : "";
      if (v) body[key] = v;
    }
    if (f.phone) {
      const phone = value(f.phone);
      // The design shows a fixed country code in front of the number.
      const code = ref.current?.querySelector(".phone-prefix")?.textContent?.trim() ?? "";
      if (phone) body.phone = phone.startsWith("+") || phone.startsWith("00") ? phone : `${code} ${phone}`.trim();
    }
    const lang = document.documentElement.lang;
    if (lang) body.lang = lang;
    body.pageUrl = window.location.pathname;
    return { body };
  };

  /** The design's button feedback, keeping the button's own text nodes to put back. */
  const button = () => {
    const btn = ref.current?.querySelector<HTMLButtonElement>(".btn-submit-form");
    const saved = btn ? Array.from(btn.childNodes) : [];
    return {
      busy() {
        if (!btn) return;
        btn.replaceChildren("Sending…");
        btn.disabled = true;
        btn.style.opacity = ".7";
      },
      restore() {
        if (!btn) return;
        btn.replaceChildren(...saved);
        btn.disabled = false;
        btn.style.background = "";
        btn.style.opacity = "1";
      },
      sent(done: () => void) {
        if (!btn) return done();
        btn.replaceChildren("✓ Message Sent");
        btn.style.background = "var(--teal-600)";
        btn.style.opacity = "1";
        setTimeout(() => {
          this.restore();
          done();
        }, 3000);
      },
    };
  };

  const submit = async (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    if (sending.current) return;
    const r = read();
    if ("problems" in r) return show(r.problems);
    show([]);
    sending.current = true;
    const b = button();
    b.busy();
    try {
      const res = await fetch("/api/v1/public/inquiries", {
        method: "POST",
        headers: { "Content-Type": "application/json", Accept: "application/json" },
        body: JSON.stringify(r.body),
      });
      if (res.ok) {
        ref.current?.reset();
        b.sent(() => (sending.current = false));
        return;
      }
      b.restore();
      sending.current = false;
      if (res.status === 429) return show([{ field: null, text: "Too many requests, please try again in a few minutes." }]);
      const data = await res.json().catch(() => null);
      const errors: string[] = Array.isArray(data?.errors) ? data.errors : [];
      show(errors.length ? errors.map((m) => problemOf(m, page)) : [{ field: null, text: GENERIC }]);
    } catch {
      b.restore();
      sending.current = false;
      show([{ field: null, text: "Couldn't send your message. Please check your connection and try again." }]);
    }
  };

  return (
    <form ref={ref} className={className} noValidate onSubmit={submit}>
      {children}
      {problems.length > 0 && (
        <div role="alert" className="inquiry-form-errors text-[13px] leading-[1.5] text-[#c62828]">
          {problems.map((p, i) => (
            <p key={i}>{p}</p>
          ))}
        </div>
      )}
    </form>
  );
}

/** An API validation message → a visitor-friendly one (and the field it concerns). */
function problemOf(msg: string, page: InquiryPage): Problem {
  if (/is not available/i.test(msg)) return { field: null, text: "This form isn't available right now. Please email or call us instead." };
  const field = /^(name|email|phone|company|inquiryType|meetingDate|meetingTime|message)\b/.exec(msg)?.[1];
  if (!field) return { field: null, text: GENERIC };
  return { field, text: page === "media-insights" && field === "name" ? MESSAGES.company : MESSAGES[field] };
}
