"use client";
import { jsx, jsxs } from 'react/jsx-runtime';
import { useMemo, useState, useCallback } from 'react';
import AutoForm from '../auto-form/index.mjs';
import { buildFieldConfigFromJsonSchema } from '../auto-form/helpers.mjs';
import { Input } from '../input.mjs';
import { Label } from '../label.mjs';
import { Button } from '../button.mjs';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '../dialog.mjs';
import { Select, SelectTrigger, SelectValue, SelectContent, SelectItem } from '../select.mjs';

function EditFieldDialog({
  open,
  onOpenChange,
  field,
  component,
  onUpdate,
  steps = [],
  allFieldIds = []
}) {
  const initialValues = 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] = useState(null);
  const [localPropsOverride, setLocalPropsOverride] = useState(null);
  const [stepGroupOverride, setStepGroupOverride] = useState(null);
  const fieldName = fieldNameOverride ?? initialValues.fieldName;
  const localProps = localPropsOverride ?? initialValues.props;
  const localStepGroup = stepGroupOverride ?? field?.stepGroup ?? 0;
  const isDuplicateId = useMemo(() => {
    if (!field || fieldName === field.id) return false;
    return allFieldIds.some((id) => id === fieldName && id !== field.id);
  }, [fieldName, field, allFieldIds]);
  const [prevInitial, setPrevInitial] = useState(initialValues);
  if (prevInitial !== initialValues) {
    setPrevInitial(initialValues);
    setFieldNameOverride(null);
    setLocalPropsOverride(null);
    setStepGroupOverride(null);
  }
  const formKey = initialValues.key;
  const handleValuesChange = useCallback(
    (values) => {
      setLocalPropsOverride(values);
    },
    []
  );
  const handleSave = 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 = buildFieldConfigFromJsonSchema(jsonSchema);
  return /* @__PURE__ */ jsx(Dialog, { open, onOpenChange, children: /* @__PURE__ */ jsxs(DialogContent, { className: "max-w-md max-h-[90vh] overflow-y-auto", children: [
    /* @__PURE__ */ jsxs(DialogHeader, { children: [
      /* @__PURE__ */ jsxs(DialogTitle, { className: "flex items-center gap-2", children: [
        Icon && /* @__PURE__ */ jsx(Icon, { className: "h-5 w-5 text-muted-foreground" }),
        "Edit ",
        component.label
      ] }),
      /* @__PURE__ */ jsx(DialogDescription, { children: "Configure the properties for this field" })
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "space-y-4 py-4", children: [
      /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
        /* @__PURE__ */ jsx(Label, { htmlFor: "field-name", children: "Field Name" }),
        /* @__PURE__ */ jsx(
          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__ */ jsx("p", { className: "text-xs text-destructive", children: "A field with this name already exists. Please choose a different name." }) : /* @__PURE__ */ 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__ */ jsxs("div", { className: "space-y-2", children: [
        /* @__PURE__ */ jsx(Label, { htmlFor: "field-step", children: "Step" }),
        /* @__PURE__ */ jsxs(
          Select,
          {
            value: String(localStepGroup),
            onValueChange: (value) => setStepGroupOverride(parseInt(value, 10)),
            children: [
              /* @__PURE__ */ jsx(SelectTrigger, { id: "field-step", children: /* @__PURE__ */ jsx(SelectValue, { placeholder: "Select step" }) }),
              /* @__PURE__ */ jsx(SelectContent, { children: steps.map((step, index) => /* @__PURE__ */ jsx(SelectItem, { value: String(index), children: step.title }, step.id)) })
            ]
          }
        ),
        /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: "Which step this field belongs to" })
      ] }),
      /* @__PURE__ */ jsx("div", { className: "border-t pt-4", children: /* @__PURE__ */ jsx(
        AutoForm,
        {
          formSchema: component.propertiesSchema,
          values: localProps,
          onValuesChange: handleValuesChange,
          fieldConfig,
          className: "space-y-4"
        },
        formKey
      ) })
    ] }),
    /* @__PURE__ */ jsxs(DialogFooter, { children: [
      /* @__PURE__ */ jsx(Button, { variant: "outline", onClick: () => onOpenChange(false), children: "Cancel" }),
      /* @__PURE__ */ jsx(Button, { onClick: handleSave, disabled: isDuplicateId, children: "Save Changes" })
    ] })
  ] }) });
}

export { EditFieldDialog };
