"use client";

import { useState } from "react";
import { Button } from "./ui/button";

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

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setStatus("loading");

    try {
      // Get app_id from environment or URL
      const appId =
        process.env.NEXT_PUBLIC_APP_ID ||
        new URLSearchParams(window.location.search).get("app_id") ||
        "";

      // Create form data
      const formData = new FormData();
      formData.append("app_id", appId);
      formData.append("email", email);
      formData.append("form_type", "newsletter"); // Help identify form type in Kleap
      formData.append("_honeypot", ""); // Honeypot field

      // Submit to Kleap's form API
      const response = await fetch("https://form.kleap.co", {
        method: "POST",
        body: formData,
      });

      if (response.ok) {
        setStatus("success");
        setEmail("");
        // Reset status after 3 seconds
        setTimeout(() => setStatus("idle"), 3000);
      } else {
        throw new Error("Failed to submit");
      }
    } catch {
      setStatus("error");
      // Reset status after 3 seconds
      setTimeout(() => setStatus("idle"), 3000);
    }
  };

  return (
    <div className="w-full max-w-md mx-auto">
      <h3 className="text-lg font-semibold mb-2 text-black dark:text-white">
        Subscribe to our newsletter
      </h3>
      <p className="text-sm text-gray-600 dark:text-gray-400 mb-4">
        Get the latest updates and exclusive content delivered to your inbox.
      </p>

      <form onSubmit={handleSubmit} className="flex gap-2">
        <input
          type="email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          placeholder="Enter your email"
          required
          className="flex-1 px-4 py-2 rounded-md border border-gray-300 dark:border-gray-700 bg-white dark:bg-neutral-900 text-black dark:text-white placeholder:text-gray-400 focus:ring-2 focus:ring-neutral-400 focus:outline-none"
        />

        {/* Honeypot field - hidden from users */}
        <input
          type="text"
          name="_honeypot"
          style={{ display: "none" }}
          tabIndex={-1}
          autoComplete="off"
        />

        <Button
          type="submit"
          disabled={status === "loading"}
          className="whitespace-nowrap"
        >
          {status === "loading"
            ? "..."
            : status === "success"
              ? "✓"
              : status === "error"
                ? "Error"
                : "Subscribe"}
        </Button>
      </form>

      {status === "success" && (
        <p className="mt-2 text-sm text-green-600 dark:text-green-400">
          Thanks for subscribing!
        </p>
      )}

      {status === "error" && (
        <p className="mt-2 text-sm text-red-600 dark:text-red-400">
          Something went wrong. Please try again.
        </p>
      )}
    </div>
  );
}
