import { jsx as r, jsxs as m } from "react/jsx-runtime";
import { aK as k } from "./use-page-data.BYLN5MSa.js";
import { a as h } from "./twind.Cg2g8xBZ.js";
import { g as P } from "./get.D6Ij4kC_.js";
import { forwardRef as R, useState as $ } from "react";
import { a as W } from "./use-datarecord.B3zMFYnX.js";
import { b as E } from "./use-section-style.CqWLdjop.js";
import { B as D } from "./BrickRoot.CQgjTuOI.js";
const x = h(
  `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`
), b = ({
  fieldName: e,
  title: a,
  required: n,
  description: c,
  children: s
}) => /* @__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: "*" })
  ] }),
  s
] }), M = ({
  fieldName: e,
  fieldSchema: a,
  value: n,
  onChange: c,
  title: s,
  required: t,
  description: o
}) => /* @__PURE__ */ r(b, { fieldName: e, title: s, required: t, description: o, 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: (l) => c(l.target.checked),
      required: t,
      className: h(
        "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: [
    s,
    " ",
    t && /* @__PURE__ */ r("span", { children: "*" })
  ] })
] }) }), U = ({
  fieldName: e,
  fieldSchema: a,
  value: n,
  onChange: c,
  title: s,
  required: t,
  description: o
}) => /* @__PURE__ */ r(b, { fieldName: e, title: s, required: t, description: o, children: /* @__PURE__ */ r(
  "input",
  {
    id: e,
    name: e,
    type: "number",
    value: typeof n == "number" ? n : "",
    onChange: (l) => {
      const u = l.target.value;
      c(u === "" ? 0 : Number(u));
    },
    placeholder: a["ui:placeholder"],
    min: a.minimum,
    max: a.maximum,
    required: t,
    className: x
  }
) }), I = ({
  fieldName: e,
  fieldSchema: a,
  value: n,
  onChange: c,
  title: s,
  required: t,
  description: o
}) => {
  const i = a.enum || [], l = typeof n == "string" ? n : "", u = a.metadata?.["ui:widget"], f = i.reduce(
    (d, g) => g.length > d.length ? g : d,
    // @ts-ignore
    a["ui:placeholder"] || "Choose an option"
  ), p = Math.max(f.length * 0.6 + 5, 10), y = i.length === 1 ? "checkbox" : u;
  return y === "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: [
      s,
      " ",
      t && /* @__PURE__ */ r("span", { className: "text-red-500", children: "*" })
    ] }),
    /* @__PURE__ */ r("div", { className: "space-y-2 mt-2", children: i.map((d) => /* @__PURE__ */ m("label", { className: "flex items-center space-x-2", children: [
      /* @__PURE__ */ r(
        "input",
        {
          type: "checkbox",
          name: e,
          value: d,
          onChange: (g) => c(g.target.checked ? g.target.value : ""),
          required: t,
          className: h(
            "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: d })
    ] }, d)) })
  ] }) }) : y === "radio" ? /* @__PURE__ */ r("div", { className: "flex-1 flex flex-col gap-1", children: /* @__PURE__ */ m("fieldset", { children: [
    /* @__PURE__ */ m("legend", { className: "font-medium", children: [
      s,
      " ",
      t && /* @__PURE__ */ r("span", { children: "*" })
    ] }),
    /* @__PURE__ */ r("div", { className: "space-y-2 mt-2", children: i.map((d) => /* @__PURE__ */ m("label", { className: "flex items-center space-x-2", children: [
      /* @__PURE__ */ r(
        "input",
        {
          type: "radio",
          name: e,
          value: d,
          checked: l === d,
          onChange: (g) => c(g.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: d })
    ] }, d)) })
  ] }) }) : /* @__PURE__ */ r(b, { fieldName: e, title: s, required: t, description: o, children: /* @__PURE__ */ m(
    "select",
    {
      id: e,
      name: e,
      value: l,
      onChange: (d) => c(d.target.value),
      required: t,
      className: h(x, "w-full"),
      style: { minWidth: `${p}rem` },
      children: [
        /* @__PURE__ */ r("option", { value: "", disabled: !0, children: a["ui:placeholder"] || // @ts-ignore
        a.description || "Choose an option" }),
        i.map((d) => /* @__PURE__ */ r("option", { value: d, children: d }, d))
      ]
    }
  ) });
}, z = ({
  fieldName: e,
  fieldSchema: a,
  value: n,
  onChange: c,
  title: s,
  required: t,
  description: o
}) => /* @__PURE__ */ r(b, { fieldName: e, title: s, required: t, description: o, children: /* @__PURE__ */ r(
  "input",
  {
    id: e,
    name: e,
    type: "email",
    value: typeof n == "string" ? n : "",
    onChange: (l) => c(l.target.value),
    placeholder: a["ui:placeholder"],
    required: t,
    className: x
  }
) }), G = ({
  fieldName: e,
  fieldSchema: a,
  value: n,
  onChange: c,
  title: s,
  required: t,
  description: o
}) => /* @__PURE__ */ r(b, { fieldName: e, title: s, required: t, description: o, children: /* @__PURE__ */ r(
  "input",
  {
    id: e,
    name: e,
    type: "url",
    value: typeof n == "string" ? n : "",
    onChange: (l) => c(l.target.value),
    placeholder: a["ui:placeholder"],
    required: t,
    className: x
  }
) }), K = ({
  fieldName: e,
  fieldSchema: a,
  value: n,
  onChange: c,
  title: s,
  required: t,
  description: o
}) => /* @__PURE__ */ r(b, { fieldName: e, title: s, required: t, description: o, children: /* @__PURE__ */ r(
  "input",
  {
    id: e,
    name: e,
    type: "date",
    value: typeof n == "string" ? n : "",
    onChange: (l) => c(l.target.value),
    required: t,
    className: x
  }
) }), X = ({
  fieldName: e,
  fieldSchema: a,
  value: n,
  onChange: c,
  title: s,
  required: t,
  description: o
}) => /* @__PURE__ */ r(b, { fieldName: e, title: s, required: t, description: o, children: /* @__PURE__ */ r(
  "input",
  {
    id: e,
    name: e,
    type: "datetime-local",
    value: typeof n == "string" ? n : "",
    onChange: (l) => c(l.target.value),
    required: t,
    className: x
  }
) }), H = ({
  fieldName: e,
  fieldSchema: a,
  value: n,
  onChange: c,
  title: s,
  required: t,
  description: o
}) => /* @__PURE__ */ r(b, { fieldName: e, title: s, required: t, description: o, children: /* @__PURE__ */ r(
  "input",
  {
    id: e,
    name: e,
    type: "text",
    value: typeof n == "string" ? n : "",
    onChange: (l) => c(l.target.value),
    placeholder: a["ui:placeholder"],
    minLength: a.minLength,
    maxLength: a.maxLength,
    required: t,
    className: h(x)
  }
) }), J = ({
  fieldName: e,
  fieldSchema: a,
  value: n,
  onChange: c,
  title: s,
  required: t,
  description: o
}) => /* @__PURE__ */ r(b, { fieldName: e, title: s, required: t, description: o, children: /* @__PURE__ */ r(
  "textarea",
  {
    id: e,
    name: e,
    value: typeof n == "string" ? n : "",
    onChange: (l) => c(l.target.value),
    placeholder: a["ui:placeholder"],
    minLength: a.minLength,
    maxLength: a.maxLength,
    required: t,
    rows: 4,
    className: x
  }
) });
function Q(e) {
  if (e.enum && Array.isArray(e.enum) && e.enum.length > 0)
    return "datarecord-select";
  if (e.type === "string" && !e.format && e.metadata?.["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 Y(e, a, n, c, s, t, o) {
  const i = P(s, t) ?? n.default, l = Array.isArray(c.required) ? c.required.includes(a) : !1, u = n.title ?? n["ui:title"], f = n.description ?? n["ui:description"], p = {
    fieldName: a,
    fieldSchema: n,
    value: i,
    onChange: (y) => o({ [t]: y }, t),
    title: u || a,
    required: l,
    description: f
  };
  switch (e) {
    case "datarecord-string":
      return /* @__PURE__ */ r(H, { ...p }, `field-${t}`);
    case "datarecord-textarea":
      return /* @__PURE__ */ r(J, { ...p }, `field-${t}`);
    case "datarecord-select":
      return /* @__PURE__ */ r(I, { ...p }, `field-${t}`);
    case "datarecord-number":
      return /* @__PURE__ */ r(U, { ...p }, `field-${t}`);
    case "datarecord-boolean":
      return /* @__PURE__ */ r(M, { ...p }, `field-${t}`);
    case "datarecord-email":
      return /* @__PURE__ */ r(z, { ...p }, `field-${t}`);
    case "datarecord-url":
      return /* @__PURE__ */ r(G, { ...p }, `field-${t}`);
    case "datarecord-date":
      return /* @__PURE__ */ r(K, { ...p }, `field-${t}`);
    case "datarecord-datetime":
      return /* @__PURE__ */ r(X, { ...p }, `field-${t}`);
    default:
      return null;
  }
}
function Z(e, a, n) {
  const c = [];
  return Object.entries(e.properties).sort(([t, o], [i, l]) => {
    const u = o.metadata?.order, f = l.metadata?.order;
    return u !== void 0 && f !== void 0 ? u - f : u !== void 0 ? -1 : f !== void 0 ? 1 : t.localeCompare(i);
  }).forEach(([t, o]) => {
    if (o["ui:field"] === "hidden")
      return;
    if (o.metadata?.filter) {
      const u = o.metadata.filter;
      if (!u(e, a)) {
        console.warn("processDatarecordSchemaToFields: Field filter returned false for", t);
        return;
      }
    }
    const i = t, l = Q(o);
    if (l) {
      const u = Y(
        l,
        t,
        // @ts-ignore
        o,
        e,
        a,
        i,
        n
      );
      u ? c.push(u) : console.log("!!! No datarecord field component created for", t);
    } else
      console.log("!!! Unknown datarecord field type for", t, o);
  }), c;
}
const oe = R((e, a) => {
  const { brick: n } = e, c = E(n), [s, t] = $("idle"), { button: o, direction: i, ...l } = c, {
    title: u,
    buttonLabel: f,
    successMessage: p,
    errorMessage: y,
    intro: d,
    datarecordId: g,
    editable: v = !0
  } = n.props, w = n.props.button || {}, C = W(g), [L, O] = $({}), T = (F, V) => {
    const B = { ...L, ...F };
    O(B);
  }, j = (F) => {
    F.preventDefault(), !v && (t("submitting"), fetch(new URL(window.location.href), {
      method: "POST",
      body: new FormData(F.target),
      headers: {
        // biome-ignore lint/style/noNonNullAssertion: <explanation>
        "X-DataRecord-Id": g
      }
    }).then((V) => {
      V.ok ? t("success") : t("error");
    }).catch((V) => {
      t("error");
    }));
  };
  if (g && !C)
    return v ? /* @__PURE__ */ r(
      D,
      {
        brick: n,
        editable: v,
        manifest: k,
        className: "p-4 border border-red-200 bg-red-50 text-red-600 rounded",
        children: "Error loading datarecord"
      }
    ) : null;
  if (!C)
    return /* @__PURE__ */ r(
      D,
      {
        brick: n,
        editable: v,
        manifest: k,
        className: h("text-center p-4 flex items-center justify-center", Object.values(l)),
        children: g ? "Loading database..." : /* @__PURE__ */ m("span", { children: [
          "This is a form brick.",
          /* @__PURE__ */ r("br", {}),
          "To use it, please select a database",
          /* @__PURE__ */ r("br", {}),
          " you want to connect this form with."
        ] })
      }
    );
  const N = C.schema, A = Z(N, L, T);
  return /* @__PURE__ */ m(
    D,
    {
      brick: n,
      editable: v,
      manifest: k,
      as: "form",
      onSubmit: j,
      className: h("flex flex-col gap-4", Object.values(l)),
      noValidate: !0,
      children: [
        u && /* @__PURE__ */ r("h2", { className: "text-[110%] font-semibold", children: u }),
        d && /* @__PURE__ */ r("p", { children: d }),
        /* @__PURE__ */ r("div", { className: h("flex gap-4 flex-wrap @mobile:flex-col", Object.values(i)), children: A }),
        s === "error" && /* @__PURE__ */ r("div", { children: y }),
        s === "success" && /* @__PURE__ */ r("div", { children: p }),
        /* @__PURE__ */ r("div", { className: h("flex", w.position), children: /* @__PURE__ */ r(
          "button",
          {
            type: "submit",
            disabled: s === "submitting",
            className: h(
              "btn @mobile:min-w-full",
              w.color,
              w.size === "wide" ? "@desktop:w-full" : "@desktop:min-w-fit",
              Object.values(o)
            ),
            children: f || "Submit"
          }
        ) })
      ]
    }
  );
});
export {
  oe as default
};
