"use client";

import { useState } from "react";
import { isValidEmail } from "../lib/email";
import { ArrowRightIcon } from "./ArrowRightIcon";

/**
 * Replaces the (disabled) Add-to-cart button's spot once a product/variant
 * is out of stock — lets a visitor leave their email to be notified once
 * lib/jobs/sendBackInStockEmails.ts (Payload backend) sends the "it's
 * back" mail. Always shows the email input + submit control directly (no
 * extra click to reveal them).
 *
 * One input with the submit control embedded inside it (absolutely
 * positioned, not a layout sibling) — not a separate stacked button below
 * the input. A first version stacked input + full-width "Benachrichtigen"
 * button, which made an out-of-stock ProductCard.tsx visibly taller than
 * its in-stock siblings (two form rows vs. one button); shrinking that
 * stacked version's own padding was tried and reverted — the actual ask
 * was to keep every control's height untouched and make the CARD match
 * instead. Embedding the submit icon inside the input keeps this whole
 * control to exactly one row, given an explicit h-14 (3.5rem/56px) to
 * match AddToCartInlineButton's own "In den Warenkorb" button's actual
 * rendered height — that button isn't 56px from its py-3 padding alone,
 * its 1.875rem cart-icon image is the tallest thing in it, so matching
 * padding here wouldn't have matched height; a sold-out card now ends up
 * exactly as tall as an in-stock one.
 */
export function NotifyMeForm({ productId, variantName = "" }: { productId: number; variantName?: string }) {
  const [email, setEmail] = useState("");
  const [status, setStatus] = useState<"idle" | "submitting" | "success" | "error">("idle");
  const [error, setError] = useState("");

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!isValidEmail(email)) {
      setError("Bitte gib eine gültige E-Mail-Adresse ein.");
      return;
    }
    setError("");
    setStatus("submitting");
    try {
      const res = await fetch("/api/stock-notifications", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email, productId, variantName }),
      });
      const data: { ok: boolean; reason?: string } = await res.json();
      if (!data.ok) {
        setStatus("error");
        setError(data.reason || "Eintragen hat nicht geklappt. Bitte versuch es später erneut.");
        return;
      }
      setStatus("success");
    } catch {
      setStatus("error");
      setError("Eintragen hat nicht geklappt. Bitte versuch es später erneut.");
    }
  }

  if (status === "success") {
    return <p className="text-body-sm text-success">Danke! Wir melden uns, sobald es wieder verfügbar ist.</p>;
  }

  return (
    <form onSubmit={handleSubmit} className="flex flex-col gap-1.5 w-full">
      <div className="relative w-full">
        <input
          type="email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          placeholder="Bei Verfügbarkeit benachrichtigen"
          aria-label="E-Mail-Adresse für Benachrichtigung, sobald das Produkt wieder verfügbar ist"
          // h-14 (3.5rem/56px), not py-3 alone — AddToCartInlineButton's
          // own button isn't 56px tall because of its py-3 padding alone,
          // it's that plus its 1.875rem/30px cart-icon image, which is
          // taller than this input's own text line-height would be at
          // that same padding. Setting the height explicitly (rather than
          // trying to reverse-engineer a padding value that happens to
          // produce 56px for text-body-sm) is what actually matches it.
          className="w-full h-14 rounded-sm border border-border pl-3 pr-12 text-body-sm text-text-primary bg-bg-base focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand"
        />
        <button
          type="submit"
          disabled={status === "submitting"}
          aria-label="Benachrichtigen"
          title="Benachrichtigen"
          className="absolute right-1.5 top-1/2 -translate-y-1/2 flex size-8 items-center justify-center rounded-sm text-text-primary hover:text-brand transition-colors disabled:opacity-60 disabled:cursor-not-allowed"
        >
          {status === "submitting" ? "…" : <ArrowRightIcon />}
        </button>
      </div>
      {error && <p className="text-label text-red-600">{error}</p>}
    </form>
  );
}
