"use client";
'use strict';

const jsxRuntime = require('react/jsx-runtime');
const React = require('react');
const index = require('../auto-form/index.cjs');
const helpers = require('../auto-form/helpers.cjs');
const input = require('../input.cjs');
const label = require('../label.cjs');
const button = require('../button.cjs');
const dialog = require('../dialog.cjs');
const select = require('../select.cjs');

function EditFieldDialog({
  open,
  onOpenChange,
  field,
  component,
  onUpdate,
  steps = [],
  allFieldIds = []
}) {
  const initialValues = React.useMemo(() => {
    if (!field) return { fieldName: "", props: {}, key: "" };
    const values = { ...field.props };
    if (Array.isArray(values.options)) {
      values.options = values.options.join("\n");
    }
    return { fieldName: field.id, props: values, key: `${field.id}-${open}` };
  }, [field, open]);
  const [fieldNameOverride, setFieldNameOverride] = React.useState(null);
  const [localPropsOverride, setLocalPropsOverride] = React.useState(null);
  const [stepGroupOverride, setStepGroupOverride] = React.useState(null);
  const fieldName = fieldNameOverride ?? initialValues.fieldName;
  const localProps = localPropsOverride ?? initialValues.props;
  const localStepGroup = stepGroupOverride ?? field?.stepGroup ?? 0;
  const isDuplicateId = React.useMemo(() => {
    if (!field || fieldName === field.id) return false;
    return allFieldIds.some((id) => id === fieldName && id !== field.id);
  }, [fieldName, field, allFieldIds]);
  const [prevInitial, setPrevInitial] = React.useState(initialValues);
  if (prevInitial !== initialValues) {
    setPrevInitial(initialValues);
    setFieldNameOverride(null);
    setLocalPropsOverride(null);
    setStepGroupOverride(null);
  }
  const formKey = initialValues.key;
  const handleValuesChange = React.useCallback(
    (values) => {
      setLocalPropsOverride(values);
    },
    []
  );
  const handleSave = React.useCallback(() => {
    if (!field) return;
    const props = { ...localProps };
    if (typeof props.options === "string") {
      props.options = props.options.split("\n").map((s) => s.trim()).filter(Boolean);
    }
    const newId = fieldName !== field.id ? fieldName : void 0;
    const stepGroup = stepGroupOverride !== null && stepGroupOverride !== field.stepGroup ? stepGroupOverride : void 0;
    onUpdate(field.id, props, newId, stepGroup);
    onOpenChange(false);
  }, [field, localProps, fieldName, onUpdate, onOpenChange, stepGroupOverride]);
  if (!field || !component) {
    return null;
  }
  const Icon = component.icon;
  const jsonSchema = component.propertiesSchema.toJSONSchema();
  const fieldConfig = helpers.buildFieldConfigFromJsonSchema(jsonSchema);
  return /* @__PURE__ */ jsxRuntime.jsx(dialog.Dialog, { open, onOpenChange, children: /* @__PURE__ */ jsxRuntime.jsxs(dialog.DialogContent, { className: "max-w-md max-h-[90vh] overflow-y-auto", children: [
    /* @__PURE__ */ jsxRuntime.jsxs(dialog.DialogHeader, { children: [
      /* @__PURE__ */ jsxRuntime.jsxs(dialog.DialogTitle, { className: "flex items-center gap-2", children: [
        Icon && /* @__PURE__ */ jsxRuntime.jsx(Icon, { className: "h-5 w-5 text-muted-foreground" }),
        "Edit ",
        component.label
      ] }),
      /* @__PURE__ */ jsxRuntime.jsx(dialog.DialogDescription, { children: "Configure the properties for this field" })
    ] }),
    /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-4 py-4", children: [
      /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-2", children: [
        /* @__PURE__ */ jsxRuntime.jsx(label.Label, { htmlFor: "field-name", children: "Field Name" }),
        /* @__PURE__ */ jsxRuntime.jsx(
          input.Input,
          {
            id: "field-name",
            value: fieldName,
            onChange: (e) => setFieldNameOverride(e.target.value),
            placeholder: "Enter field name",
            className: isDuplicateId ? "border-destructive focus-visible:ring-destructive" : "",
            "aria-invalid": isDuplicateId
          }
        ),
        isDuplicateId ? /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-xs text-destructive", children: "A field with this name already exists. Please choose a different name." }) : /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-xs text-muted-foreground", children: "This is the key used in the form data and JSON schema" })
      ] }),
      steps.length > 1 && field && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-2", children: [
        /* @__PURE__ */ jsxRuntime.jsx(label.Label, { htmlFor: "field-step", children: "Step" }),
        /* @__PURE__ */ jsxRuntime.jsxs(
          select.Select,
          {
            value: String(localStepGroup),
            onValueChange: (value) => setStepGroupOverride(parseInt(value, 10)),
            children: [
              /* @__PURE__ */ jsxRuntime.jsx(select.SelectTrigger, { id: "field-step", children: /* @__PURE__ */ jsxRuntime.jsx(select.SelectValue, { placeholder: "Select step" }) }),
              /* @__PURE__ */ jsxRuntime.jsx(select.SelectContent, { children: steps.map((step, index) => /* @__PURE__ */ jsxRuntime.jsx(select.SelectItem, { value: String(index), children: step.title }, step.id)) })
            ]
          }
        ),
        /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-xs text-muted-foreground", children: "Which step this field belongs to" })
      ] }),
      /* @__PURE__ */ jsxRuntime.jsx("div", { className: "border-t pt-4", children: /* @__PURE__ */ jsxRuntime.jsx(
        index.default,
        {
          formSchema: component.propertiesSchema,
          values: localProps,
          onValuesChange: handleValuesChange,
          fieldConfig,
          className: "space-y-4"
        },
        formKey
      ) })
    ] }),
    /* @__PURE__ */ jsxRuntime.jsxs(dialog.DialogFooter, { children: [
      /* @__PURE__ */ jsxRuntime.jsx(button.Button, { variant: "outline", onClick: () => onOpenChange(false), children: "Cancel" }),
      /* @__PURE__ */ jsxRuntime.jsx(button.Button, { onClick: handleSave, disabled: isDuplicateId, children: "Save Changes" })
    ] })
  ] }) });
}

exports.EditFieldDialog = EditFieldDialog;
