"use client";

import { useActionState, useEffect, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import { submitLead, type LeadState } from "@/app/actions";
import {
  INDUSTRY_OPTIONS,
  COMPANY_SIZE_OPTIONS,
  INTEREST_OPTIONS,
} from "@/lib/content";
import FloatInput from "./FloatInput";
import FloatDropdown from "./FloatDropdown";
import FloatTextarea from "./FloatTextarea";
import PhoneInput from "./PhoneInput";

const initial: LeadState = { ok: false, message: "" };

/* Compact multi-select dropdown — occupies one select-sized row, posts
   repeated `interests` fields so the server action needs no changes. */
function InterestMultiSelect() {
  const [selected, setSelected] = useState<string[]>([
    "Production",
    "Inventory",
  ]);
  const [open, setOpen] = useState(false);
  const wrapRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!open) return;
    const onDown = (e: MouseEvent) => {
      if (wrapRef.current && !wrapRef.current.contains(e.target as Node)) {
        setOpen(false);
      }
    };
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") setOpen(false);
    };
    document.addEventListener("mousedown", onDown);
    document.addEventListener("keydown", onKey);
    return () => {
      document.removeEventListener("mousedown", onDown);
      document.removeEventListener("keydown", onKey);
    };
  }, [open ]);

  const toggle = (o: string) =>
    setSelected((prev) =>
      prev.includes(o) ? prev.filter((v) => v !== o) : [...prev, o]
    );

  const summary =
    selected.length === 0
      ? "Select areas"
      : selected.length <= 2
        ? selected.join(", ")
        : `${selected.length} areas selected`;

  return (
    <div ref={wrapRef} className="relative mt-1.5">
      {selected.map((v) => (
        <input key={v} type="hidden" name="interests" value={v} />
      ))}
      <button
        type="button"
        aria-haspopup="listbox"
        aria-expanded={open}
        onClick={() => setOpen((o) => !o)}
        className={`flex h-12 w-full items-center justify-between gap-2 rounded-xl border bg-white px-3.5 text-left text-sm font-normal transition-colors ${
          open ? "border-brand" : "border-[#d5dce8]"
        } ${selected.length === 0 ? "text-muted" : "text-ink"}`}
      >
        <span className="min-w-0 flex-1 truncate">{summary}</span>
        {selected.length > 0 && (
          <span className="grid size-5 shrink-0 place-items-center rounded-full bg-brand text-[11px] font-semibold text-white">
            {selected.length}
          </span>
        )}
        <svg
          width="16"
          height="16"
          viewBox="0 0 16 16"
          fill="none"
          aria-hidden="true"
          className={`shrink-0 text-muted transition-transform ${open ? "rotate-180" : ""}`}
        >
          <path
            d="M4 6l4 4 4-4"
            stroke="currentColor"
            strokeWidth="1.6"
            strokeLinecap="round"
            strokeLinejoin="round"
          />
        </svg>
      </button>
      {open && (
        <div
          role="listbox"
          aria-multiselectable="true"
          className="absolute inset-x-0 top-[calc(100%+6px)] z-20 rounded-lg border border-[#d5dce8] bg-white p-1.5 shadow-card"
        >
          {INTEREST_OPTIONS.map((o) => {
            const checked = selected.includes(o);
            return (
              <label
                key={o}
                role="option"
                aria-selected={checked}
                className={`flex cursor-pointer items-center gap-2.5 rounded-md px-2.5 py-2 text-[13px] font-medium transition-colors ${
                  checked ? "bg-brand-tint text-ink" : "text-body hover:bg-slate-50"
                }`}
              >
                <input
                  type="checkbox"
                  checked={checked}
                  onChange={() => toggle(o)}
                  className="size-4 shrink-0 accent-[#1d4ed8]"
                />
                {o}
              </label>
            );
          })}
          {selected.length > 0 && (
            <button
              type="button"
              onClick={() => setSelected([])}
              className="mt-1 w-full rounded-md px-2.5 py-2 text-left text-[12.5px] font-semibold text-brand hover:bg-brand-tint"
            >
              Clear all
            </button>
          )}
        </div>
      )}
    </div>
  );
}

export default function DemoForm({
  title = "Request a demo",
  extended = false,
}: {
  title?: string;
  extended?: boolean;
}) {
  const [state, action, pending] = useActionState(submitLead, initial);
  const router = useRouter();
  const statusRef = useRef<HTMLDivElement>(null);
  const wasPending = useRef(false);
  const savedName = useRef("");

  // On success, hand off to the Thank You page — no scroll games needed.
  useEffect(() => {
    if (wasPending.current && !pending && state.ok) {
      const q = savedName.current
      ? `/thank-you?source=demo&name=${encodeURIComponent(savedName.current)}`
      : "/thank-you?source=demo";
      router.push(q);
    }
    wasPending.current = pending;
  }, [pending, state.ok, router]);

  return (
    <form
      action={action}
      onSubmit={(e) => {
        // Block rapid double-clicks / Enter-key re-submits while sending
        if (pending) {
          e.preventDefault();
          return;
        }
        savedName.current = String(
          new FormData(e.currentTarget).get("name") ?? ""
        ).trim();
      }}
      className={`bg-white text-ink ${
        extended
          ? "rounded-[20px] p-10 shadow-hero max-lg:p-8 max-sm:p-6"
          : "rounded-[18px] p-[30px] shadow-card max-sm:p-[22px_18px]"
      }`}
      aria-label="Request a demo"
    >
      <h3
        className={`mb-[18px] font-display font-bold text-navy ${
          extended ? "text-[22px]" : "text-xl"
        }`}
      >
        {title}
      </h3>
      <div className="grid grid-cols-2 gap-x-3.5 gap-y-4 max-sm:grid-cols-1">
        <FloatInput
          id="demo-name"
          name="name"
          type="text"
          label="Full Name"
          autoComplete="name"
          required
          minLength={2}
          filter="name"
          error={state.errors?.name}
        />
        <FloatInput
          id="demo-company"
          name="company"
          type="text"
          label="Company"
          autoComplete="organization"
          required
          minLength={2}
          error={state.errors?.company}
        />
        <FloatInput
          id="demo-email"
          name="email"
          type="email"
          label="Work Email"
          autoComplete="email"
          required
          error={state.errors?.email}
        />
        <PhoneInput
          id="demo-phone"
          label="Phone"
          error={state.errors?.phone}
        />
        {extended ? (
          <>
            <FloatDropdown
              id="demo-industry"
              name="industry"
              label="Industry"
              options={INDUSTRY_OPTIONS}
              defaultValue="Manufacturing"
              required
              error={state.errors?.industry}
            />
            <FloatDropdown
              id="demo-size"
              name="companySize"
              label="Company Size"
              options={COMPANY_SIZE_OPTIONS}
              placeholder="Select size"
              error={state.errors?.companySize}
            />
            <div className="col-span-full min-w-0">
              <span className="mb-2 block text-[11.5px] font-semibold">
                Areas of Interest
              </span>
              <InterestMultiSelect />
            </div>
            <FloatTextarea
              id="demo-notes"
              name="notes"
              label="Anything we should know?"
              rows={4}
              className="col-span-full"
            />
          </>
        ) : (
          <FloatDropdown
            id="demo-industry"
            name="industry"
            label="Industry"
            options={INDUSTRY_OPTIONS}
            defaultValue="Manufacturing"
            required
            className="col-span-full max-sm:col-span-1"
            error={state.errors?.industry}
          />
        )}
      </div>

      {/* Honeypot — hidden from humans */}
      <div aria-hidden="true" className="absolute -left-[9999px] top-auto h-px w-px overflow-hidden">
        <label>
          Website
          <input name="website" type="text" tabIndex={-1} autoComplete="off" />
        </label>
      </div>

      {extended ? (
        <div className="mb-3 mt-5 flex items-start gap-2 text-xs font-normal text-muted">
          <input
            id="demo-consent"
            name="consent"
            type="checkbox"
            required
            className="mt-0.5 size-4 shrink-0 accent-[#1d4ed8]"
          />
          <span>
            <label htmlFor="demo-consent" className="cursor-pointer">
              I agree to be contacted by MxERP about my enquiry.
            </label>{" "}
            See our{" "}
            <a
              href="/privacy-policy"
              target="_blank"
              rel="noopener noreferrer"
              className="font-medium text-brand hover:underline"
            >
              privacy policy
            </a>
            .
          </span>
        </div>
      ) : (
        <label className="mb-3 mt-4 flex items-start gap-2 text-xs font-normal text-muted">
          <input name="consent" type="checkbox" required className="mt-0.5 size-4 accent-[#1d4ed8]" />
          I agree to be contacted about MxERP demo (DPDP consent).
        </label>
      )}

      <div ref={statusRef} aria-live="polite" className="min-h-[22px] text-[13px] scroll-mt-24">
        {state.message && (
          <p className={state.ok ? "text-green-700" : "text-red-600"}>{state.message}</p>
        )}
      </div>

      <button
        type="submit"
        disabled={pending}
        className={`mt-1 flex h-12 w-full items-center justify-center rounded-lg text-sm font-semibold text-white disabled:opacity-60 ${
          extended ? "bg-brand hover:bg-brand-dark" : "bg-navy"
        }`}
      >
        {pending ? "Booking…" : extended ? "Request my demo" : "Book my demo"}
      </button>
    </form>
  );
}
