"use client";
import React, { useState, useId } from "react";

const categories = [
  "Conference Rooms & UC",
  "Digital Signage",
  "Live Events & Staging",
  "Displays & LED",
  "Audio",
  "AV over IP",
  "InfoComm & ISE",
];

export default function NewsletterSignup() {
  const [email, setEmail] = useState("");
  const [selected, setSelected] = useState<string[]>(["Conference Rooms & UC"]);
  const [submitted, setSubmitted] = useState(false);
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);
  const formId = useId();

  const toggleCategory = (cat: string) => {
    setSelected((prev) =>
      prev.includes(cat) ? prev.filter((c) => c !== cat) : [...prev, cat]
    );
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      setError("Please enter a valid email address.");
      return;
    }
    setError("");
    setLoading(true);

    try {
      const response = await fetch("/api/newsletter/subscribe", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email, topics: selected }),
      });
      const data = await response.json();
      if (!response.ok) {
        throw new Error(data.error || "Failed to subscribe");
      }
      setSubmitted(true);
    } catch (err: unknown) {
      const message = err instanceof Error ? err.message : "Something went wrong. Please try again.";
      setError(message);
    } finally {
      setLoading(false);
    }
  };

  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === "Enter") {
      handleSubmit(e as unknown as React.FormEvent);
    }
  };

  return (
    <section className="max-w-container mx-auto px-4" aria-labelledby={`${formId}-heading`}>
      <div className="bg-[#0d1520] border border-[#DCE6F2] py-8 md:py-10">
        <div className="max-w-2xl mx-auto text-center px-4">
          {/* Header */}
          <div className="flex items-center justify-center gap-3 mb-3">
            <div className="flex-1 h-px bg-[#DCE6F2] max-w-[80px]" />
            <span className="section-label" id={`${formId}-heading`}>Newsletter</span>
            <div className="flex-1 h-px bg-[#DCE6F2] max-w-[80px]" />
          </div>
          <p className="font-heading text-[#e0e0e0] text-xl md:text-2xl font-bold mb-1.5">
            Stay Ahead of the Pro AV Industry
          </p>
          <p className="font-body text-[#777] text-sm mb-6">
            Get the latest news, product launches, and industry insights delivered to your inbox.
          </p>

          {submitted ? (
            <div
              className="bg-[#FFFFFF] border border-[#1D4ED8] rounded-sm px-6 py-8 text-center"
              role="status"
              aria-live="polite">
              <div className="w-10 h-10 rounded-full bg-[#1D4ED8]/20 flex items-center justify-center mx-auto mb-3">
                <svg width="20" height="20" viewBox="0 0 20 20" fill="none" aria-hidden="true">
                  <path d="M4 10l4 4 8-8" stroke="#1D4ED8" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                </svg>
              </div>
              <p className="font-heading text-[#e0e0e0] font-bold text-lg mb-1">You&apos;re subscribed!</p>
              <p className="font-body text-[#777] text-sm">
                Thanks for signing up. Check your inbox for a confirmation email.
              </p>
            </div>
          ) : (
            <form onSubmit={handleSubmit} noValidate aria-label="Newsletter signup form">
              {/* Category checkboxes */}
              <fieldset className="mb-5">
                <legend className="font-body text-xs font-bold text-[#888] uppercase tracking-wider mb-3">
                  Topics you care about
                </legend>
                <div className="flex flex-wrap justify-center gap-2">
                  {categories.map((cat) => {
                    const checked = selected.includes(cat);
                    return (
                      <label
                        key={cat}
                        className={`newsletter-chip ${checked ? "newsletter-chip-active" : ""}`}>
                        <input
                          type="checkbox"
                          checked={checked}
                          onChange={() => toggleCategory(cat)}
                          className="sr-only"
                          aria-label={`Subscribe to ${cat} news`}
                        />
                        <span aria-hidden="true" className={`mr-1.5 inline-block w-3 h-3 rounded-sm border transition-colors ${checked ? "bg-[#1D4ED8] border-[#1D4ED8]" : "border-[#444]"}`}>
                          {checked && (
                            <svg viewBox="0 0 12 12" fill="none" className="w-full h-full" aria-hidden="true">
                              <path d="M2 6l3 3 5-5" stroke="white" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
                            </svg>
                          )}
                        </span>
                        {cat}
                      </label>
                    );
                  })}
                </div>
              </fieldset>

              {/* Email input + submit */}
              <div className="flex flex-col sm:flex-row gap-2 max-w-md mx-auto">
                <div className="flex-1 relative">
                  <label htmlFor={`${formId}-email`} className="sr-only">Email address</label>
                  <input
                    id={`${formId}-email`}
                    type="email"
                    value={email}
                    onChange={(e) => { setEmail(e.target.value); setError(""); }}
                    onKeyDown={handleKeyDown}
                    placeholder="Enter your email address"
                    autoComplete="email"
                    aria-required="true"
                    aria-describedby={error ? `${formId}-error` : undefined}
                    aria-invalid={!!error}
                    disabled={loading}
                    className={`search-input w-full py-2.5 px-4 text-sm ${error ? "border-red-500 focus:border-red-500" : ""} ${loading ? "opacity-60 cursor-not-allowed" : ""}`}
                  />
                </div>
                <button
                  type="submit"
                  disabled={loading}
                  className={`btn-subscribe py-2.5 px-6 text-sm whitespace-nowrap focus:outline-none focus-visible:ring-2 focus-visible:ring-[#1D4ED8] focus-visible:ring-offset-2 focus-visible:ring-offset-[#0d1520] ${loading ? "opacity-70 cursor-not-allowed" : ""}`}>
                  {loading ? "Subscribing..." : "Subscribe Free"}
                </button>
              </div>

              {error && (
                <p
                  id={`${formId}-error`}
                  className="font-body text-red-400 text-xs mt-2"
                  role="alert"
                  aria-live="assertive">
                  {error}
                </p>
              )}

              <p className="font-body text-[#555] text-xs mt-3">
                You&apos;ll also be added to the daily newsletters for Broadcast Beat,
                BroadcastEngineering.com, Sports Media Beat, and The Crew Grid.
                Unsubscribe from any one (or all) anytime. By subscribing you agree
                to our{" "}
                <a href="/privacy" className="text-[#1D4ED8] hover:underline focus:outline-none focus-visible:underline">
                  Privacy Policy
                </a>.
              </p>
            </form>
          )}
        </div>
      </div>
    </section>
  );
}
