"use client";

import { useState } from "react";
import { motion, useReducedMotion } from "motion/react";
import { ArrowRight, Check, Loader2 } from "lucide-react";
import { cn } from "@/lib/utils";

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

export function WaitlistForm({ className }: { className?: string }) {
  const [email, setEmail] = useState("");
  const [status, setStatus] = useState<Status>("idle");
  const [errorMsg, setErrorMsg] = useState("");
  const reduced = useReducedMotion();

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!email.trim()) return;

    setStatus("loading");
    setErrorMsg("");

    try {
      const res = await fetch("/api/waitlist", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email: email.trim() }),
      });

      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        throw new Error(data.error || "Something went wrong");
      }

      setStatus("success");
    } catch (err) {
      setStatus("error");
      setErrorMsg(err instanceof Error ? err.message : "Something went wrong");
    }
  }

  if (status === "success") {
    return (
      <motion.div
        initial={reduced ? {} : { opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        className={cn("text-center", className)}
      >
        <div className="inline-flex items-center justify-center h-12 w-12 rounded-full bg-emerald-500/20 border border-emerald-500/30 mb-4">
          <Check className="h-6 w-6 text-emerald-400" />
        </div>
        <p className="text-lg font-semibold text-white">You&apos;re on the list.</p>
        <p className="mt-2 text-sm text-gray-400">
          We&apos;ll email you when your spot opens up.
        </p>
      </motion.div>
    );
  }

  return (
    <form onSubmit={handleSubmit} className={cn("w-full max-w-md", className)}>
      <div className="flex gap-2">
        <input
          type="email"
          required
          placeholder="you@company.com"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          disabled={status === "loading"}
          className={cn(
            "flex-1 rounded-lg bg-white/[0.04] border border-white/10 px-4 py-3",
            "text-sm text-white placeholder:text-gray-500",
            "focus:outline-none focus:border-violet-500/50 focus:ring-1 focus:ring-violet-500/30",
            "transition-all disabled:opacity-50"
          )}
        />
        <button
          type="submit"
          disabled={status === "loading"}
          className="rounded-lg bg-violet-600 hover:bg-violet-500 px-5 py-3 text-sm font-medium text-white transition-all shadow-lg shadow-violet-600/25 disabled:opacity-50 flex items-center gap-2"
        >
          {status === "loading" ? (
            <Loader2 className="h-4 w-4 animate-spin" />
          ) : (
            <>
              Request Access
              <ArrowRight className="h-4 w-4" />
            </>
          )}
        </button>
      </div>
      {status === "error" && (
        <p className="mt-2 text-xs text-red-400">{errorMsg}</p>
      )}
    </form>
  );
}
