import { jsx as r, jsxs as m } from "react/jsx-runtime";
import { c as k } from "./schema-resolver.iYlSHQsB.js";
import { forwardRef as E, useState as N } from "react";
import { c as M } from "./index.Bxix3KXR.js";
import { _ as b } from "./twind.D7be0E5m.js";
import { g as R } from "./get.Ba1R1ACs.js";
import { a as U } from "./use-datarecord.Sa4_fax2.js";
import { b as B } from "./use-section-style.D7ZN4IXn.js";
import { u as I } from "./use-color-preset.B03-6uH7.js";
const y = b(
  `px-3 py-2 border border-base-200 rounded-md shadow-inset
  focus:(outline-2 outline-offset-0 outline-accent-500 ring-none border-accent-500)
  placeholder:text-inherit placeholder:opacity-70`
), x = ({
  fieldName: e,
  title: a,
  required: n,
  description: o,
  children: c
}) => /* @__PURE__ */ m("div", { className: "flex-1 flex flex-col gap-1", children: [
  /* @__PURE__ */ m("label", { htmlFor: e, className: "font-medium", children: [
    a,
    " ",
    n && /* @__PURE__ */ r("span", { children: "*" })
  ] }),
  c
] }), S = ({
  fieldName: e,
  fieldSchema: a,
  value: n,
  onChange: o,
  title: c,
  required: t,
  description: s
}) => /* @__PURE__ */ r(x, { fieldName: e, title: c, required: t, description: s, children: /* @__PURE__ */ m("div", { className: "flex items-center space-x-3", children: [
  /* @__PURE__ */ r(
    "input",
    {
      id: e,
      name: e,
      type: "checkbox",
      defaultChecked: typeof n == "boolean" ? n : !1,
      onChange: (i) => o(i.target.checked),
      required: t,
      className: b(
        "rounded border border-base-200 focus:outline-none focus:(ring-2 ring-accent-500 border-accent-500) text-accent-500"
      )
    }
  ),
  /* @__PURE__ */ m("label", { htmlFor: e, className: "font-medium", children: [
    c,
    " ",
    t && /* @__PURE__ */ r("span", { children: "*" })
  ] })
] }) }), z = ({
  fieldName: e,
  fieldSchema: a,
  value: n,
  onChange: o,
  title: c,
  required: t,
  description: s
}) => /* @__PURE__ */ r(x, { fieldName: e, title: c, required: t, description: s, children: /* @__PURE__ */ r(
  "input",
  {
    id: e,
    name: e,
    type: "number",
    value: typeof n == "number" ? n : "",
    onChange: (i) => {
      const p = i.target.value;
      o(p === "" ? 0 : Number(p));
    },
    placeholder: a["ui:placeholder"],
    min: a.minimum,
    max: a.maximum,
    required: t,
    className: y
  }
) }), G = ({
  fieldName: e,
  fieldSchema: a,
  value: n,
  onChange: o,
  title: c,
  required: t,
  description: s
}) => {
  var v;
  const l = a.enum || [], i = typeof n == "string" ? n : "", p = (v = a.metadata) == null ? void 0 : v["ui:widget"], h = l.reduce(
    (u, f) => f.length > u.length ? f : u,
    a["ui:placeholder"] || "Choose an option"
  ), d = Math.max(h.length * 0.6 + 5, 10), g = l.length === 1 ? "checkbox" : p;
  return g === "checkbox" ? /* @__PURE__ */ r("div", { className: "flex-1 flex flex-col gap-1", children: /* @__PURE__ */ m("fieldset", { children: [
    /* @__PURE__ */ m("legend", { className: "block text-sm font-medium ", children: [
      c,
      " ",
      t && /* @__PURE__ */ r("span", { className: "text-red-500", children: "*" })
    ] }),
    /* @__PURE__ */ r("div", { className: "space-y-2 mt-2", children: l.map((u) => /* @__PURE__ */ m("label", { className: "flex items-center space-x-2", children: [
      /* @__PURE__ */ r(
        "input",
        {
          type: "checkbox",
          name: e,
          value: u,
          onChange: (f) => o(f.target.checked ? f.target.value : ""),
          required: t,
          className: b(
            "rounded border border-base-200 focus:outline-none focus:(ring-2 ring-accent-500 border-accent-500) text-accent-500"
          )
        }
      ),
      /* @__PURE__ */ r("span", { className: "text-sm", children: u })
    ] }, u)) })
  ] }) }) : g === "radio" ? /* @__PURE__ */ r("div", { className: "flex-1 flex flex-col gap-1", children: /* @__PURE__ */ m("fieldset", { children: [
    /* @__PURE__ */ m("legend", { className: "font-medium", children: [
      c,
      " ",
      t && /* @__PURE__ */ r("span", { children: "*" })
    ] }),
    /* @__PURE__ */ r("div", { className: "space-y-2 mt-2", children: l.map((u) => /* @__PURE__ */ m("label", { className: "flex items-center space-x-2", children: [
      /* @__PURE__ */ r(
        "input",
        {
          type: "radio",
          name: e,
          value: u,
          checked: i === u,
          onChange: (f) => o(f.target.value),
          required: t,
          className: "border border-base-200 focus:outline-none focus:(ring-2 ring-accent-500 border-accent-500) text-accent-500"
        }
      ),
      /* @__PURE__ */ r("span", { children: u })
    ] }, u)) })
  ] }) }) : /* @__PURE__ */ r(x, { fieldName: e, title: c, required: t, description: s, children: /* @__PURE__ */ m(
    "select",
    {
      id: e,
      name: e,
      value: i,
      onChange: (u) => o(u.target.value),
      required: t,
      className: b(y, "w-full"),
      style: { minWidth: `${d}rem` },
      children: [
        /* @__PURE__ */ r("option", { value: "", disabled: !0, children: a["ui:placeholder"] || a.description || "Choose an option" }),
        l.map((u) => /* @__PURE__ */ r("option", { value: u, children: u }, u))
      ]
    }
  ) });
}, X = ({
  fieldName: e,
  fieldSchema: a,
  value: n,
  onChange: o,
  title: c,
  required: t,
  description: s
}) => /* @__PURE__ */ r(x, { fieldName: e, title: c, required: t, description: s, children: /* @__PURE__ */ r(
  "input",
  {
    id: e,
    name: e,
    type: "email",
    value: typeof n == "string" ? n : "",
    onChange: (i) => o(i.target.value),
    placeholder: a["ui:placeholder"],
    required: t,
    className: y
  }
) }), _ = ({
  fieldName: e,
  fieldSchema: a,
  value: n,
  onChange: o,
  title: c,
  required: t,
  description: s
}) => /* @__PURE__ */ r(x, { fieldName: e, title: c, required: t, description: s, children: /* @__PURE__ */ r(
  "input",
  {
    id: e,
    name: e,
    type: "url",
    value: typeof n == "string" ? n : "",
    onChange: (i) => o(i.target.value),
    placeholder: a["ui:placeholder"],
    required: t,
    className: y
  }
) }), H = ({
  fieldName: e,
  fieldSchema: a,
  value: n,
  onChange: o,
  title: c,
  required: t,
  description: s
}) => /* @__PURE__ */ r(x, { fieldName: e, title: c, required: t, description: s, children: /* @__PURE__ */ r(
  "input",
  {
    id: e,
    name: e,
    type: "date",
    value: typeof n == "string" ? n : "",
    onChange: (i) => o(i.target.value),
    required: t,
    className: y
  }
) }), J = ({
  fieldName: e,
  fieldSchema: a,
  value: n,
  onChange: o,
  title: c,
  required: t,
  description: s
}) => /* @__PURE__ */ r(x, { fieldName: e, title: c, required: t, description: s, children: /* @__PURE__ */ r(
  "input",
  {
    id: e,
    name: e,
    type: "datetime-local",
    value: typeof n == "string" ? n : "",
    onChange: (i) => o(i.target.value),
    required: t,
    className: y
  }
) }), K = ({
  fieldName: e,
  fieldSchema: a,
  value: n,
  onChange: o,
  title: c,
  required: t,
  description: s
}) => /* @__PURE__ */ r(x, { fieldName: e, title: c, required: t, description: s, children: /* @__PURE__ */ r(
  "input",
  {
    id: e,
    name: e,
    type: "text",
    value: typeof n == "string" ? n : "",
    onChange: (i) => o(i.target.value),
    placeholder: a["ui:placeholder"],
    minLength: a.minLength,
    maxLength: a.maxLength,
    required: t,
    className: b(y)
  }
) }), Q = ({
  fieldName: e,
  fieldSchema: a,
  value: n,
  onChange: o,
  title: c,
  required: t,
  description: s
}) => /* @__PURE__ */ r(x, { fieldName: e, title: c, required: t, description: s, children: /* @__PURE__ */ r(
  "textarea",
  {
    id: e,
    name: e,
    value: typeof n == "string" ? n : "",
    onChange: (i) => o(i.target.value),
    placeholder: a["ui:placeholder"],
    minLength: a.minLength,
    maxLength: a.maxLength,
    required: t,
    rows: 4,
    className: y
  }
) });
function Y(e) {
  var a;
  if (e.enum && Array.isArray(e.enum) && e.enum.length > 0)
    return "datarecord-select";
  if (e.type === "string" && !e.format && ((a = e.metadata) != null && a["ui:multiline"]))
    return "datarecord-textarea";
  if (e.type === "string")
    switch (e.format) {
      case "email":
        return "datarecord-email";
      case "uri":
        return "datarecord-url";
      case "date":
        return "datarecord-date";
      case "date-time":
        return "datarecord-datetime";
      default:
        return "datarecord-string";
    }
  return e.type === "number" ? "datarecord-number" : e.type === "boolean" ? "datarecord-boolean" : null;
}
function Z(e, a, n, o, c, t, s) {
  const l = R(c, t) ?? n.default, i = Array.isArray(o.required) ? o.required.includes(a) : !1, p = n.title ?? n["ui:title"], h = n.description ?? n["ui:description"], d = {
    fieldName: a,
    fieldSchema: n,
    value: l,
    onChange: (g) => s({ [t]: g }, t),
    title: p || a,
    required: i,
    description: h
  };
  switch (e) {
    case "datarecord-string":
      return /* @__PURE__ */ r(K, { ...d }, `field-${t}`);
    case "datarecord-textarea":
      return /* @__PURE__ */ r(Q, { ...d }, `field-${t}`);
    case "datarecord-select":
      return /* @__PURE__ */ r(G, { ...d }, `field-${t}`);
    case "datarecord-number":
      return /* @__PURE__ */ r(z, { ...d }, `field-${t}`);
    case "datarecord-boolean":
      return /* @__PURE__ */ r(S, { ...d }, `field-${t}`);
    case "datarecord-email":
      return /* @__PURE__ */ r(X, { ...d }, `field-${t}`);
    case "datarecord-url":
      return /* @__PURE__ */ r(_, { ...d }, `field-${t}`);
    case "datarecord-date":
      return /* @__PURE__ */ r(H, { ...d }, `field-${t}`);
    case "datarecord-datetime":
      return /* @__PURE__ */ r(J, { ...d }, `field-${t}`);
    default:
      return null;
  }
}
function q(e, a, n) {
  const o = [];
  return Object.entries(e.properties).sort(([t, s], [l, i]) => {
    var v, u;
    const p = k(s), h = k(i), d = (v = p.metadata) == null ? void 0 : v.order, g = (u = h.metadata) == null ? void 0 : u.order;
    return d !== void 0 && g !== void 0 ? d - g : d !== void 0 ? -1 : g !== void 0 ? 1 : t.localeCompare(l);
  }).forEach(([t, s]) => {
    var h;
    const l = k(s);
    if (l["ui:field"] === "hidden")
      return;
    if ((h = l.metadata) != null && h.filter) {
      const d = l.metadata.filter;
      if (!d(e, a)) {
        console.warn("processDatarecordSchemaToFields: Field filter returned false for", t);
        return;
      }
    }
    const i = t, p = Y(l);
    if (p) {
      const d = Z(
        p,
        t,
        l,
        e,
        a,
        i,
        n
      );
      d ? o.push(d) : console.log("!!! No datarecord field component created for", t);
    } else
      console.log("!!! Unknown datarecord field type for", t, l);
  }), o;
}
const ie = E((e, a) => {
  const { brick: n } = e, o = I(n), c = B(n), [t, s] = N("idle"), { button: l, buttonPosition: i, direction: p, ...h } = c, {
    title: d,
    buttonLabel: g,
    successMessage: v,
    errorMessage: u,
    intro: f,
    datarecordId: F,
    editable: D = !0
  } = n.props, L = n.props.button || {}, C = U(F), [$, O] = N({}), j = (w, V) => {
    const A = { ...$, ...w };
    O(A);
  }, T = (w) => {
    if (w.preventDefault(), D) {
      M("This form is not clickable in edit mode but will lead to form submission when published.", {
        id: "form-no-click-toast",
        style: {
          minWidth: "max-content"
        }
      });
      return;
    }
    s("submitting"), fetch(new URL(window.location.href), {
      method: "POST",
      body: new FormData(w.target),
      headers: {
        "X-DataRecord-Id": F
      }
    }).then((V) => {
      V.ok ? s("success") : s("error");
    }).catch((V) => {
      s("error");
    });
  };
  if (F && !C)
    return D ? /* @__PURE__ */ r("div", { ref: a, className: "p-4 border border-red-200 bg-red-50 text-red-600 rounded", children: "Error loading datarecord" }) : null;
  if (!C)
    return /* @__PURE__ */ r(
      "div",
      {
        ref: a,
        className: b(
          "flex-grow min-h-fit text-center shrink-0 p-4 flex items-center justify-center",
          Object.values(h),
          o.main
        ),
        children: F ? "Loading database..." : /* @__PURE__ */ m("span", { children: [
          "Select a database",
          /* @__PURE__ */ r("br", {}),
          " you want to connect this form with."
        ] })
      }
    );
  const P = C.schema, W = q(P, $, j);
  return /* @__PURE__ */ m(
    "div",
    {
      ref: a,
      className: b("flex-grow shrink-0 min-h-fit max-w-fit", Object.values(h), o.main),
      children: [
        d && /* @__PURE__ */ r("h2", { className: "form-title text-[110%] font-semibold mb-4", children: d }),
        f && /* @__PURE__ */ r("p", { className: "form-intro  mb-6", children: f }),
        /* @__PURE__ */ m("form", { onSubmit: T, className: "flex flex-col gap-4", children: [
          /* @__PURE__ */ r("div", { className: b("flex gap-4 @mobile:flex-col", p), children: W }),
          t === "error" && /* @__PURE__ */ r("div", { children: u }),
          t === "success" && /* @__PURE__ */ r("div", { children: v }),
          /* @__PURE__ */ r("div", { className: b("flex pt-1", Object.values(i)), children: /* @__PURE__ */ r(
            "button",
            {
              type: "submit",
              disabled: t === "submitting",
              className: b(
                "btn @mobile:min-w-full",
                L.color,
                L.size === "wide" ? "w-full" : "",
                Object.values(l)
              ),
              children: g || "Submit"
            }
          ) })
        ] })
      ]
    }
  );
});
export {
  ie as default
};
//# sourceMappingURL=form.D8kiLsO8.js.map
