import { j as r } from "../../../../../_virtual/jsx-runtime.js";
import { a as y } from "../../../../sdk/dist/shared/chunk-SLRU4CT6.js";
import "@sinclair/typebox";
import "../../../../sdk/dist/shared/chunk-UU2MSQXY.js";
import "../../../../sdk/dist/shared/chunk-T3LIA4YB.js";
import "../../../../sdk/dist/shared/chunk-UMHXXXVP.js";
import { resolveSchema as w } from "../../../../sdk/dist/shared/utils/schema-resolver.js";
import { tx as b } from "../../../../style-system/dist/twind.js";
import E from "../../../../../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/get.js";
import { forwardRef as P, useState as T } from "react";
import { useDatarecord as q } from "../../editor/hooks/use-datarecord.js";
import { useBrickStyle as B } from "../hooks/use-brick-style.js";
import { DateTimeField as L, DateField as M, UrlField as N, EmailField as U, BooleanField as I, NumberField as z, SelectField as V, TextareaField as W, StringField as X } from "./form/Fields.js";
import v from "../components/BrickRoot.js";
function _(t) {
  if (t.enum && Array.isArray(t.enum) && t.enum.length > 0)
    return "datarecord-select";
  if (t.type === "string" && !t.format && t.metadata?.["ui:multiline"])
    return "datarecord-textarea";
  if (t.type === "string")
    switch (t.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 t.type === "number" ? "datarecord-number" : t.type === "boolean" ? "datarecord-boolean" : null;
}
function G(t, c, o, l, m, e, u) {
  const s = E(m, e) ?? o.default, d = Array.isArray(l.required) ? l.required.includes(c) : !1, n = o.title ?? o["ui:title"], i = o.description ?? o["ui:description"], a = {
    fieldName: c,
    fieldSchema: o,
    value: s,
    onChange: (f) => u({ [e]: f }, e),
    title: n || c,
    required: d,
    description: i
  };
  switch (t) {
    case "datarecord-string":
      return /* @__PURE__ */ r.jsx(X, { ...a }, `field-${e}`);
    case "datarecord-textarea":
      return /* @__PURE__ */ r.jsx(W, { ...a }, `field-${e}`);
    case "datarecord-select":
      return /* @__PURE__ */ r.jsx(V, { ...a }, `field-${e}`);
    case "datarecord-number":
      return /* @__PURE__ */ r.jsx(z, { ...a }, `field-${e}`);
    case "datarecord-boolean":
      return /* @__PURE__ */ r.jsx(I, { ...a }, `field-${e}`);
    case "datarecord-email":
      return /* @__PURE__ */ r.jsx(U, { ...a }, `field-${e}`);
    case "datarecord-url":
      return /* @__PURE__ */ r.jsx(N, { ...a }, `field-${e}`);
    case "datarecord-date":
      return /* @__PURE__ */ r.jsx(M, { ...a }, `field-${e}`);
    case "datarecord-datetime":
      return /* @__PURE__ */ r.jsx(L, { ...a }, `field-${e}`);
    default:
      return null;
  }
}
function H(t, c, o) {
  const l = [];
  return Object.entries(t.properties).sort(([e, u], [s, d]) => {
    const n = w(u), i = w(d), a = n.metadata?.order, f = i.metadata?.order;
    return a !== void 0 && f !== void 0 ? a - f : a !== void 0 ? -1 : f !== void 0 ? 1 : e.localeCompare(s);
  }).forEach(([e, u]) => {
    const s = w(u);
    if (s["ui:field"] === "hidden")
      return;
    if (s.metadata?.filter) {
      const i = s.metadata.filter;
      if (!i(t, c)) {
        console.warn("processDatarecordSchemaToFields: Field filter returned false for", e);
        return;
      }
    }
    const d = e, n = _(s);
    if (n) {
      const i = G(
        n,
        e,
        s,
        t,
        c,
        d,
        o
      );
      i ? l.push(i) : console.log("!!! No datarecord field component created for", e);
    } else
      console.log("!!! Unknown datarecord field type for", e, s);
  }), l;
}
const ce = P((t, c) => {
  const { brick: o } = t, l = B(o), [m, e] = T("idle"), { button: u, direction: s, ...d } = l, {
    title: n,
    buttonLabel: i,
    successMessage: a,
    errorMessage: f,
    intro: D,
    datarecordId: x,
    editable: p = !0
  } = o.props, g = o.props.button || {}, F = q(x), [S, $] = T({}), k = (j, h) => {
    const A = { ...S, ...j };
    $(A);
  }, O = (j) => {
    j.preventDefault(), !p && (e("submitting"), fetch(new URL(window.location.href), {
      method: "POST",
      body: new FormData(j.target),
      headers: {
        "X-DataRecord-Id": x
      }
    }).then((h) => {
      h.ok ? e("success") : e("error");
    }).catch((h) => {
      e("error");
    }));
  };
  if (x && !F)
    return p ? /* @__PURE__ */ r.jsx(
      v,
      {
        brick: o,
        editable: p,
        manifest: y,
        className: "p-4 border border-red-200 bg-red-50 text-red-600 rounded",
        children: "Error loading datarecord"
      }
    ) : null;
  if (!F)
    return /* @__PURE__ */ r.jsx(
      v,
      {
        brick: o,
        editable: p,
        manifest: y,
        className: b("text-center p-4 flex items-center justify-center", Object.values(d)),
        children: x ? "Loading database..." : /* @__PURE__ */ r.jsxs("span", { children: [
          "This is a form brick.",
          /* @__PURE__ */ r.jsx("br", {}),
          "To use it, please select a database",
          /* @__PURE__ */ r.jsx("br", {}),
          " you want to connect this form with."
        ] })
      }
    );
  const C = F.schema, R = H(C, S, k);
  return /* @__PURE__ */ r.jsxs(
    v,
    {
      brick: o,
      editable: p,
      manifest: y,
      as: "form",
      onSubmit: O,
      className: b("flex flex-col gap-4", Object.values(d)),
      children: [
        n && /* @__PURE__ */ r.jsx("h2", { className: "text-[110%] font-semibold", children: n }),
        D && /* @__PURE__ */ r.jsx("p", { children: D }),
        /* @__PURE__ */ r.jsx("div", { className: b("flex gap-4 flex-wrap @mobile:flex-col", Object.values(s)), children: R }),
        m === "error" && /* @__PURE__ */ r.jsx("div", { children: f }),
        m === "success" && /* @__PURE__ */ r.jsx("div", { children: a }),
        /* @__PURE__ */ r.jsx("div", { className: b("flex", g.position), children: /* @__PURE__ */ r.jsx(
          "button",
          {
            type: "submit",
            disabled: m === "submitting",
            className: b(
              "btn @mobile:min-w-full",
              g.color,
              g.size === "wide" ? "@desktop:w-full" : "@desktop:min-w-fit",
              Object.values(u)
            ),
            children: i || "Submit"
          }
        ) })
      ]
    }
  );
});
export {
  ce as default
};
//# sourceMappingURL=form.js.map
