"use client";

import { AnimatePresence, motion } from "framer-motion";
import { Check, ChevronDown, LoaderCircle, X } from "lucide-react";
import {
  createContext,
  type FormEvent,
  type ReactNode,
  useCallback,
  useContext,
  useEffect,
  useId,
  useMemo,
  useState,
  useTransition,
} from "react";
import { joinWaitlist } from "@/actions/waitlist";
import {
  isTurnstileConfiguredClient,
  TurnstileWidget,
} from "@/components/shared/TurnstileWidget";
import { cn } from "@/utils/cn";

type WaitlistContextValue = {
  openWaitlist: (prefillEmail?: string) => void;
  closeWaitlist: () => void;
};

const WaitlistContext = createContext<WaitlistContextValue | null>(null);

export function useWaitlist() {
  const context = useContext(WaitlistContext);
  if (!context) {
    throw new Error("useWaitlist must be used within WaitlistProvider");
  }
  return context;
}

const HEARD_FROM_OPTIONS = [
  "Google / Search",
  "Product Hunt",
  "Twitter / X",
  "LinkedIn",
  "Friend or colleague",
  "Blog or article",
  "Other",
] as const;

type WaitlistProviderProps = {
  children: ReactNode;
};

export function WaitlistProvider({ children }: WaitlistProviderProps) {
  const [isOpen, setIsOpen] = useState(false);
  const [email, setEmail] = useState("");
  const [heardFrom, setHeardFrom] = useState("");
  const [websiteUrl, setWebsiteUrl] = useState("");
  const [honeypot, setHoneypot] = useState("");
  const [turnstileToken, setTurnstileToken] = useState<string | null>(null);
  const [turnstileReset, setTurnstileReset] = useState(0);
  const [error, setError] = useState<string | null>(null);
  const [submitted, setSubmitted] = useState(false);
  const [isPending, startTransition] = useTransition();
  const titleId = useId();
  const descriptionId = useId();
  const turnstileRequired = isTurnstileConfiguredClient();

  const resetForm = useCallback(() => {
    setEmail("");
    setHeardFrom("");
    setWebsiteUrl("");
    setHoneypot("");
    setTurnstileToken(null);
    setTurnstileReset((n) => n + 1);
    setError(null);
    setSubmitted(false);
  }, []);

  const openWaitlist = useCallback((prefillEmail?: string) => {
    setIsOpen(true);
    setError(null);
    setSubmitted(false);
    setHeardFrom("");
    setWebsiteUrl("");
    setHoneypot("");
    setTurnstileToken(null);
    setTurnstileReset((n) => n + 1);
    setEmail(prefillEmail?.trim() ?? "");
  }, []);

  const closeWaitlist = useCallback(() => {
    setIsOpen(false);
  }, []);

  useEffect(() => {
    if (!isOpen) return;

    const onKeyDown = (event: KeyboardEvent) => {
      if (event.key === "Escape") closeWaitlist();
    };

    document.addEventListener("keydown", onKeyDown);
    const previousOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";

    return () => {
      document.removeEventListener("keydown", onKeyDown);
      document.body.style.overflow = previousOverflow;
    };
  }, [isOpen, closeWaitlist]);

  const handleSubmit = (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    setError(null);

    if (turnstileRequired && !turnstileToken) {
      setError("Complete the security check and try again.");
      return;
    }

    startTransition(async () => {
      const result = await joinWaitlist({
        email,
        heardFrom,
        websiteUrl,
        turnstileToken,
        honeypot,
      });

      if (!result.success) {
        setError(result.error);
        setTurnstileToken(null);
        setTurnstileReset((n) => n + 1);
        return;
      }

      setSubmitted(true);
    });
  };

  const value = useMemo(
    () => ({ openWaitlist, closeWaitlist }),
    [openWaitlist, closeWaitlist],
  );

  return (
    <WaitlistContext.Provider value={value}>
      {children}

      <AnimatePresence
        onExitComplete={() => {
          if (!isOpen) resetForm();
        }}
      >
        {isOpen && (
          <div className="fixed inset-0 z-100 flex items-end justify-center p-3 sm:items-center sm:p-6">
            <motion.button
              type="button"
              aria-label="Close waitlist dialog"
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              transition={{ duration: 0.2 }}
              className="absolute inset-0 bg-ink/40 backdrop-blur-[3px]"
              onClick={closeWaitlist}
            />

            <motion.div
              role="dialog"
              aria-modal="true"
              aria-labelledby={titleId}
              aria-describedby={descriptionId}
              initial={{ opacity: 0, y: 18, scale: 0.98 }}
              animate={{ opacity: 1, y: 0, scale: 1 }}
              exit={{ opacity: 0, y: 10, scale: 0.98 }}
              transition={{ duration: 0.28, ease: [0.22, 1, 0.36, 1] }}
              className={cn(
                "relative z-10 flex w-full max-w-110 flex-col",
                "max-h-[min(92vh,680px)] overflow-hidden",
                "rounded-[22px] bg-white",
                "shadow-[0_28px_80px_-28px_rgba(4,16,57,0.55),0_0_0_1px_rgba(4,16,57,0.06)]",
              )}
            >
              <div
                className="relative shrink-0 px-6 pt-6 pb-5 sm:px-8 sm:pt-8 sm:pb-6"
                style={{
                  backgroundImage: `
                    radial-gradient(ellipse 80% 90% at 0% 0%, #EDE9FF 0%, transparent 60%),
                    radial-gradient(ellipse 70% 80% at 100% 0%, #DDFBE9 0%, transparent 55%)
                  `,
                }}
              >
                <button
                  type="button"
                  onClick={closeWaitlist}
                  aria-label="Close"
                  className={cn(
                    "absolute top-4 right-4 inline-flex h-8 w-8 items-center justify-center sm:top-5 sm:right-5",
                    "rounded-full text-ink/45 transition-colors",
                    "hover:bg-white/80 hover:text-ink",
                    "focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-brand",
                  )}
                >
                  <X className="h-4 w-4" strokeWidth={2} aria-hidden="true" />
                </button>

                {submitted ? (
                  <div className="pr-8">
                    <div className="mb-4 inline-flex h-11 w-11 items-center justify-center rounded-full bg-brand/12 text-brand">
                      <Check
                        className="h-5 w-5"
                        strokeWidth={2.5}
                        aria-hidden="true"
                      />
                    </div>
                    <h2
                      id={titleId}
                      className="text-[1.625rem] leading-tight font-bold tracking-[-0.02em] text-ink sm:text-[1.75rem]"
                    >
                      You&apos;re on the list
                    </h2>
                    <p
                      id={descriptionId}
                      className="mt-2.5 max-w-[34ch] text-[15px] leading-relaxed text-ink/65"
                    >
                      We&apos;ll email you a one-time credential as soon as a
                      spot opens — so you get ChatHiro at its best.
                    </p>
                  </div>
                ) : (
                  <div className="pr-8">
                    <p className="text-[13px] font-medium tracking-[-0.01em] text-brand">
                      Limited access
                    </p>
                    <h2
                      id={titleId}
                      className="mt-1.5 text-[1.625rem] leading-tight font-bold tracking-[-0.02em] text-ink sm:text-[1.75rem]"
                    >
                      We&apos;re at capacity
                    </h2>
                    <p
                      id={descriptionId}
                      className="mt-2.5 max-w-[38ch] text-[15px] leading-relaxed text-ink/65"
                    >
                      We&apos;re expanding carefully and pausing public signups.
                      Join the waitlist and we&apos;ll invite you with one-time
                      access when ready.
                    </p>
                  </div>
                )}
              </div>

              <div className="flex min-h-0 flex-1 flex-col overflow-y-auto px-6 pt-1 pb-6 sm:px-8 sm:pb-8">
                {submitted ? (
                  <button
                    type="button"
                    onClick={closeWaitlist}
                    className={primaryButtonClassName}
                  >
                    Close
                  </button>
                ) : (
                  <form onSubmit={handleSubmit} className="flex flex-col gap-4">
                    {/* Honeypot — hidden from users; bots that fill it are dropped. */}
                    <div
                      aria-hidden="true"
                      className="pointer-events-none absolute -left-[9999px] h-0 w-0 overflow-hidden opacity-0"
                    >
                      <label htmlFor="waitlist-company-website">
                        Company website
                      </label>
                      <input
                        id="waitlist-company-website"
                        name="companyWebsite"
                        type="text"
                        tabIndex={-1}
                        autoComplete="off"
                        value={honeypot}
                        onChange={(event) => setHoneypot(event.target.value)}
                      />
                    </div>

                    <Field label="Work email" htmlFor="waitlist-email">
                      <input
                        id="waitlist-email"
                        type="email"
                        required
                        autoComplete="email"
                        value={email}
                        onChange={(event) => setEmail(event.target.value)}
                        placeholder="you@company.com"
                        className={inputClassName}
                      />
                    </Field>

                    <Field
                      label="How did you hear about us?"
                      htmlFor="waitlist-heard-from"
                    >
                      <div className="relative">
                        <select
                          id="waitlist-heard-from"
                          required
                          value={heardFrom}
                          onChange={(event) => setHeardFrom(event.target.value)}
                          className={cn(
                            inputClassName,
                            "appearance-none pr-10",
                            !heardFrom && "text-ink/40",
                          )}
                        >
                          <option value="" disabled>
                            Select an option
                          </option>
                          {HEARD_FROM_OPTIONS.map((option) => (
                            <option
                              key={option}
                              value={option}
                              className="text-ink"
                            >
                              {option}
                            </option>
                          ))}
                        </select>
                        <ChevronDown
                          className="pointer-events-none absolute top-1/2 right-3.5 h-4 w-4 -translate-y-1/2 text-ink/35"
                          aria-hidden="true"
                        />
                      </div>
                    </Field>

                    <Field
                      label="Website URL"
                      htmlFor="waitlist-website"
                      hint="Where you'd like to add ChatHiro"
                    >
                      <input
                        id="waitlist-website"
                        type="url"
                        required
                        autoComplete="url"
                        value={websiteUrl}
                        onChange={(event) => setWebsiteUrl(event.target.value)}
                        placeholder="https://yourwebsite.com"
                        className={inputClassName}
                      />
                    </Field>

                    <TurnstileWidget
                      action="waitlist"
                      onToken={setTurnstileToken}
                      resetSignal={turnstileReset}
                    />

                    {error && (
                      <p
                        role="alert"
                        className="rounded-xl bg-[#FEF2F2] px-3.5 py-2.5 text-sm text-[#B91C1C]"
                      >
                        {error}
                      </p>
                    )}

                    <div className="mt-1 flex flex-col gap-3">
                      <button
                        type="submit"
                        disabled={
                          isPending || (turnstileRequired && !turnstileToken)
                        }
                        className={primaryButtonClassName}
                      >
                        {isPending ? (
                          <>
                            <LoaderCircle
                              className="h-4 w-4 animate-spin"
                              aria-hidden="true"
                            />
                            Submitting…
                          </>
                        ) : (
                          "Join the waitlist"
                        )}
                      </button>
                      <p className="text-center text-[12px] leading-relaxed text-ink/45">
                        No spam. We only email when your invite is ready.
                      </p>
                    </div>
                  </form>
                )}
              </div>
            </motion.div>
          </div>
        )}
      </AnimatePresence>
    </WaitlistContext.Provider>
  );
}

function Field({
  label,
  htmlFor,
  hint,
  children,
}: {
  label: string;
  htmlFor: string;
  hint?: string;
  children: ReactNode;
}) {
  return (
    <div className="flex flex-col gap-1.5">
      <div className="flex items-baseline justify-between gap-3">
        <label
          htmlFor={htmlFor}
          className="text-[13px] font-medium tracking-[-0.01em] text-ink"
        >
          {label}
        </label>
        {hint && <span className="text-[11px] text-ink/40">{hint}</span>}
      </div>
      {children}
    </div>
  );
}

const inputClassName = cn(
  "w-full rounded-xl border border-ink/10 bg-[#F8FAFC]",
  "px-3.5 py-3 text-[15px] text-ink outline-none",
  "transition-[border-color,box-shadow,background-color] duration-150",
  "placeholder:text-ink/35",
  "hover:border-ink/16",
  "focus:border-brand focus:bg-white focus:shadow-[0_0_0_3px_rgba(108,92,231,0.14)]",
);

const primaryButtonClassName = cn(
  "inline-flex w-full items-center justify-center gap-2",
  "rounded-xl bg-brand px-5 py-3.5",
  "text-[15px] font-semibold text-white",
  "shadow-[0_10px_24px_-12px_rgba(108,92,231,0.85)]",
  "transition-[background-color,transform] duration-150",
  "hover:bg-brand-strong active:scale-[0.99]",
  "focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-brand",
  "disabled:cursor-not-allowed disabled:opacity-70 disabled:active:scale-100",
);
