"use client";

import Link from "next/link";
import { useId, useState, type FormEvent } from "react";
import { Button } from "@/components/Button";
import { ApiError } from "@/lib/api";
import { newsletterApi } from "@/lib/api/newsletter";

type FormState = "idle" | "submitting" | "success" | "already" | "invalid" | "error";

export function NewsletterSection() {
  const emailId = useId();
  const statusId = useId();

  const [email, setEmail] = useState("");
  const [state, setState] = useState<FormState>("idle");
  const [message, setMessage] = useState<string | null>(null);

  const busy = state === "submitting";

  function clearFeedback() {
    if (state === "invalid" || state === "error" || state === "success" || state === "already") {
      setState("idle");
      setMessage(null);
    }
  }

  async function onSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    if (busy) return;

    const trimmed = email.trim();
    if (!trimmed || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(trimmed)) {
      setState("invalid");
      setMessage("Enter a valid email address.");
      return;
    }

    setState("submitting");
    setMessage(null);

    try {
      const result = await newsletterApi.subscribe(trimmed, true);
      setState(result.status === "already_subscribed" ? "already" : "success");
      setMessage(result.message);
      setEmail("");
    } catch (error) {
      if (error instanceof ApiError && error.isValidation) {
        const emailError = error.errors.email?.[0];
        const consentError = error.errors.marketing_consent?.[0];
        setState("invalid");
        setMessage(emailError ?? consentError ?? error.message);
        return;
      }

      setState("error");
      setMessage(
        error instanceof ApiError
          ? error.message
          : "Unable to complete newsletter signup. Please try again later.",
      );
    }
  }

  return (
    <section
      className="border-t border-white/10 bg-primary text-white"
      aria-labelledby="newsletter-heading"
    >
      <div className="mx-auto grid w-full max-w-page gap-8 px-4 py-14 md:grid-cols-[minmax(0,1.1fr)_minmax(0,0.9fr)] md:items-end md:gap-12 md:px-6 md:py-16">
        <div className="max-w-[36rem]">
          <p className="text-[0.72rem] font-medium tracking-[0.16em] text-white/45 uppercase">
            Newsletter
          </p>
          <h2
            id="newsletter-heading"
            className="mt-3 text-[clamp(1.85rem,3.4vw,2.6rem)] leading-[1.08] tracking-[-0.03em] text-white"
          >
            Good things are happening.
          </h2>
          <p className="mt-3.5 max-w-[42ch] text-[1.02rem] leading-relaxed text-white/72">
            Get creator insights, brand opportunities, and the latest updates from Postvertise.
          </p>
        </div>

        <div>
          <form className="space-y-3.5" onSubmit={onSubmit} noValidate aria-describedby={statusId}>
            <p
              id={statusId}
              role="status"
              aria-live="polite"
              className={
                message
                  ? state === "error" || state === "invalid"
                    ? "text-[0.86rem] text-[#FDBA74]"
                    : "text-[0.86rem] text-white/80"
                  : "sr-only"
              }
            >
              {message ?? ""}
            </p>

            <p className="text-[0.95rem] leading-snug text-white/78">
              Drop your email and we&apos;ll keep you in the loop.
            </p>

            <div className="flex flex-col gap-2.5 min-[520px]:flex-row min-[520px]:items-stretch">
              <label className="sr-only" htmlFor={emailId}>
                Email address
              </label>
              <input
                id={emailId}
                name="email"
                type="email"
                autoComplete="email"
                inputMode="email"
                required
                disabled={busy}
                value={email}
                onChange={(event) => {
                  setEmail(event.target.value);
                  clearFeedback();
                }}
                placeholder="you@company.com"
                aria-invalid={state === "invalid" ? true : undefined}
                aria-describedby={message ? statusId : undefined}
                className="h-11 w-full min-w-0 flex-1 rounded-pv border border-white/18 bg-white/95 px-3.5 text-sm text-primary placeholder:text-ink-40 outline-none focus:outline-none disabled:opacity-70"
              />
              <Button
                type="submit"
                disabled={busy}
                className="h-11 w-full shrink-0 min-[520px]:w-auto"
                aria-busy={busy || undefined}
              >
                {busy ? "Subscribing…" : "Subscribe"}
              </Button>
            </div>

            <p className="text-[0.82rem] leading-snug text-white/62">
              By subscribing, you agree to receive marketing emails from Postvertise. See our{" "}
              <Link
                href="/privacy"
                className="underline decoration-white/35 underline-offset-2 transition-colors hover:text-white hover:decoration-white"
              >
                Privacy Policy
              </Link>
              . You can unsubscribe anytime. Transactional account emails are separate.
            </p>
          </form>
        </div>
      </div>
    </section>
  );
}
