"use client";

import { useRef, useState, type FormEvent } from "react";
import { ArrowRight, Check, Copy, LoaderCircle } from "lucide-react";
import { LIMITS, normalise, validate, type InquiryErrors, type InquiryInput } from "@/lib/inquiry";
import type { Dictionary, Locale } from "@/lib/i18n";

type Status = "idle" | "sending" | "success" | "error";
type Field = Exclude<keyof InquiryInput, "website" | "locale">;

const EMPTY: Record<Field, string> = { name: "", company: "", email: "", phone: "", subject: "", message: "" };
const REQUIRED: Field[] = ["name", "company", "email", "subject", "message"];

export default function InquiryForm({ t, locale }: { t: Dictionary["inquiry"]; locale: Locale }) {
  const [values, setValues] = useState(EMPTY);
  const [errors, setErrors] = useState<InquiryErrors>({});
  const [touched, setTouched] = useState<Partial<Record<Field, boolean>>>({});
  const [status, setStatus] = useState<Status>("idle");
  const [serverError, setServerError] = useState<string>("");
  const [copied, setCopied] = useState(false);
  const [notConfigured, setNotConfigured] = useState(false);
  const formRef = useRef<HTMLFormElement>(null);
  const statusRef = useRef<HTMLDivElement>(null);
  const honeypot = useRef<HTMLInputElement>(null);

  const set = (k: Field, v: string) => {
    const next = { ...values, [k]: v };
    setValues(next);
    if (touched[k]) setErrors(validate(normalise(next)));
  };
  const blur = (k: Field) => {
    setTouched((t0) => ({ ...t0, [k]: true }));
    setErrors(validate(normalise(values)));
  };

  const onSubmit = async (e: FormEvent) => {
    e.preventDefault();
    const input = normalise({ ...values, website: honeypot.current?.value ?? "", locale });
    const errs = validate(input);
    setErrors(errs);
    setTouched({ name: true, company: true, email: true, phone: true, subject: true, message: true });
    if (Object.keys(errs).length) {
      setServerError(t.errors.summary);
      setStatus("error");
      const first = (Object.keys(EMPTY) as Field[]).find((k) => errs[k]);
      if (first) formRef.current?.querySelector<HTMLElement>(`[name="${first}"]`)?.focus();
      return;
    }
    setStatus("sending");
    setServerError("");
    setNotConfigured(false);
    try {
      const res = await fetch("/api/inquiry", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(input),
      });
      const data = (await res.json().catch(() => ({}))) as { ok?: boolean; code?: string; errors?: InquiryErrors };
      if (res.ok && data.ok) {
        setStatus("success");
        setValues(EMPTY);
        setTouched({});
        requestAnimationFrame(() => statusRef.current?.focus());
        return;
      }
      if (data.code === "invalid" && data.errors) setErrors(data.errors);
      setNotConfigured(data.code === "not_configured");
      setServerError(
        data.code === "not_configured"
          ? t.errors.notConfigured
          : data.code === "rate_limited"
            ? t.errors.rateLimited
            : data.code === "invalid"
              ? t.errors.summary
              : t.errors.generic,
      );
      setStatus("error");
    } catch {
      setServerError(t.errors.generic);
      setStatus("error");
    }
    requestAnimationFrame(() => statusRef.current?.focus());
  };

  const copyMessage = async () => {
    const text = [
      `${t.fields.name}: ${values.name}`,
      `${t.fields.company}: ${values.company}`,
      `${t.fields.email}: ${values.email}`,
      `${t.fields.phone}: ${values.phone}`,
      `${t.fields.subject}: ${values.subject}`,
      "",
      values.message,
    ].join("\n");
    try {
      await navigator.clipboard.writeText(text);
      setCopied(true);
      setTimeout(() => setCopied(false), 2500);
    } catch {
      /* clipboard unavailable — the text stays in the form */
    }
  };

  const err = (k: Field) => (touched[k] && errors[k] ? t.errors[errors[k]!] : "");

  if (status === "success") {
    return (
      <div ref={statusRef} tabIndex={-1} role="status" className="border border-gold/40 p-8 sm:p-12">
        <span className="flex h-14 w-14 items-center justify-center rounded-full bg-gold text-navy-ink" aria-hidden="true">
          <Check size={26} />
        </span>
        <p className="display display-sm mt-8">{t.successTitle}</p>
        <p className="body-copy mt-4 text-white/75">{t.successBody}</p>
        <button type="button" className="btn mt-10 text-white" onClick={() => setStatus("idle")}>
          {t.another}
        </button>
      </div>
    );
  }

  const input = (k: Field, type: string, autoComplete: string, extra: Record<string, unknown> = {}) => {
    const id = `inq-${k}`;
    const msg = err(k);
    const required = REQUIRED.includes(k);
    return (
      <div className="field">
        <label htmlFor={id} className="field-label">
          {t.fields[k]}
          {required && <span aria-hidden="true"> *</span>}
        </label>
        <input
          id={id}
          name={k}
          type={type}
          autoComplete={autoComplete}
          required={required}
          value={values[k]}
          placeholder={t.placeholders[k as keyof typeof t.placeholders]}
          onChange={(e) => set(k, e.target.value)}
          onBlur={() => blur(k)}
          aria-invalid={msg ? true : undefined}
          aria-describedby={msg ? `${id}-err` : undefined}
          className="field-input"
          {...extra}
        />
        {msg && (
          <p id={`${id}-err`} className="mt-2 text-sm text-[#f3a397]">
            {msg}
          </p>
        )}
      </div>
    );
  };

  const subjectErr = err("subject");
  const messageErr = err("message");

  return (
    <form ref={formRef} onSubmit={onSubmit} noValidate className="space-y-9" aria-describedby="inq-consent">
      <div className="grid gap-9 sm:grid-cols-2">
        {input("name", "text", "name", { maxLength: LIMITS.name })}
        {input("company", "text", "organization", { maxLength: LIMITS.company })}
        {input("email", "email", "email", { maxLength: LIMITS.email, inputMode: "email" })}
        {input("phone", "tel", "tel", { maxLength: LIMITS.phone, inputMode: "tel" })}
      </div>

      <div className="field">
        <label htmlFor="inq-subject" className="field-label">
          {t.fields.subject}
          <span aria-hidden="true"> *</span>
        </label>
        <select
          id="inq-subject"
          name="subject"
          required
          value={values.subject}
          onChange={(e) => set("subject", e.target.value)}
          onBlur={() => blur("subject")}
          aria-invalid={subjectErr ? true : undefined}
          aria-describedby={subjectErr ? "inq-subject-err" : undefined}
          className="field-input"
        >
          <option value="" disabled>
            {t.subjectPlaceholder}
          </option>
          {t.subjects.map((s) => (
            <option key={s} value={s}>
              {s}
            </option>
          ))}
        </select>
        {subjectErr && (
          <p id="inq-subject-err" className="mt-2 text-sm text-[#f3a397]">
            {subjectErr}
          </p>
        )}
      </div>

      <div className="field">
        <label htmlFor="inq-message" className="field-label">
          {t.fields.message}
          <span aria-hidden="true"> *</span>
        </label>
        <textarea
          id="inq-message"
          name="message"
          required
          rows={5}
          maxLength={LIMITS.message}
          value={values.message}
          placeholder={t.placeholders.message}
          onChange={(e) => set("message", e.target.value)}
          onBlur={() => blur("message")}
          aria-invalid={messageErr ? true : undefined}
          aria-describedby={messageErr ? "inq-message-err" : undefined}
          className="field-input resize-y"
        />
        {messageErr && (
          <p id="inq-message-err" className="mt-2 text-sm text-[#f3a397]">
            {messageErr}
          </p>
        )}
      </div>

      {/* Honeypot (hidden from people and assistive tech) */}
      <div aria-hidden="true" className="absolute -left-[9999px] h-px w-px overflow-hidden">
        <label htmlFor="inq-website">Website</label>
        <input ref={honeypot} id="inq-website" name="website" type="text" tabIndex={-1} autoComplete="off" />
      </div>

      <div ref={statusRef} tabIndex={-1} aria-live="polite" className="outline-none">
        {status === "error" && serverError && (
          <div role="alert" className="border-l-2 border-[#f3a397] bg-white/5 p-5 text-sm leading-relaxed text-white/90">
            <p>{serverError}</p>
            {notConfigured && (
              <button type="button" onClick={copyMessage} className="mt-4 inline-flex min-h-[44px] items-center gap-2 font-semibold text-gold-light underline-offset-4 hover:underline">
                {copied ? <Check size={16} /> : <Copy size={16} />}
                {copied ? t.copied : t.copy}
              </button>
            )}
          </div>
        )}
      </div>

      <div className="flex flex-col-reverse gap-6 sm:flex-row sm:items-center sm:justify-between">
        <p id="inq-consent" className="text-xs text-white/55">
          {t.consent}
        </p>
        <button type="submit" className="btn btn-solid justify-center" disabled={status === "sending"} aria-busy={status === "sending"}>
          {status === "sending" ? (
            <>
              <LoaderCircle size={16} className="animate-spin" aria-hidden="true" />
              {t.sending}
            </>
          ) : (
            <>
              {t.submit}
              <ArrowRight size={16} aria-hidden="true" />
            </>
          )}
        </button>
      </div>
    </form>
  );
}
