"use client";

import { useState } from "react";

export default function UnsubscribeForm({
  customerId,
  signature,
}: {
  customerId: string;
  signature: string;
}) {
  const [state, setState] = useState<"idle" | "loading" | "done" | "error">("idle");

  async function handleClick() {
    setState("loading");
    const res = await fetch("/api/campaigns/email/unsubscribe", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ customerId, signature }),
    });
    setState(res.ok ? "done" : "error");
  }

  if (state === "done") {
    return <p className="text-muted">You&apos;ve been unsubscribed. Sorry to see you go.</p>;
  }

  return (
    <div>
      <button
        onClick={handleClick}
        disabled={state === "loading"}
        className="inline-flex items-center justify-center rounded-lg bg-brand-green px-5 py-2.5 text-sm font-medium text-white transition-colors hover:bg-brand-green-deep disabled:opacity-50"
      >
        {state === "loading" ? "Unsubscribing…" : "Unsubscribe"}
      </button>
      {state === "error" && (
        <p className="mt-3 text-sm text-red-400">Something went wrong. Please try again.</p>
      )}
    </div>
  );
}
