"use client";

import { useState } from "react";
import { createLead } from "@/lib/strapi";
import { PaperPlane } from "./icons";

type Status = "idle" | "loading" | "sent" | "error";

export function NewsletterForm() {
  const [email, setEmail] = useState("");
  const [status, setStatus] = useState<Status>("idle");

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!email || status === "loading") return;
    setStatus("loading");
    const ok = await createLead({
      email,
      sourcePage: window.location.pathname,
      submittedAt: new Date().toISOString(),
    });
    if (ok) {
      setStatus("sent");
      setEmail("");
    } else {
      setStatus("error");
    }
  }

  return (
    <form onSubmit={handleSubmit} className="w-full">
      <div className="flex items-center gap-2 rounded-pill border border-line bg-paper py-2 pl-5 pr-2 shadow-soft focus-within:border-leaf/60">
        <input
          type="email"
          required
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          placeholder="Enter your email address"
          aria-label="Email address"
          disabled={status === "loading"}
          className="min-w-0 flex-1 bg-transparent py-2 text-sm text-ink outline-none placeholder:text-muted disabled:opacity-60"
        />
        <button
          type="submit"
          aria-label="Subscribe"
          disabled={status === "loading"}
          className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-gradient-to-br from-leaf-deep via-teal to-sky text-white transition-transform hover:scale-105 disabled:opacity-60 disabled:hover:scale-100"
        >
          <PaperPlane className="h-4 w-4" />
        </button>
      </div>
      <p
        className={`mt-2 pl-5 text-sm transition-opacity ${
          status === "sent"
            ? "text-leaf-deep opacity-100"
            : status === "error"
              ? "text-red-500 opacity-100"
              : "opacity-0"
        }`}
      >
        {status === "error"
          ? "Something went wrong — please try again."
          : "Thanks — we'll be in touch."}
      </p>
    </form>
  );
}
