"use client";

import { subscribeNewsletter } from "@/lib/actions/newsletter";
import { useFormAction } from "@/lib/forms/use-form-action";
import { validateNewsletter } from "@/lib/forms/validation";
import type { Dictionary } from "@/i18n/get-dictionary";
import { MailOutlineIcon } from "@/components/icons";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";

export function NewsletterForm({ t }: { t: Dictionary["footer"] }) {
  const { errors, onSubmit, onChange, pending, sent, failed } = useFormAction(subscribeNewsletter, validateNewsletter);
  const emailError = errors.email === "required" ? t.emailRequired : errors.email === "invalid" ? t.invalidEmail : undefined;

  return (
    <form onSubmit={onSubmit} onChange={onChange} noValidate className="relative">
      {/* Tablet (Figma 744): field on top, button under it. */}
      <div className="flex items-center gap-4 md:max-lg:flex-col md:max-lg:items-start md:max-lg:gap-2 lg:flex-wrap">
        <div className="relative min-w-0 flex-1 sm:max-w-[335px] md:max-lg:w-full">
          <Label htmlFor="newsletter-email" className="sr-only">
            {t.emailPlaceholder}
          </Label>
          <MailOutlineIcon className="pointer-events-none absolute start-3 top-1/2 size-[18px] -translate-y-1/2 text-placeholder-dark" />
          {/* Figma: white field on the footer, unlike the dark form fields */}
          <Input
            id="newsletter-email"
            type="email"
            name="email"
            required
            autoComplete="email"
            placeholder={t.emailPlaceholder}
            aria-invalid={emailError ? true : undefined}
            aria-describedby="newsletter-status"
            className="h-10 border-soft bg-white ps-[34px] text-text-dark placeholder:text-placeholder-dark hover:bg-white max-md:text-xs md:h-[49px] dark:bg-white"
          />
        </div>
        {/* Figma: 18px bold on a "normal" line → 47px tall, next to the 49px field. */}
        <Button type="submit" variant="brand" size="pill" disabled={pending} className="leading-[normal] max-lg:h-10 max-lg:text-sm max-md:px-3">
          {t.subscribe}
        </Button>
      </div>
      {/* Under the form, absolutely placed so a message doesn't change the footer height (Figma: 340px). */}
      <p id="newsletter-status" aria-live="polite" className="absolute top-full mt-2 text-sm">
        {emailError || failed ? (
          <span className="text-destructive">{emailError ?? t.subscribeFailed}</span>
        ) : (
          sent && <span className="text-accent-mint">{t.subscribed}</span>
        )}
      </p>
    </form>
  );
}
