"use client";

import { useEffect, useRef } from "react";
import type { PublicForm } from "@/lib/types";
import { formDataToObject, useFormSubmit } from "@/lib/forms";
import { SchemaField, layoutRows, type FieldExtras } from "./SchemaFields";

/** A CMS form (quote request, contact...) in the source design. Fields,
 *  labels, required flags and select options all come from Aggie's form
 *  builder; placeholders and side-by-side rows come from the block props. */
export default function CardForm({
  form,
  rows,
  extras,
  submitLabel,
  buttonClass = "submit-btn",
  successHtml,
  source
}: {
  form: PublicForm;
  rows: string[][];
  extras: FieldExtras;
  submitLabel: string;
  buttonClass?: string;
  successHtml: string;
  source: string;
}) {
  const { state, error, send } = useFormSubmit(form.formKey);
  const formRef = useRef<HTMLFormElement>(null);

  // Fields named in the page address are filled in (e.g. ?noticeNumber=00001).
  useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    const el = formRef.current;
    if (!el) return;
    params.forEach((v, k) => {
      const input = el.elements.namedItem(k) as unknown as HTMLInputElement | null;
      if (input && typeof input.value === "string" && !input.value) input.value = v;
    });
  }, []);

  if (state === "done") {
    return (
      <div
        className="form-success"
        style={{ display: "block" }}
        dangerouslySetInnerHTML={{ __html: successHtml || form.successMessage || "Thank you!" }}
      />
    );
  }

  const onSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const data = formDataToObject(e.currentTarget);
    if (data._hp) return;
    delete data._hp;
    await send({ ...data, ...(source ? { source } : {}) });
  };

  return (
    <form onSubmit={onSubmit} ref={formRef}>
      <input type="text" name="_hp" tabIndex={-1} autoComplete="off" style={{ position: "absolute", left: -9999 }} aria-hidden="true" />
      {layoutRows(form.fields, rows).map((group) =>
        group.length > 1 ? (
          <div className="form-row" key={group.map((g) => g.fieldKey).join("-")}>
            {group.map((f) => (
              <SchemaField key={f.fieldKey} field={f} extras={extras} />
            ))}
          </div>
        ) : (
          group[0] && <SchemaField key={group[0].fieldKey} field={group[0]} extras={extras} />
        )
      )}
      <button type="submit" className={buttonClass} disabled={state === "sending"}>
        {state === "sending" ? "Sending…" : submitLabel}
      </button>
      {state === "error" && <p className="msc-form-error">{error}</p>}
    </form>
  );
}
