"use client";

import { useState } from "react";
import { Section } from "@/components/layout/Section";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";

export function Newsletter() {
  const [email, setEmail] = useState("");
  const [status, setStatus] = useState<"idle" | "loading" | "done" | "error">("idle");

  async function submit(e: React.FormEvent) {
    e.preventDefault();
    setStatus("loading");
    try {
      const res = await fetch("/api/inquiry", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          intent: "newsletter",
          name: "Newsletter subscriber",
          email,
          message: "Newsletter signup from homepage",
        }),
      });
      if (!res.ok) throw new Error();
      setStatus("done");
      setEmail("");
    } catch {
      setStatus("error");
    }
  }

  return (
    <Section variant="muted">
      <div className="mx-auto max-w-xl text-center">
        <h2 className="text-2xl font-bold">Stay up to date</h2>
        <p className="mt-2 text-muted-foreground">
          Get announcements before anyone else about the next GRV Summit edition.
        </p>
        <form onSubmit={submit} className="mt-6 flex flex-col gap-3 sm:flex-row sm:items-end">
          <div className="flex-1 space-y-2 text-left">
            <Label htmlFor="newsletter-email">Email</Label>
            <Input
              id="newsletter-email"
              type="email"
              required
              placeholder="you@email.com"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
            />
          </div>
          <Button
            type="submit"
            className="rounded-full bg-[#37a47a] text-[#ffffff] hover:bg-[#37a47a]/90"
            disabled={status === "loading"}
          >
            {status === "loading" ? "Signing up…" : "Sign up"}
          </Button>
        </form>
        {status === "done" && <p className="mt-3 text-sm text-primary">You&apos;re on the list!</p>}
        {status === "error" && (
          <p className="mt-3 text-sm text-destructive">Something went wrong. Try again.</p>
        )}
      </div>
    </Section>
  );
}
