import {
  CategoryTree
} from "./chunk-XLA2CNCW.js";
import {
  insertCategoryTreeItem
} from "./chunk-Y456KVIN.js";
import {
  transformNullableFormData
} from "./chunk-7RPRNVBS.js";
import {
  HandleInput
} from "./chunk-HJ56YXBU.js";
import {
  TabbedForm,
  defineTabMeta,
  useTabbedForm
} from "./chunk-4LXBQTFN.js";
import {
  useDocumentDirection
} from "./chunk-Y7QKP6QU.js";
import {
  RouteFocusModal,
  useRouteModal
} from "./chunk-FWJLS7XD.js";
import {
  Form
} from "./chunk-3QSRE5LS.js";
import {
  useCreateProductCategory,
  useProductCategories
} from "./chunk-Z2QQZOG3.js";

// src/pages/categories/category-create/components/create-category-form/schema.ts
import { z } from "zod";
var CreateCategoryDetailsSchema = z.object({
  name: z.string().min(1),
  description: z.string().optional(),
  handle: z.string().optional(),
  status: z.enum(["active", "inactive"]),
  visibility: z.enum(["public", "internal"])
});
var CreateCategorySchema = z.object({
  rank: z.number().nullable(),
  parent_category_id: z.string().nullable()
}).merge(CreateCategoryDetailsSchema);

// src/pages/categories/category-create/category-create.tsx
import { Children as Children2 } from "react";
import { useSearchParams } from "react-router-dom";

// src/pages/categories/category-create/components/create-category-form/create-category-form.tsx
import { zodResolver } from "@hookform/resolvers/zod";
import { toast } from "@medusajs/ui";
import { Children, useMemo as useMemo2 } from "react";
import { useForm } from "react-hook-form";
import { useTranslation as useTranslation3 } from "react-i18next";

// src/pages/categories/category-create/components/create-category-form/create-category-details.tsx
import { Heading, Input, Select, Text, Textarea } from "@medusajs/ui";
import { useTranslation } from "react-i18next";
import { jsx, jsxs } from "react/jsx-runtime";
var Root = () => {
  const { t } = useTranslation();
  const form = useTabbedForm();
  const direction = useDocumentDirection();
  return /* @__PURE__ */ jsx("div", { className: "flex flex-col items-center p-16", children: /* @__PURE__ */ jsxs("div", { className: "flex w-full max-w-[720px] flex-col gap-y-8", "data-testid": "category-create-form-content", children: [
    /* @__PURE__ */ jsxs("div", { "data-testid": "category-create-form-header", children: [
      /* @__PURE__ */ jsx(Heading, { "data-testid": "category-create-form-heading", children: t("categories.create.header") }),
      /* @__PURE__ */ jsx(Text, { size: "small", className: "text-ui-fg-subtle", "data-testid": "category-create-form-hint", children: t("categories.create.hint") })
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-1 gap-4 md:grid-cols-2", children: [
      /* @__PURE__ */ jsx(
        Form.Field,
        {
          control: form.control,
          name: "name",
          render: ({ field }) => {
            return /* @__PURE__ */ jsxs(Form.Item, { "data-testid": "category-create-form-name-item", children: [
              /* @__PURE__ */ jsx(Form.Label, { "data-testid": "category-create-form-name-label", children: t("fields.title") }),
              /* @__PURE__ */ jsx(Form.Control, { "data-testid": "category-create-form-name-control", children: /* @__PURE__ */ jsx(Input, { autoComplete: "off", ...field, "data-testid": "category-create-form-name-input" }) }),
              /* @__PURE__ */ jsx(Form.ErrorMessage, { "data-testid": "category-create-form-name-error" })
            ] });
          }
        }
      ),
      /* @__PURE__ */ jsx(
        Form.Field,
        {
          control: form.control,
          name: "handle",
          render: ({ field }) => {
            return /* @__PURE__ */ jsxs(Form.Item, { "data-testid": "category-create-form-handle-item", children: [
              /* @__PURE__ */ jsx(Form.Label, { optional: true, tooltip: t("collections.handleTooltip"), "data-testid": "category-create-form-handle-label", children: t("fields.handle") }),
              /* @__PURE__ */ jsx(Form.Control, { "data-testid": "category-create-form-handle-control", children: /* @__PURE__ */ jsx(HandleInput, { ...field, "data-testid": "category-create-form-handle-input" }) }),
              /* @__PURE__ */ jsx(Form.ErrorMessage, { "data-testid": "category-create-form-handle-error" })
            ] });
          }
        }
      )
    ] }),
    /* @__PURE__ */ jsx(
      Form.Field,
      {
        control: form.control,
        name: "description",
        render: ({ field }) => {
          return /* @__PURE__ */ jsxs(Form.Item, { "data-testid": "category-create-form-description-item", children: [
            /* @__PURE__ */ jsx(Form.Label, { optional: true, "data-testid": "category-create-form-description-label", children: t("fields.description") }),
            /* @__PURE__ */ jsx(Form.Control, { "data-testid": "category-create-form-description-control", children: /* @__PURE__ */ jsx(Textarea, { ...field, "data-testid": "category-create-form-description-textarea" }) }),
            /* @__PURE__ */ jsx(Form.ErrorMessage, { "data-testid": "category-create-form-description-error" })
          ] });
        }
      }
    ),
    /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-1 gap-4 md:grid-cols-2", children: [
      /* @__PURE__ */ jsx(
        Form.Field,
        {
          control: form.control,
          name: "status",
          render: ({ field: { ref, onChange, ...field } }) => {
            return /* @__PURE__ */ jsxs(Form.Item, { "data-testid": "category-create-form-status-item", children: [
              /* @__PURE__ */ jsx(Form.Label, { "data-testid": "category-create-form-status-label", children: t("categories.fields.status.label") }),
              /* @__PURE__ */ jsx(Form.Control, { "data-testid": "category-create-form-status-control", children: /* @__PURE__ */ jsxs(
                Select,
                {
                  dir: direction,
                  ...field,
                  onValueChange: onChange,
                  "data-testid": "category-create-form-status-select",
                  children: [
                    /* @__PURE__ */ jsx(Select.Trigger, { ref, "data-testid": "category-create-form-status-select-trigger", children: /* @__PURE__ */ jsx(Select.Value, { "data-testid": "category-create-form-status-select-value" }) }),
                    /* @__PURE__ */ jsxs(Select.Content, { "data-testid": "category-create-form-status-select-content", children: [
                      /* @__PURE__ */ jsx(Select.Item, { value: "active", "data-testid": "category-create-form-status-select-option-active", children: t("categories.fields.status.active") }),
                      /* @__PURE__ */ jsx(Select.Item, { value: "inactive", "data-testid": "category-create-form-status-select-option-inactive", children: t("categories.fields.status.inactive") })
                    ] })
                  ]
                }
              ) }),
              /* @__PURE__ */ jsx(Form.ErrorMessage, { "data-testid": "category-create-form-status-error" })
            ] });
          }
        }
      ),
      /* @__PURE__ */ jsx(
        Form.Field,
        {
          control: form.control,
          name: "visibility",
          render: ({ field: { ref, onChange, ...field } }) => {
            return /* @__PURE__ */ jsxs(Form.Item, { "data-testid": "category-create-form-visibility-item", children: [
              /* @__PURE__ */ jsx(Form.Label, { "data-testid": "category-create-form-visibility-label", children: t("categories.fields.visibility.label") }),
              /* @__PURE__ */ jsx(Form.Control, { "data-testid": "category-create-form-visibility-control", children: /* @__PURE__ */ jsxs(
                Select,
                {
                  dir: direction,
                  ...field,
                  onValueChange: onChange,
                  "data-testid": "category-create-form-visibility-select",
                  children: [
                    /* @__PURE__ */ jsx(Select.Trigger, { ref, "data-testid": "category-create-form-visibility-select-trigger", children: /* @__PURE__ */ jsx(Select.Value, { "data-testid": "category-create-form-visibility-select-value" }) }),
                    /* @__PURE__ */ jsxs(Select.Content, { "data-testid": "category-create-form-visibility-select-content", children: [
                      /* @__PURE__ */ jsx(Select.Item, { value: "public", "data-testid": "category-create-form-visibility-select-option-public", children: t("categories.fields.visibility.public") }),
                      /* @__PURE__ */ jsx(Select.Item, { value: "internal", "data-testid": "category-create-form-visibility-select-option-internal", children: t("categories.fields.visibility.internal") })
                    ] })
                  ]
                }
              ) }),
              /* @__PURE__ */ jsx(Form.ErrorMessage, { "data-testid": "category-create-form-visibility-error" })
            ] });
          }
        }
      )
    ] })
  ] }) });
};
Root._tabMeta = defineTabMeta({
  id: "details",
  labelKey: "categories.create.tabs.details",
  validationFields: ["name", "handle", "description", "status", "visibility"]
});
var CreateCategoryDetails = Root;

// src/pages/categories/category-create/components/create-category-form/create-category-nesting.tsx
import { Badge } from "@medusajs/ui";
import { useMemo, useState } from "react";
import { useWatch } from "react-hook-form";
import { useTranslation as useTranslation2 } from "react-i18next";
import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
var ID = "new-item";
var Root2 = () => {
  const { t } = useTranslation2();
  const form = useTabbedForm();
  const [snapshot, setSnapshot] = useState([]);
  const shouldFreeze = form.formState.isSubmitting;
  const { product_categories, isPending, isError, error } = useProductCategories({
    parent_category_id: "null",
    limit: 9999,
    fields: "id,name,parent_category_id,rank,category_children,rank",
    include_descendants_tree: true
  });
  const parentCategoryId = useWatch({
    control: form.control,
    name: "parent_category_id"
  });
  const watchedRank = useWatch({
    control: form.control,
    name: "rank"
  });
  const watchedName = useWatch({
    control: form.control,
    name: "name"
  });
  const value = useMemo(() => {
    const temp = {
      id: ID,
      name: watchedName,
      parent_category_id: parentCategoryId,
      rank: watchedRank,
      category_children: null
    };
    return insertCategoryTreeItem(product_categories ?? [], temp);
  }, [product_categories, watchedName, parentCategoryId, watchedRank]);
  const handleChange = ({
    parentId,
    index
  }, list) => {
    form.setValue("parent_category_id", parentId, {
      shouldDirty: true,
      shouldTouch: true
    });
    form.setValue("rank", index, {
      shouldDirty: true,
      shouldTouch: true
    });
    setSnapshot(list);
  };
  if (isError) {
    throw error;
  }
  const ready = !isPending && !!product_categories;
  return /* @__PURE__ */ jsx2("div", { className: "bg-ui-bg-subtle flex-1", "data-testid": "category-create-form-nesting", children: /* @__PURE__ */ jsx2(
    CategoryTree,
    {
      value: shouldFreeze ? snapshot : value,
      enableDrag: (item) => item.id === ID,
      onChange: handleChange,
      renderValue: (item) => {
        if (item.id === ID) {
          return /* @__PURE__ */ jsxs2("div", { className: "flex items-center gap-x-3", "data-testid": "category-create-form-nesting-new-item", children: [
            /* @__PURE__ */ jsx2("span", { children: item.name }),
            /* @__PURE__ */ jsx2(Badge, { size: "2xsmall", color: "blue", "data-testid": "category-create-form-nesting-new-badge", children: t("categories.fields.new.label") })
          ] });
        }
        return item.name;
      },
      isLoading: !ready
    }
  ) });
};
Root2._tabMeta = defineTabMeta({
  id: "organize",
  labelKey: "categories.create.tabs.organize",
  validationFields: ["parent_category_id", "rank"]
});
var CreateCategoryNesting = Root2;

// src/pages/categories/category-create/components/create-category-form/create-category-form.tsx
import { jsx as jsx3 } from "react/jsx-runtime";
var CreateCategoryForm = ({
  parentCategoryId,
  children,
  schema,
  defaultValues: extraDefaults
}) => {
  const { t } = useTranslation3();
  const { handleSuccess } = useRouteModal();
  const form = useForm({
    defaultValues: {
      name: "",
      description: "",
      handle: "",
      status: "active",
      visibility: "public",
      rank: parentCategoryId ? 0 : null,
      parent_category_id: parentCategoryId,
      ...extraDefaults
    },
    resolver: zodResolver(schema ?? CreateCategorySchema)
  });
  const { mutateAsync, isPending } = useCreateProductCategory();
  const handleSubmit = form.handleSubmit(async (data) => {
    const { visibility, status, parent_category_id, rank, name, ...rest } = data;
    const parsedData = transformNullableFormData(rest, false);
    await mutateAsync(
      {
        name,
        ...parsedData,
        parent_category_id: parent_category_id ?? void 0,
        rank: rank ?? void 0,
        is_active: status === "active",
        is_internal: visibility === "internal"
      },
      {
        onSuccess: ({ product_category }) => {
          toast.success(
            t("categories.create.successToast", {
              name: product_category.name
            })
          );
          handleSuccess(`/categories/${product_category.id}`);
        },
        onError: (error) => {
          toast.error(error.message);
        }
      }
    );
  });
  const defaultTabs = useMemo2(
    () => [
      /* @__PURE__ */ jsx3(CreateCategoryDetails, {}, "details"),
      /* @__PURE__ */ jsx3(CreateCategoryNesting, {}, "organize")
    ],
    []
  );
  const hasCustomChildren = Children.count(children) > 0;
  return /* @__PURE__ */ jsx3(
    TabbedForm,
    {
      form,
      onSubmit: handleSubmit,
      isLoading: isPending,
      children: hasCustomChildren ? children : defaultTabs
    }
  );
};

// src/pages/categories/category-create/category-create.tsx
import { jsx as jsx4 } from "react/jsx-runtime";
var Root3 = ({ children }) => {
  const [searchParams] = useSearchParams();
  const parentCategoryId = searchParams.get("parent_category_id");
  return /* @__PURE__ */ jsx4(RouteFocusModal, { children: Children2.count(children) > 0 ? children : /* @__PURE__ */ jsx4(CreateCategoryForm, { parentCategoryId }) });
};
var CategoryCreatePage = Object.assign(Root3, {
  Form: CreateCategoryForm,
  DetailsTab: CreateCategoryDetails,
  OrganizeTab: CreateCategoryNesting,
  Tab: TabbedForm.Tab
});
var CategoryCreate = Root3;

export {
  CreateCategorySchema,
  CategoryCreatePage,
  CategoryCreate
};
