"use client";

import { useState, useRef, type FormEvent } from "react";
import RecaptchaV2, { type RecaptchaHandle } from "@/components/RecaptchaV2";

const WP_SUBMIT_URL =
  (process.env.NEXT_PUBLIC_WORDPRESS_URL || "") +
  "/wp-json/sigma/v1/submit-lead";

type Status = "idle" | "sending" | "sent" | "error";

export default function ContactForm({
  submitLabel = "Send message",
  smsConsentText,
}: {
  submitLabel?: string;
  smsConsentText?: string;
}) {
  const [formActive, setFormActive] = useState(false);
  const [status, setStatus] = useState<Status>("idle");
  const [error, setError] = useState<string>("");
  const recaptchaRef = useRef<RecaptchaHandle>(null);

  async function onSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setFormActive(true);
    setStatus("sending");
    setError("");

    const recaptchaToken = recaptchaRef.current?.getToken() ?? "";
    if (!recaptchaToken) {
      setStatus("error");
      setError("Please complete the reCAPTCHA verification.");
      return;
    }

    const form = e.currentTarget;
    const data = new FormData(form);

    const payload: Record<string, unknown> = {
      firstName: data.get("first_name"),
      lastName: data.get("last_name"),
      company: data.get("company"),
      email: data.get("email"),
      phone: data.get("phone"),
      message: data.get("message"),
      smsConsent: data.get("sms_consent") === "on",
      recaptcha_token: recaptchaToken,
    };

    try {
      const res = await fetch(WP_SUBMIT_URL, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });
      const raw = await res.text();
      const brace = raw.lastIndexOf("{");
      const json = (
        brace >= 0 ? JSON.parse(raw.slice(brace)) : { ok: false }
      ) as {
        ok: boolean;
        message?: string;
        entry_id?: number;
      };
      if (json.ok) {
        setStatus("sent");
        form.reset();
      } else {
        setStatus("error");
        setError(json.message ?? "Something went wrong.");
      }
    } catch {
      setStatus("error");
      setError("Network error. Please try again or call us.");
    }
  }

  if (status === "sent") {
    return (
      <div style={{
        padding: "16px 18px",
        borderRadius: 12,
        background: "rgba(19,163,166,.12)",
        color: "#02474b",
        fontSize: 15,
        fontWeight: 700,
      }}>
        Thanks — we&rsquo;ll be in touch soon.
      </div>
    );
  }

  return (
    <form onSubmit={onSubmit} style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
      <input type="text" name="first_name" placeholder="First name" required
        onFocus={() => { if (!formActive) setFormActive(true); }}
        style={{ padding: "14px 16px", border: "1px solid rgba(2,47,49,.16)", borderRadius: 12, background: "rgba(255,255,255,.7)", fontSize: 15 }} />
      <input type="text" name="last_name" placeholder="Last name" required
        style={{ padding: "14px 16px", border: "1px solid rgba(2,47,49,.16)", borderRadius: 12, background: "rgba(255,255,255,.7)", fontSize: 15 }} />
      <input type="text" name="company" placeholder="Company"
        style={{ gridColumn: "1 / -1", padding: "14px 16px", border: "1px solid rgba(2,47,49,.16)", borderRadius: 12, background: "rgba(255,255,255,.7)", fontSize: 15 }} />
      <input type="email" name="email" placeholder="Email" required
        style={{ padding: "14px 16px", border: "1px solid rgba(2,47,49,.16)", borderRadius: 12, background: "rgba(255,255,255,.7)", fontSize: 15 }} />
      <input type="tel" name="phone" placeholder="Phone" required
        style={{ padding: "14px 16px", border: "1px solid rgba(2,47,49,.16)", borderRadius: 12, background: "rgba(255,255,255,.7)", fontSize: 15 }} />
      <textarea name="message" placeholder="How can we help?"
        style={{ gridColumn: "1 / -1", padding: "14px 16px", border: "1px solid rgba(2,47,49,.16)", borderRadius: 12, background: "rgba(255,255,255,.7)", fontSize: 15, minHeight: 110, resize: "vertical" }} />
      <div style={{ gridColumn: "1 / -1" }}>
        {formActive && <RecaptchaV2 ref={recaptchaRef} />}
      </div>
      <button type="submit" disabled={status === "sending"} className="hv0"
        style={{ gridColumn: "1 / -1", marginTop: 4, background: "linear-gradient(135deg,#13a3a6,#006568)", color: "#fff", fontWeight: 700, fontSize: 16, padding: 16, border: 0, borderRadius: 999, cursor: status === "sending" ? "default" : "pointer", boxShadow: "0 14px 30px rgba(0,101,104,.3)", opacity: status === "sending" ? 0.6 : 1 }}>
        {status === "sending" ? "Sending…" : submitLabel}
      </button>
      {error && (
        <p style={{ gridColumn: "1 / -1", margin: 0, color: "#b00020", fontSize: 13 }}>
          {error}
        </p>
      )}
      {smsConsentText && (
        <label style={{ gridColumn: "1 / -1", display: "flex", gap: 9, alignItems: "flex-start", fontSize: 12, lineHeight: 1.5, color: "#63686d" }}>
          <input type="checkbox" name="sms_consent" style={{ marginTop: 3 }} />
          <span>{smsConsentText}</span>
        </label>
      )}
    </form>
  );
}
