"use client";

import type { PublicFormField } from "@/lib/types";

export interface FieldExtras {
  placeholders: Record<string, string>;
  hints: Record<string, string>;
}

/** One CMS form field in the source design's markup (.form-group). */
export function SchemaField({
  field,
  extras,
  value,
  onChange
}: {
  field: PublicFormField;
  extras: FieldExtras;
  value?: string;
  onChange?: (v: string) => void;
}) {
  const ph = extras.placeholders[field.fieldKey];
  const hint = extras.hints[field.fieldKey];
  const t = field.fieldType.toLowerCase();
  const controlled = value !== undefined && onChange !== undefined;
  const common = {
    id: `f_${field.fieldKey}`,
    name: field.fieldKey,
    required: field.isRequired,
    ...(controlled ? { value, onChange: (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => onChange(e.target.value) } : {})
  };

  if (t === "heading") {
    return <h4 style={{ fontWeight: 700, color: "var(--navy)", margin: "8px 0 12px" }}>{field.label}</h4>;
  }
  if (t === "checkbox") {
    return (
      <div className="form-group" style={{ display: "flex", gap: 10, alignItems: "flex-start" }}>
        <input type="checkbox" id={common.id} name={field.fieldKey} value="Yes" required={field.isRequired} style={{ width: "auto", marginTop: 4 }} />
        <label htmlFor={common.id}>{field.label}</label>
      </div>
    );
  }

  let control: React.ReactNode;
  if (t === "textarea") {
    control = <textarea {...common} placeholder={ph} />;
  } else if (t === "select" || t === "radio") {
    control = (
      <select {...common} defaultValue={controlled ? undefined : ""}>
        <option value="">{ph || "Select…"}</option>
        {(field.options || []).map((o) => (
          <option key={o} value={o}>
            {o}
          </option>
        ))}
      </select>
    );
  } else {
    const type = t === "email" ? "email" : t === "tel" ? "tel" : t === "date" ? "date" : t === "number" ? "number" : "text";
    control = <input type={type} {...common} placeholder={ph} />;
  }

  return (
    <div className="form-group">
      <label htmlFor={common.id}>
        {field.label}
        {field.isRequired && (
          <>
            {" "}
            <span className="required-mark">*</span>
          </>
        )}
      </label>
      {control}
      {hint && <div className="form-hint">{hint}</div>}
    </div>
  );
}

/** Lay fields out in rows: `rows` lists field keys to pair side by side
 *  (e.g. [["name","company"],["email","phone"]]); every other field gets its
 *  own row, in the form's own field order. */
export function layoutRows(fields: PublicFormField[], rows: string[][]): PublicFormField[][] {
  const used = new Set<string>();
  const out: PublicFormField[][] = [];
  for (const f of fields) {
    if (used.has(f.fieldKey)) continue;
    const row = rows.find((r) => r.includes(f.fieldKey));
    if (row) {
      const group = row.map((k) => fields.find((x) => x.fieldKey === k)).filter((x): x is PublicFormField => !!x);
      group.forEach((g) => used.add(g.fieldKey));
      out.push(group);
    } else {
      used.add(f.fieldKey);
      out.push([f]);
    }
  }
  return out;
}
