import { useEffect, useRef, useState } from "react";
import { ArrowRight, CheckCircle2, FileText, Loader2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Section } from "@/components/ui/Section";
import { supabase } from "@/integrations/supabase/client";
import { trackEvent } from "@/lib/analytics";

type Lang = "sv" | "en";

const GUIDE_NAME = "experience_advantage_2026";
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

const content = {
  sv: {
    eyebrow: "KOSTNADSFRI FIELD GUIDE · 22 SIDOR",
    title: "The Experience Advantage",
    subtitle: "Guiden till upplevelseteknik för mässor & event",
    body:
      "En researchbaserad guide till hur hologram, AI, XR och interaktiva installationer kan användas för att skapa uppmärksamhet, deltagande och mätbara resultat på mässor och event.",
    support: "Från första stoppet i mässgången till interaktion, dialog och nästa affärssteg.",
    label: "E-postadress",
    placeholder: "namn@företag.se",
    cta: "Få guiden kostnadsfritt",
    sending: "Skickar…",
    micro:
      "Vi skickar guiden direkt till din inkorg. Ingen automatisk prenumeration. Läs vår",
    privacy: "integritetspolicy",
    microEnd: ".",
    errorEmpty: "Ange din e-postadress.",
    errorInvalid: "Ange en giltig e-postadress, till exempel namn@företag.se.",
    errorRate: "Du har begärt guiden flera gånger. Vänta en stund och försök igen.",
    errorGeneric:
      "Något gick fel och guiden kunde inte skickas. Försök igen om en stund eller kontakta hello@sutekistudios.com.",
    success:
      "Tack! Guiden skickas till din e-postadress. Kontrollera även skräpposten om den inte har kommit inom några minuter.",
    again: "Skicka igen",
  },
  en: {
    eyebrow: "COMPLIMENTARY FIELD GUIDE · 22 PAGES",
    title: "The Experience Advantage",
    subtitle: "Field Guide to Experiential Technology at Trade Shows",
    body:
      "A research-backed guide to using holograms, AI, XR and interactive installations to create attention, participation and measurable outcomes at trade shows and events.",
    support: "From the first stop in the aisle to interaction, conversation and the next business action.",
    label: "Work email",
    placeholder: "name@company.com",
    cta: "Get the field guide",
    sending: "Sending…",
    micro:
      "We send the guide straight to your inbox. No automatic subscription. Read our",
    privacy: "Privacy Policy",
    microEnd: ".",
    errorEmpty: "Please enter your email address.",
    errorInvalid: "Please enter a valid email address, for example name@company.com.",
    errorRate: "You have requested the guide several times. Please wait a moment and try again.",
    errorGeneric:
      "Something went wrong and the guide could not be sent. Please try again shortly or contact hello@sutekistudios.com.",
    success:
      "Your guide is on its way. Please check your spam folder if it does not arrive within a few minutes.",
    again: "Send again",
  },
} as const;

function collectUtm(): Record<string, string> {
  if (typeof window === "undefined") return {};
  const params = new URLSearchParams(window.location.search);
  const utm: Record<string, string> = {};
  ["utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content"].forEach((key) => {
    const value = params.get(key);
    if (value) utm[key] = value;
  });
  return utm;
}

export function PdfGuideSection({
  lang = "sv",
  variant = "full",
}: {
  lang?: Lang;
  variant?: "full" | "compact" | "bare";
}) {
  const t = content[lang];
  const compact = variant === "compact";
  const [email, setEmail] = useState("");
  const [honeypot, setHoneypot] = useState("");
  const [status, setStatus] = useState<"idle" | "sending" | "success">("idle");
  const [error, setError] = useState<string | null>(null);
  const [started, setStarted] = useState(false);
  const formRef = useRef<HTMLDivElement>(null);

  // Track form view once it becomes visible.
  useEffect(() => {
    const node = formRef.current;
    if (!node || typeof IntersectionObserver === "undefined") return;
    const observer = new IntersectionObserver((entries) => {
      if (entries.some((entry) => entry.isIntersecting)) {
        trackEvent("guide_form_view", { guide_name: GUIDE_NAME, language: lang });
        observer.disconnect();
      }
    }, { threshold: 0.3 });
    observer.observe(node);
    return () => observer.disconnect();
  }, [lang]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (status === "sending") return;

    const value = email.trim();
    if (!value) {
      setError(t.errorEmpty);
      return;
    }
    if (!EMAIL_RE.test(value)) {
      setError(t.errorInvalid);
      return;
    }

    setError(null);
    setStatus("sending");

    try {
      const { data, error: fnError } = await supabase.functions.invoke("send-guide", {
        body: {
          email: value,
          company: honeypot,
          language: lang,
          pageUrl: typeof window !== "undefined" ? window.location.href : "",
          utm: collectUtm(),
        },
      });

      if (fnError || !data?.success) {
        const message = String(fnError?.message ?? "");
        setError(message.includes("429") ? t.errorRate : t.errorGeneric);
        trackEvent("guide_form_error", { guide_name: GUIDE_NAME, language: lang });
        setStatus("idle");
        return;
      }

      trackEvent("guide_email_sent", {
        guide_name: GUIDE_NAME,
        language: lang,
        source_page: typeof window !== "undefined" ? window.location.pathname : "",
      });
      setStatus("success");
      setEmail("");
    } catch {
      trackEvent("guide_form_error", { guide_name: GUIDE_NAME, language: lang });
      setError(t.errorGeneric);
      setStatus("idle");
    }
  };

  const formBlock = status === "success" ? (
          <div className={compact ? "" : "max-w-xl mx-auto"}>
            <div className="flex items-start gap-3 text-left rounded-2xl border border-border bg-background p-5 sm:p-6">
              <CheckCircle2 className="h-5 w-5 shrink-0 mt-0.5 text-accent" aria-hidden="true" />
              <p className="text-foreground leading-relaxed" role="status">{t.success}</p>
            </div>
            <button
              type="button"
              onClick={() => setStatus("idle")}
              className="mt-5 text-sm font-medium text-muted-foreground underline underline-offset-4 hover:text-accent transition-colors min-h-[44px] px-2"
            >
              {t.again}
            </button>
          </div>
        ) : (
          <form onSubmit={handleSubmit} noValidate className={compact ? "text-left" : "max-w-xl mx-auto text-left"}>
            <label htmlFor="guide-email" className="block text-sm font-medium text-foreground mb-3">
              {t.label}
            </label>
            <div className="flex flex-col sm:flex-row gap-3 sm:gap-4">
              <input
                id="guide-email"
                type="email"
                name="email"
                autoComplete="email"
                value={email}
                onChange={(e) => {
                  if (!started) {
                    setStarted(true);
                    trackEvent("guide_form_start", { guide_name: GUIDE_NAME, language: lang });
                  }
                  setEmail(e.target.value);
                  if (error) setError(null);
                }}
                placeholder={t.placeholder}
                aria-invalid={error ? true : undefined}
                aria-describedby={error ? "guide-email-error" : "guide-email-micro"}
                className="w-full sm:flex-1 min-h-[56px] rounded-full border border-border bg-background px-5 text-base text-foreground placeholder:text-muted-foreground focus:outline-none focus-visible:ring-2 focus-visible:ring-accent focus:ring-2 focus:ring-accent focus:border-accent transition"
              />
              {/* Honeypot — hidden from real users */}
              <input
                type="text"
                name="company"
                tabIndex={-1}
                autoComplete="off"
                aria-hidden="true"
                value={honeypot}
                onChange={(e) => setHoneypot(e.target.value)}
                className="hidden"
              />
              <Button
                type="submit"
                size="lg"
                disabled={status === "sending"}
                className="group/btn w-full sm:w-auto min-h-[56px] h-auto whitespace-nowrap text-sm sm:text-base px-6 sm:px-7 bg-accent text-accent-foreground hover:bg-accent/90 transition-all duration-300 hover:-translate-y-0.5 hover:shadow-lg rounded-full inline-flex items-center justify-center gap-2 disabled:opacity-70 disabled:hover:translate-y-0 focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-2"
              >
                {status === "sending" ? (
                  <>
                    <Loader2 className="h-5 w-5 shrink-0 animate-spin" aria-hidden="true" />
                    {t.sending}
                  </>
                ) : (
                  <>
                    {t.cta}
                    <ArrowRight className="h-5 w-5 shrink-0 transition-transform duration-200 group-hover/btn:translate-x-1" />
                  </>
                )}
              </Button>
            </div>

            {error && (
              <p id="guide-email-error" role="alert" className="mt-3 text-sm text-destructive">
                {error}
              </p>
            )}

            <p id="guide-email-micro" className="mt-4 text-sm text-muted-foreground leading-relaxed">
              {t.micro}{" "}
              <a href={lang === "sv" ? "/integritetspolicy" : "/en/privacy-policy"} className="underline underline-offset-4 hover:text-accent transition-colors">
                {t.privacy}
              </a>
              {t.microEnd}
            </p>
          </form>
        );

  if (variant === "bare") {
    return <div ref={formRef} className="text-left">{formBlock}</div>;
  }

  return (
    <Section className={`${compact ? "section-beige" : "section-beige"} relative overflow-hidden`}>
      <div className="absolute inset-0 bg-gradient-radial opacity-20" />
      <div
        className={
          compact
            ? "relative z-10 rounded-3xl border border-border bg-background p-6 sm:p-10 grid lg:grid-cols-2 gap-8 lg:gap-14 items-center"
            : "relative z-10 max-w-3xl mx-auto text-center"
        }
      >
        <div className={compact ? "" : "contents"}>
          <div
            className={`w-14 h-14 sm:w-16 sm:h-16 rounded-2xl bg-accent/10 flex items-center justify-center mb-6 ${compact ? "" : "mx-auto mb-8"}`}
            aria-hidden="true"
          >
            <FileText className="h-7 w-7 sm:h-8 sm:w-8 text-accent" />
          </div>
          <p className="section-label mb-4 text-accent tracking-[0.14em] text-xs sm:text-sm font-semibold">{t.eyebrow}</p>
          <h2 className={`text-2xl sm:text-3xl ${compact ? "" : "md:text-4xl"} font-semibold mb-5 text-foreground text-balance`}>{t.title}</h2>
          <p className="text-lg sm:text-xl font-medium text-foreground mb-4 text-balance">{t.subtitle}</p>
          <p className="text-base sm:text-lg text-muted-foreground leading-relaxed mb-3">{t.body}</p>
          <p className={`text-sm sm:text-base text-muted-foreground/80 leading-relaxed ${compact ? "mb-0" : "mb-10"}`}>{t.support}</p>
        </div>
        <div ref={formRef} className={compact ? "" : "contents"}>

        {formBlock}
        </div>
      </div>
    </Section>
  );
}
