"use client";

import { useState } from "react";
import { ArrowRight } from "lucide-react";
import { BrandLogo } from "@/components/brand/BrandLogo";
import { DataConsentField } from "@/components/forms/DataConsentField";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { dataConsent } from "@/content/consent";

export function FooterNewsletter() {
  const [status, setStatus] = useState<"idle" | "loading" | "done" | "error">("idle");
  const [consent, setConsent] = useState(false);
  const [error, setError] = useState("");

  async function submit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    if (!consent) {
      setError(dataConsent.errorMessage);
      return;
    }
    setStatus("loading");
    setError("");
    const form = e.currentTarget;
    const data = new FormData(form);

    try {
      const res = await fetch("/api/inquiry", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          intent: "newsletter",
          firstName: data.get("firstName"),
          lastName: data.get("lastName"),
          email: data.get("email"),
          message: "Footer newsletter signup",
          consent: true,
        }),
      });
      const json = await res.json();
      if (!res.ok || !json.ok) {
        throw new Error(json.error || "Something went wrong");
      }
      setStatus("done");
      form.reset();
      setConsent(false);
    } catch (err) {
      setStatus("error");
      setError(err instanceof Error ? err.message : "Something went wrong. Please try again.");
    }
  }

  return (
    <div className="relative z-10 mx-auto max-w-5xl rounded-3xl border border-[#1a5c38]/14 bg-white p-6 shadow-md shadow-[#1a5c38]/6 md:p-10">
      <div className="grid gap-8 lg:grid-cols-[1fr_1.2fr] lg:items-start">
        <div>
          <BrandLogo href={undefined} />
          <h2 className="mt-4 text-2xl font-bold text-[#0d3d26] md:text-3xl">Stay up to date!</h2>
          <p className="mt-2 text-sm text-muted-foreground leading-relaxed">
            Get announcements about tickets, lineup, and the next Great Rift Valley Innovation
            Summit edition before anyone else.
          </p>
        </div>
        <form onSubmit={submit} className="space-y-4">
          <div className="grid gap-4 sm:grid-cols-2">
            <div className="space-y-2">
              <Label htmlFor="footer-first">First name</Label>
              <Input id="footer-first" name="firstName" required placeholder="First name" />
            </div>
            <div className="space-y-2">
              <Label htmlFor="footer-last">Last name</Label>
              <Input id="footer-last" name="lastName" required placeholder="Last name" />
            </div>
          </div>
          <div className="space-y-2">
            <Label htmlFor="footer-email">Email address</Label>
            <Input
              id="footer-email"
              name="email"
              type="email"
              required
              placeholder="you@email.com"
            />
          </div>
          <DataConsentField
            id="footer-consent"
            checked={consent}
            onCheckedChange={setConsent}
            className="border-0 bg-transparent p-0"
          />
          {error && <p className="text-sm text-destructive">{error}</p>}
          {status === "done" && (
            <p className="text-sm text-[#1a5c38]">You&apos;re on the list — thank you!</p>
          )}
          <Button
            type="submit"
            className="w-full rounded-full bg-[#1a5c38] text-white hover:bg-[#0d3d26] sm:w-auto"
            disabled={status === "loading"}
          >
            {status === "loading" ? "Signing up…" : "Sign up"}
            <ArrowRight className="size-4" />
          </Button>
        </form>
      </div>
    </div>
  );
}
