"use client";

import { useActionState } from "react";
import { subscribeToNewsletter } from "@/app/actions/newsletter";
import type { NewsletterState } from "@/lib/validations/newsletter";
import { cn } from "@/lib/utils";

const initialState: NewsletterState = {};

/**
 * Formulaire d'inscription — écrit UNE fois, mis en scène par le bloc et par la
 * modale. Corriger la validation ou le message de succès se fait ici, et nulle
 * part ailleurs.
 *
 * `idPrefix` évite la collision d'identifiants quand le bloc et la modale
 * coexistent sur la même page : deux `id="newsletter-email"` casseraient
 * l'association `label`/`input` et donc la lecture d'écran.
 */
export function NewsletterForm({
  idPrefix,
  className,
  onSuccess,
}: {
  idPrefix: string;
  className?: string;
  onSuccess?: () => void;
}) {
  const [state, formAction, isPending] = useActionState(
    async (prev: NewsletterState, data: FormData) => {
      const next = await subscribeToNewsletter(prev, data);
      if (next.success) onSuccess?.();
      return next;
    },
    initialState,
  );

  const emailId = `${idPrefix}-email`;
  const errorId = `${idPrefix}-error`;

  if (state.success) {
    return (
      <p
        role="status"
        className={cn("text-sm font-medium text-orange-700", className)}
      >
        {state.message}
      </p>
    );
  }

  return (
    <form action={formAction} className={cn("w-full", className)}>
      <label htmlFor={emailId} className="sr-only">
        Adresse e-mail
      </label>

      <div className="flex flex-col gap-3 sm:flex-row">
        <input
          id={emailId}
          name="email"
          type="email"
          required
          autoComplete="email"
          placeholder="vous@entreprise.fr"
          disabled={isPending}
          aria-invalid={state.errors?.email ? true : undefined}
          aria-describedby={state.errors?.email ? errorId : undefined}
          className="min-w-0 flex-auto rounded-lg border border-slate-300 bg-white px-4 py-2.5 text-base text-slate-900 placeholder:text-slate-400 focus:border-orange-700 focus:outline-2 focus:outline-offset-2 focus:outline-orange-700 disabled:opacity-60 sm:text-sm"
        />

        {/* Honeypot : hors flux et hors tabulation, invisible pour l'humain. */}
        <input
          type="text"
          name="website"
          tabIndex={-1}
          autoComplete="off"
          aria-hidden="true"
          className="absolute left-[-9999px] h-0 w-0 opacity-0"
        />

        <button
          type="submit"
          disabled={isPending}
          className="shrink-0 rounded-lg bg-orange-600 px-5 py-2.5 text-sm font-semibold text-white transition-colors hover:bg-orange-800 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-orange-700 disabled:cursor-not-allowed disabled:opacity-60"
        >
          {isPending ? "Envoi…" : "S'abonner"}
        </button>
      </div>

      {state.errors?.email && (
        <p id={errorId} role="alert" className="mt-2 text-xs text-red-600">
          {state.errors.email[0]}
        </p>
      )}

      <p className="mt-3 text-xs leading-relaxed text-slate-500">
        Un e-mail de confirmation vous sera envoyé. Désinscription en un clic,
        à tout moment.
      </p>
    </form>
  );
}
