"use client";

import { useId, useState } from "react";
import { HONEYPOT_FIELD } from "@/lib/forms/schema";

const fieldCls = "w-full rounded-md border border-border bg-[var(--background)] px-3 py-2 text-sm aria-[invalid=true]:border-red-600";

/** Visitor-facing rapport request form. Posts JSON to the website's own origin. */
export function RapportForm({ token, targets, initialTarget }: { token: string; targets: { id: string; title: string }[]; initialTarget: string }) {
  const uid = useId();
  const [v, setV] = useState({ targetEntryId: initialTarget, name: "", email: "", company: "", message: "" });
  const [trap, setTrap] = useState("");
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [state, setState] = useState<"idle" | "sending" | "done">("idle");
  const [message, setMessage] = useState<string | null>(null);
  const set = (k: keyof typeof v, val: string) => setV((s) => ({ ...s, [k]: val }));

  async function submit(e: React.FormEvent) {
    e.preventDefault();
    if (state === "sending") return;
    setState("sending"); setErrors({}); setMessage(null);
    try {
      const res = await fetch("/api/public/rapport", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ values: v, token, [HONEYPOT_FIELD]: trap }) });
      const body = (await res.json().catch(() => ({}))) as { ok?: boolean; error?: string; fieldErrors?: Record<string, string> };
      if (res.ok && body.ok) { setState("done"); return; }
      setErrors(body.fieldErrors ?? {}); setMessage(body.error ?? "Something went wrong. Please try again.");
    } catch { setMessage("We could not reach the server. Check your connection and try again."); }
    setState("idle");
  }

  if (state === "done") return <p role="status" className="rounded-md border border-border p-4">Thank you. Your request has been sent and will be reviewed.</p>;

  const row = (k: keyof typeof v, label: string, node: (id: string, err?: string) => React.ReactNode, required = false) => {
    const id = `${uid}-${k}`; const err = errors[k];
    return (
      <div className="space-y-1">
        <label htmlFor={id} className="block text-sm font-medium">{label}{required ? <span aria-hidden> *</span> : null}{required ? <span className="sr-only"> (required)</span> : null}</label>
        {node(id, err)}
        {err ? <p id={`${id}-err`} role="alert" className="text-xs text-red-700">{err}</p> : null}
      </div>
    );
  };
  const common = (id: string, err?: string) => ({ id, "aria-invalid": err ? true : undefined, "aria-describedby": err ? `${id}-err` : undefined }) as const;

  return (
    <form onSubmit={submit} noValidate className="mx-auto max-w-xl space-y-4 text-left">
      {message ? <p role="alert" className="rounded-md border border-red-600 p-3 text-sm">{message}</p> : null}
      {targets.length ? row("targetEntryId", "Who would you like to meet?", (id, err) => (
        <select {...common(id, err)} value={v.targetEntryId} onChange={(e) => set("targetEntryId", e.target.value)} className={fieldCls}><option value="">No one in particular</option>{targets.map((t) => <option key={t.id} value={t.id}>{t.title}</option>)}</select>
      )) : null}
      {row("name", "Your name", (id, err) => <input {...common(id, err)} type="text" autoComplete="name" maxLength={120} value={v.name} onChange={(e) => set("name", e.target.value)} className={fieldCls} />, true)}
      {row("email", "Email", (id, err) => <input {...common(id, err)} type="email" autoComplete="email" maxLength={254} value={v.email} onChange={(e) => set("email", e.target.value)} className={fieldCls} />, true)}
      {row("company", "Company", (id, err) => <input {...common(id, err)} type="text" autoComplete="organization" maxLength={160} value={v.company} onChange={(e) => set("company", e.target.value)} className={fieldCls} />)}
      {row("message", "Why would you like to meet?", (id, err) => <textarea {...common(id, err)} rows={5} maxLength={2000} value={v.message} onChange={(e) => set("message", e.target.value)} className={fieldCls} />, true)}
      <div aria-hidden style={{ position: "absolute", left: "-10000px", width: 1, height: 1, overflow: "hidden" }}>
        <label>Leave this empty<input type="text" name={HONEYPOT_FIELD} tabIndex={-1} autoComplete="off" value={trap} onChange={(e) => setTrap(e.target.value)} /></label>
      </div>
      <button type="submit" disabled={state === "sending"} className="inline-flex items-center rounded-md bg-[var(--primary)] px-5 py-2.5 text-sm font-semibold text-white disabled:opacity-60">{state === "sending" ? "Sending…" : "Send request"}</button>
    </form>
  );
}
