import { jsxs, jsx } from 'react/jsx-runtime';
import { AccordionItem, AccordionTrigger, AccordionContent } from '../../accordion.mjs';
import { Button } from '../../button.mjs';
import { Separator } from '../../separator.mjs';
import { Trash, Plus } from 'lucide-react';
import { useFieldArray } from 'react-hook-form';
import { beautifyObjectName } from '../helpers.mjs';
import AutoFormObject from './object.mjs';

function getDefType(schema) {
  return schema._zod?.def?.type || "";
}
function getArrayElementType(item) {
  const def = item._zod?.def;
  const defType = getDefType(item);
  if (defType === "array") {
    return def?.element || null;
  }
  if (["default", "optional", "nullable"].includes(defType)) {
    const innerType = def?.innerType;
    if (innerType) {
      return getArrayElementType(innerType);
    }
  }
  return null;
}
function AutoFormArray({
  name,
  item,
  form,
  path = [],
  fieldConfig
}) {
  const fieldPath = path.join(".");
  const { fields, append, remove } = useFieldArray({
    control: form.control,
    name: fieldPath
  });
  const title = fieldConfig?.label ?? beautifyObjectName(name);
  const itemDefType = getArrayElementType(item);
  return /* @__PURE__ */ jsxs(AccordionItem, { value: name, className: "border-none", children: [
    /* @__PURE__ */ jsx(AccordionTrigger, { children: title }),
    /* @__PURE__ */ jsxs(AccordionContent, { children: [
      fields.map((_field, index) => {
        const key = _field.id;
        return /* @__PURE__ */ jsxs("div", { className: "mt-4 flex flex-col", children: [
          /* @__PURE__ */ jsx(
            AutoFormObject,
            {
              schema: itemDefType,
              form,
              fieldConfig,
              path: [...path, index.toString()]
            }
          ),
          /* @__PURE__ */ jsx("div", { className: "my-4 flex justify-end", children: /* @__PURE__ */ jsx(
            Button,
            {
              variant: "secondary",
              size: "icon",
              type: "button",
              className: "hover:bg-zinc-300 hover:text-black focus:ring-0 focus:ring-offset-0 focus-visible:ring-0 focus-visible:ring-offset-0 dark:bg-white dark:text-black dark:hover:bg-zinc-300 dark:hover:text-black dark:hover:ring-0 dark:hover:ring-offset-0 dark:focus-visible:ring-0 dark:focus-visible:ring-offset-0",
              onClick: () => remove(index),
              children: /* @__PURE__ */ jsx(Trash, { className: "size-4 " })
            }
          ) }),
          /* @__PURE__ */ jsx(Separator, {})
        ] }, `${key}`);
      }),
      /* @__PURE__ */ jsxs(
        Button,
        {
          type: "button",
          variant: "secondary",
          onClick: () => append({}),
          className: "mt-4 flex items-center",
          children: [
            /* @__PURE__ */ jsx(Plus, { className: "mr-2", size: 16 }),
            "Add"
          ]
        }
      )
    ] })
  ] });
}

export { AutoFormArray as default };
