import { jsx, jsxs } from "react/jsx-runtime";
import { aN as manifest, a8 as resolveSchema } from "./use-page-data.CMUQyNAA.js";
import "@sinclair/typebox";
import { a as tx } from "./twind.DdSZmZu6.js";
import { g as get } from "./get.DbXiVauf.js";
import { forwardRef, useState } from "react";
import { a as useDatarecord } from "./use-datarecord.B4fi8Za7.js";
import { b as useBrickStyle } from "./use-section-style.DjjgfIQS.js";
import { B as BrickRoot } from "./BrickRoot.D_a_fRJm.js";
const inputClassname = tx(
  `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`
);
const GenericFieldComponent = ({
  fieldName,
  title,
  required,
  description,
  children
}) => {
  return /* @__PURE__ */ jsxs("div", { className: "flex-1 flex flex-col gap-1", children: [
    /* @__PURE__ */ jsxs("label", { htmlFor: fieldName, className: "font-medium", children: [
      title,
      " ",
      required && /* @__PURE__ */ jsx("span", { children: "*" })
    ] }),
    children
  ] });
};
const BooleanField = ({
  fieldName,
  fieldSchema,
  value,
  onChange,
  title,
  required,
  description
}) => {
  const booleanValue = typeof value === "boolean" ? value : false;
  return /* @__PURE__ */ jsx(GenericFieldComponent, { fieldName, title, required, description, children: /* @__PURE__ */ jsxs("div", { className: "flex items-center space-x-3", children: [
    /* @__PURE__ */ jsx(
      "input",
      {
        id: fieldName,
        name: fieldName,
        type: "checkbox",
        defaultChecked: booleanValue,
        onChange: (e) => onChange(e.target.checked),
        required,
        className: tx(
          "rounded border border-base-200 focus:outline-none focus:(ring-2 ring-accent-500 border-accent-500) text-accent-500"
        )
      }
    ),
    /* @__PURE__ */ jsxs("label", { htmlFor: fieldName, className: "font-medium", children: [
      title,
      " ",
      required && /* @__PURE__ */ jsx("span", { children: "*" })
    ] })
  ] }) });
};
const NumberField = ({
  fieldName,
  fieldSchema,
  value,
  onChange,
  title,
  required,
  description
}) => {
  const numberValue = typeof value === "number" ? value : "";
  return /* @__PURE__ */ jsx(GenericFieldComponent, { fieldName, title, required, description, children: /* @__PURE__ */ jsx(
    "input",
    {
      id: fieldName,
      name: fieldName,
      type: "number",
      value: numberValue,
      onChange: (e) => {
        const val = e.target.value;
        onChange(val === "" ? 0 : Number(val));
      },
      placeholder: fieldSchema["ui:placeholder"],
      min: fieldSchema.minimum,
      max: fieldSchema.maximum,
      required,
      className: inputClassname
    }
  ) });
};
const SelectField = ({
  fieldName,
  fieldSchema,
  value,
  onChange,
  title,
  required,
  description
}) => {
  const options = fieldSchema.enum || [];
  const stringValue = typeof value === "string" ? value : "";
  const widget = fieldSchema.metadata?.["ui:widget"];
  const longestOption = options.reduce(
    (longest, current) => current.length > longest.length ? current : longest,
    fieldSchema["ui:placeholder"] || "Choose an option"
  );
  const estimatedWidth = Math.max(longestOption.length * 0.6 + 5, 10);
  const effectiveWidget = options.length === 1 ? "checkbox" : widget;
  if (effectiveWidget === "checkbox") {
    return /* @__PURE__ */ jsx("div", { className: "flex-1 flex flex-col gap-1", children: /* @__PURE__ */ jsxs("fieldset", { children: [
      /* @__PURE__ */ jsxs("legend", { className: "block text-sm font-medium ", children: [
        title,
        " ",
        required && /* @__PURE__ */ jsx("span", { className: "text-red-500", children: "*" })
      ] }),
      /* @__PURE__ */ jsx("div", { className: "space-y-2 mt-2", children: options.map((option) => /* @__PURE__ */ jsxs("label", { className: "flex items-center space-x-2", children: [
        /* @__PURE__ */ jsx(
          "input",
          {
            type: "checkbox",
            name: fieldName,
            value: option,
            onChange: (e) => onChange(e.target.checked ? e.target.value : ""),
            required,
            className: tx(
              "rounded border border-base-200 focus:outline-none focus:(ring-2 ring-accent-500 border-accent-500) text-accent-500"
            )
          }
        ),
        /* @__PURE__ */ jsx("span", { className: "text-sm", children: option })
      ] }, option)) })
    ] }) });
  }
  if (effectiveWidget === "radio") {
    return /* @__PURE__ */ jsx("div", { className: "flex-1 flex flex-col gap-1", children: /* @__PURE__ */ jsxs("fieldset", { children: [
      /* @__PURE__ */ jsxs("legend", { className: "font-medium", children: [
        title,
        " ",
        required && /* @__PURE__ */ jsx("span", { children: "*" })
      ] }),
      /* @__PURE__ */ jsx("div", { className: "space-y-2 mt-2", children: options.map((option) => /* @__PURE__ */ jsxs("label", { className: "flex items-center space-x-2", children: [
        /* @__PURE__ */ jsx(
          "input",
          {
            type: "radio",
            name: fieldName,
            value: option,
            checked: stringValue === option,
            onChange: (e) => onChange(e.target.value),
            required,
            className: "border border-base-200 focus:outline-none focus:(ring-2 ring-accent-500 border-accent-500) text-accent-500"
          }
        ),
        /* @__PURE__ */ jsx("span", { children: option })
      ] }, option)) })
    ] }) });
  }
  return /* @__PURE__ */ jsx(GenericFieldComponent, { fieldName, title, required, description, children: /* @__PURE__ */ jsxs(
    "select",
    {
      id: fieldName,
      name: fieldName,
      value: stringValue,
      onChange: (e) => onChange(e.target.value),
      required,
      className: tx(inputClassname, "w-full"),
      style: { minWidth: `${estimatedWidth}rem` },
      children: [
        /* @__PURE__ */ jsx("option", { value: "", disabled: true, children: fieldSchema["ui:placeholder"] || fieldSchema.description || "Choose an option" }),
        options.map((option) => /* @__PURE__ */ jsx("option", { value: option, children: option }, option))
      ]
    }
  ) });
};
const EmailField = ({
  fieldName,
  fieldSchema,
  value,
  onChange,
  title,
  required,
  description
}) => {
  const stringValue = typeof value === "string" ? value : "";
  return /* @__PURE__ */ jsx(GenericFieldComponent, { fieldName, title, required, description, children: /* @__PURE__ */ jsx(
    "input",
    {
      id: fieldName,
      name: fieldName,
      type: "email",
      value: stringValue,
      onChange: (e) => onChange(e.target.value),
      placeholder: fieldSchema["ui:placeholder"],
      required,
      className: inputClassname
    }
  ) });
};
const UrlField = ({
  fieldName,
  fieldSchema,
  value,
  onChange,
  title,
  required,
  description
}) => {
  const stringValue = typeof value === "string" ? value : "";
  return /* @__PURE__ */ jsx(GenericFieldComponent, { fieldName, title, required, description, children: /* @__PURE__ */ jsx(
    "input",
    {
      id: fieldName,
      name: fieldName,
      type: "url",
      value: stringValue,
      onChange: (e) => onChange(e.target.value),
      placeholder: fieldSchema["ui:placeholder"],
      required,
      className: inputClassname
    }
  ) });
};
const DateField = ({
  fieldName,
  fieldSchema,
  value,
  onChange,
  title,
  required,
  description
}) => {
  const stringValue = typeof value === "string" ? value : "";
  return /* @__PURE__ */ jsx(GenericFieldComponent, { fieldName, title, required, description, children: /* @__PURE__ */ jsx(
    "input",
    {
      id: fieldName,
      name: fieldName,
      type: "date",
      value: stringValue,
      onChange: (e) => onChange(e.target.value),
      required,
      className: inputClassname
    }
  ) });
};
const DateTimeField = ({
  fieldName,
  fieldSchema,
  value,
  onChange,
  title,
  required,
  description
}) => {
  const stringValue = typeof value === "string" ? value : "";
  return /* @__PURE__ */ jsx(GenericFieldComponent, { fieldName, title, required, description, children: /* @__PURE__ */ jsx(
    "input",
    {
      id: fieldName,
      name: fieldName,
      type: "datetime-local",
      value: stringValue,
      onChange: (e) => onChange(e.target.value),
      required,
      className: inputClassname
    }
  ) });
};
const StringField = ({
  fieldName,
  fieldSchema,
  value,
  onChange,
  title,
  required,
  description
}) => {
  const stringValue = typeof value === "string" ? value : "";
  return /* @__PURE__ */ jsx(GenericFieldComponent, { fieldName, title, required, description, children: /* @__PURE__ */ jsx(
    "input",
    {
      id: fieldName,
      name: fieldName,
      type: "text",
      value: stringValue,
      onChange: (e) => onChange(e.target.value),
      placeholder: fieldSchema["ui:placeholder"],
      minLength: fieldSchema.minLength,
      maxLength: fieldSchema.maxLength,
      required,
      className: tx(inputClassname)
    }
  ) });
};
const TextareaField = ({
  fieldName,
  fieldSchema,
  value,
  onChange,
  title,
  required,
  description
}) => {
  const stringValue = typeof value === "string" ? value : "";
  return /* @__PURE__ */ jsx(GenericFieldComponent, { fieldName, title, required, description, children: /* @__PURE__ */ jsx(
    "textarea",
    {
      id: fieldName,
      name: fieldName,
      value: stringValue,
      onChange: (e) => onChange(e.target.value),
      placeholder: fieldSchema["ui:placeholder"],
      minLength: fieldSchema.minLength,
      maxLength: fieldSchema.maxLength,
      required,
      rows: 4,
      className: inputClassname
    }
  ) });
};
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__ */ jsx(StringField, { ...datarecordProps }, `field-${id}`);
    case "datarecord-textarea":
      return /* @__PURE__ */ jsx(TextareaField, { ...datarecordProps }, `field-${id}`);
    case "datarecord-select":
      return /* @__PURE__ */ jsx(SelectField, { ...datarecordProps }, `field-${id}`);
    case "datarecord-number":
      return /* @__PURE__ */ jsx(NumberField, { ...datarecordProps }, `field-${id}`);
    case "datarecord-boolean":
      return /* @__PURE__ */ jsx(BooleanField, { ...datarecordProps }, `field-${id}`);
    case "datarecord-email":
      return /* @__PURE__ */ jsx(EmailField, { ...datarecordProps }, `field-${id}`);
    case "datarecord-url":
      return /* @__PURE__ */ jsx(UrlField, { ...datarecordProps }, `field-${id}`);
    case "datarecord-date":
      return /* @__PURE__ */ jsx(DateField, { ...datarecordProps }, `field-${id}`);
    case "datarecord-datetime":
      return /* @__PURE__ */ 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 = resolveSchema(aSchema);
    const bField = resolveSchema(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 = resolveSchema(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__ */ jsx(
      BrickRoot,
      {
        brick,
        editable,
        manifest,
        className: "p-4 border border-red-200 bg-red-50 text-red-600 rounded",
        children: "Error loading datarecord"
      }
    ) : null;
  }
  if (!datarecord) {
    return /* @__PURE__ */ jsx(
      BrickRoot,
      {
        brick,
        editable,
        manifest,
        className: tx("text-center p-4 flex items-center justify-center", Object.values(rest)),
        children: datarecordId ? "Loading database..." : /* @__PURE__ */ jsxs("span", { children: [
          "This is a form brick.",
          /* @__PURE__ */ jsx("br", {}),
          "To use it, please select a database",
          /* @__PURE__ */ jsx("br", {}),
          " you want to connect this form with."
        ] })
      }
    );
  }
  const typeboxSchema = datarecord.schema;
  const fields = processDatarecordSchemaToFields(typeboxSchema, formData, handleFieldChange);
  return /* @__PURE__ */ jsxs(
    BrickRoot,
    {
      brick,
      editable,
      manifest,
      as: "form",
      onSubmit: handleSubmit,
      className: tx("flex flex-col gap-4", Object.values(rest)),
      noValidate: true,
      children: [
        title && /* @__PURE__ */ jsx("h2", { className: "text-[110%] font-semibold", children: title }),
        intro && /* @__PURE__ */ jsx("p", { children: intro }),
        /* @__PURE__ */ jsx("div", { className: tx("flex gap-4 flex-wrap @mobile:flex-col", Object.values(direction)), children: fields }),
        submitState === "error" && /* @__PURE__ */ jsx("div", { children: errorMessage }),
        submitState === "success" && /* @__PURE__ */ jsx("div", { children: successMessage }),
        /* @__PURE__ */ jsx("div", { className: tx("flex", buttonProps.position), children: /* @__PURE__ */ jsx(
          "button",
          {
            type: "submit",
            disabled: submitState === "submitting",
            className: tx(
              "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.CTeBH2pJ.js.map
