import { j as jsxRuntimeExports } from "../../../../../_virtual/jsx-runtime.js";
import { a as M } from "../../../../sdk/dist/shared/chunk-SXHDQ64Z.js";
import "@sinclair/typebox";
import "../../../../sdk/dist/shared/chunk-3YVJ2ELD.js";
import { d as b } from "../../../../sdk/dist/shared/chunk-QGYZ7CG5.js";
import "../../../../sdk/dist/shared/chunk-AFVJZPLS.js";
import "../../../../sdk/dist/shared/chunk-A3GF4PYW.js";
import "../../../../sdk/dist/shared/chunk-W33JMRRN.js";
import { tx as D } from "../../../../style-system/dist/twind.js";
import get from "../../../../../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/get.js";
import { forwardRef, useState } from "react";
import { useDatarecord } from "../../editor/hooks/use-datarecord.js";
import { useBrickStyle } from "../hooks/use-brick-style.js";
import { DateTimeField, DateField, UrlField, EmailField, BooleanField, NumberField, SelectField, TextareaField, StringField } from "./form/Fields.js";
import BrickRoot from "../components/BrickRoot.js";
function getDatarecordFieldType(schema) {
  if (schema.enum && Array.isArray(schema.enum) && schema.enum.length > 0) {
    return "datarecord-select";
  }
  if (schema.type === "string" && !schema.format && schema.metadata?.["ui:multiline"]) {
    return "datarecord-textarea";
  }
  if (schema.type === "string") {
    switch (schema.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";
    }
  }
  if (schema.type === "number") {
    return "datarecord-number";
  }
  if (schema.type === "boolean") {
    return "datarecord-boolean";
  }
  return null;
}
function createDatarecordFieldComponent(fieldType, fieldName, fieldSchema, formSchema, formData, id, onChange) {
  const currentValue = get(formData, id) ?? fieldSchema.default;
  const required = Array.isArray(formSchema.required) ? formSchema.required.includes(fieldName) : false;
  const title = fieldSchema.title ?? fieldSchema["ui:title"];
  const description = fieldSchema.description ?? fieldSchema["ui:description"];
  const datarecordProps = {
    fieldName,
    fieldSchema,
    value: currentValue,
    onChange: (value) => onChange({ [id]: value }, id),
    title: title || fieldName,
    required,
    description
  };
  switch (fieldType) {
    case "datarecord-string":
      return /* @__PURE__ */ jsxRuntimeExports.jsx(StringField, { ...datarecordProps }, `field-${id}`);
    case "datarecord-textarea":
      return /* @__PURE__ */ jsxRuntimeExports.jsx(TextareaField, { ...datarecordProps }, `field-${id}`);
    case "datarecord-select":
      return /* @__PURE__ */ jsxRuntimeExports.jsx(SelectField, { ...datarecordProps }, `field-${id}`);
    case "datarecord-number":
      return /* @__PURE__ */ jsxRuntimeExports.jsx(NumberField, { ...datarecordProps }, `field-${id}`);
    case "datarecord-boolean":
      return /* @__PURE__ */ jsxRuntimeExports.jsx(BooleanField, { ...datarecordProps }, `field-${id}`);
    case "datarecord-email":
      return /* @__PURE__ */ jsxRuntimeExports.jsx(EmailField, { ...datarecordProps }, `field-${id}`);
    case "datarecord-url":
      return /* @__PURE__ */ jsxRuntimeExports.jsx(UrlField, { ...datarecordProps }, `field-${id}`);
    case "datarecord-date":
      return /* @__PURE__ */ jsxRuntimeExports.jsx(DateField, { ...datarecordProps }, `field-${id}`);
    case "datarecord-datetime":
      return /* @__PURE__ */ jsxRuntimeExports.jsx(DateTimeField, { ...datarecordProps }, `field-${id}`);
    default:
      return null;
  }
}
function processDatarecordSchemaToFields(schema, formData, onChange) {
  const fields = [];
  const sortedFields = Object.entries(schema.properties).sort(([aName, aSchema], [bName, bSchema]) => {
    const aField = b(aSchema);
    const bField = b(bSchema);
    const aOrder = aField.metadata?.order;
    const bOrder = bField.metadata?.order;
    if (aOrder !== void 0 && bOrder !== void 0) {
      return aOrder - bOrder;
    }
    if (aOrder !== void 0) return -1;
    if (bOrder !== void 0) return 1;
    return aName.localeCompare(bName);
  });
  sortedFields.forEach(([fieldName, fieldSchema]) => {
    const field = b(fieldSchema);
    if (field["ui:field"] === "hidden") {
      return;
    }
    if (field.metadata?.filter) {
      const filter = field.metadata.filter;
      if (!filter(schema, formData)) {
        console.warn("processDatarecordSchemaToFields: Field filter returned false for", fieldName);
        return;
      }
    }
    const id = fieldName;
    const datarecordFieldType = getDatarecordFieldType(field);
    if (datarecordFieldType) {
      const fieldComponent = createDatarecordFieldComponent(
        datarecordFieldType,
        fieldName,
        field,
        schema,
        formData,
        id,
        onChange
      );
      if (fieldComponent) {
        fields.push(fieldComponent);
      } else {
        console.log("!!! No datarecord field component created for", fieldName);
      }
    } else {
      console.log("!!! Unknown datarecord field type for", fieldName, field);
    }
  });
  return fields;
}
const WidgetForm = forwardRef((props, ref) => {
  const { brick } = props;
  const styles = useBrickStyle(brick);
  const [submitState, setSubmitState] = useState("idle");
  const { button, direction, ...rest } = styles;
  const {
    title,
    buttonLabel,
    successMessage,
    errorMessage,
    intro,
    datarecordId,
    editable = true
  } = brick.props;
  const buttonProps = brick.props.button || {};
  const datarecord = useDatarecord(datarecordId);
  const [formData, setFormData] = useState({});
  const handleFieldChange = (data, fieldPath) => {
    const newData = { ...formData, ...data };
    setFormData(newData);
  };
  const handleSubmit = (e) => {
    e.preventDefault();
    if (editable) {
      return;
    }
    setSubmitState("submitting");
    fetch(new URL(window.location.href), {
      method: "POST",
      body: new FormData(e.target),
      headers: {
        "X-DataRecord-Id": datarecordId
      }
    }).then((response) => {
      if (response.ok) {
        setSubmitState("success");
      } else {
        setSubmitState("error");
      }
    }).catch((error) => {
      setSubmitState("error");
    });
  };
  if (datarecordId && !datarecord) {
    return editable ? /* @__PURE__ */ jsxRuntimeExports.jsx(
      BrickRoot,
      {
        brick,
        editable,
        manifest: M,
        className: "p-4 border border-red-200 bg-red-50 text-red-600 rounded",
        children: "Error loading datarecord"
      }
    ) : null;
  }
  if (!datarecord) {
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      BrickRoot,
      {
        brick,
        editable,
        manifest: M,
        className: D("text-center p-4 flex items-center justify-center", Object.values(rest)),
        children: datarecordId ? "Loading database..." : /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { children: [
          "This is a form brick.",
          /* @__PURE__ */ jsxRuntimeExports.jsx("br", {}),
          "To use it, please select a database",
          /* @__PURE__ */ jsxRuntimeExports.jsx("br", {}),
          " you want to connect this form with."
        ] })
      }
    );
  }
  const typeboxSchema = datarecord.schema;
  const fields = processDatarecordSchemaToFields(typeboxSchema, formData, handleFieldChange);
  return /* @__PURE__ */ jsxRuntimeExports.jsxs(
    BrickRoot,
    {
      brick,
      editable,
      manifest: M,
      as: "form",
      onSubmit: handleSubmit,
      className: D("flex flex-col gap-4", Object.values(rest)),
      noValidate: true,
      children: [
        title && /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { className: "text-[110%] font-semibold", children: title }),
        intro && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { children: intro }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: D("flex gap-4 flex-wrap @mobile:flex-col", Object.values(direction)), children: fields }),
        submitState === "error" && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: errorMessage }),
        submitState === "success" && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: successMessage }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: D("flex", buttonProps.position), children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          "button",
          {
            type: "submit",
            disabled: submitState === "submitting",
            className: D(
              "btn @mobile:min-w-full",
              buttonProps.color,
              buttonProps.size === "wide" ? "@desktop:w-full" : "@desktop:min-w-fit",
              Object.values(button)
            ),
            children: buttonLabel || "Submit"
          }
        ) })
      ]
    }
  );
});
export {
  WidgetForm as default
};
//# sourceMappingURL=form.js.map
