import { jsxs, jsx } from 'react/jsx-runtime';
import { FormItem, FormControl, FormMessage } from '../../form.mjs';
import { Select, SelectTrigger, SelectValue, SelectContent, SelectItem } from '../../select.mjs';
import AutoFormLabel from '../common/label.mjs';
import AutoFormTooltip from '../common/tooltip.mjs';
import { getBaseSchema } from '../helpers.mjs';

function getEnumValues(schema) {
  if (Array.isArray(schema.options)) {
    return schema.options;
  }
  if (schema.enum) {
    return Object.values(schema.enum);
  }
  const def = schema._zod?.def;
  if (def?.entries) {
    return Object.values(def.entries);
  }
  return [];
}
function AutoFormEnum({
  label,
  isRequired,
  field,
  fieldConfigItem,
  zodItem,
  fieldProps
}) {
  const baseSchema = getBaseSchema(zodItem);
  const baseValues = getEnumValues(baseSchema);
  let values = [];
  if (!baseValues || baseValues.length === 0) {
    values = [];
  } else {
    values = baseValues.map((value) => [value, value]);
  }
  function findItem(value) {
    return values.find((item) => item[0] === value);
  }
  const handleValueChange = (val) => {
    if (val === "" && field.value && field.value !== "") {
      return;
    }
    field.onChange(val);
  };
  return /* @__PURE__ */ jsxs(FormItem, { children: [
    /* @__PURE__ */ jsx(
      AutoFormLabel,
      {
        label: fieldConfigItem?.label || label,
        isRequired
      }
    ),
    /* @__PURE__ */ jsx(FormControl, { children: /* @__PURE__ */ jsxs(
      Select,
      {
        onValueChange: handleValueChange,
        value: field.value ?? "",
        ...fieldProps,
        children: [
          /* @__PURE__ */ jsx(SelectTrigger, { className: fieldProps.className, children: /* @__PURE__ */ jsx(SelectValue, { placeholder: fieldConfigItem.inputProps?.placeholder, children: field.value ? findItem(field.value)?.[1] : "Select an option" }) }),
          /* @__PURE__ */ jsx(SelectContent, { children: values.map(([value, label2]) => /* @__PURE__ */ jsx(SelectItem, { value: label2, children: label2 }, value)) })
        ]
      }
    ) }),
    /* @__PURE__ */ jsx(AutoFormTooltip, { fieldConfigItem }),
    /* @__PURE__ */ jsx(FormMessage, {})
  ] });
}

export { AutoFormEnum as default };
