import {
  TextCell
} from "./chunk-JHIMVLB2.js";
import {
  _DataTable,
  useDataTable
} from "./chunk-ULJ3OMWU.js";
import {
  SingleColumnPage
} from "./chunk-XIZLPYEE.js";
import {
  Combobox
} from "./chunk-AW77UWCZ.js";
import {
  ActionMenu
} from "./chunk-BDGZ4EQO.js";
import {
  useAttributeTableFilters
} from "./chunk-RT6L7JXU.js";
import {
  useAttributeTableQuery
} from "./chunk-C3WE6EFO.js";
import {
  attributesQueryKeys,
  useAttributes,
  useDeleteAttribute,
  useUpdateAttribute
} from "./chunk-XMVTX2EN.js";
import {
  useProductCategories
} from "./chunk-52BRBQMY.js";
import {
  queryClient
} from "./chunk-RHKRREUU.js";
import {
  sdk
} from "./chunk-RIN4CBRB.js";

// src/pages/attributes/attribute-list/loader.ts
var attributeListQuery = () => ({
  queryKey: attributesQueryKeys.lists(),
  queryFn: async () => sdk.admin.attributes.query({
    limit: 20,
    offset: 0,
    fields: "*possible_values,*product_categories"
  })
});
var attributeListLoader = async (_args) => {
  const query = attributeListQuery();
  return queryClient.getQueryData(query.queryKey) ?? await queryClient.fetchQuery(query);
};

// src/pages/attributes/attribute-list/attribute-list.tsx
import { Children as Children3 } from "react";

// src/pages/attributes/attribute-list/components/attribute-list-view/attribute-list-view.tsx
import { Children as Children2 } from "react";
import { Container } from "@medusajs/ui";

// src/pages/attributes/attribute-list/components/attribute-list-view/attribute-list-data-table.tsx
import { keepPreviousData } from "@tanstack/react-query";
import { useTranslation as useTranslation2 } from "react-i18next";

// src/hooks/table/columns/use-attribute-table-columns.tsx
import { createColumnHelper } from "@tanstack/react-table";
import { useMemo, useState } from "react";
import { createPortal } from "react-dom";
import { useTranslation } from "react-i18next";
import {
  Badge,
  Button,
  Heading,
  Prompt,
  Switch,
  Text,
  toast,
  usePrompt
} from "@medusajs/ui";
import { PencilSquare, Trash } from "@medusajs/icons";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
var MAX_VISIBLE_VALUES = 2;
var FilterableToggle = ({ attribute }) => {
  const { mutateAsync } = useUpdateAttribute(attribute.id);
  const handleToggle = async (checked) => {
    try {
      await mutateAsync({ is_filterable: checked });
    } catch (err) {
      toast.error(err.message);
    }
  };
  return /* @__PURE__ */ jsx("div", { onClick: (e) => {
    e.preventDefault();
    e.stopPropagation();
  }, children: /* @__PURE__ */ jsx(
    Switch,
    {
      checked: !!attribute.is_filterable,
      onCheckedChange: handleToggle,
      size: "small"
    }
  ) });
};
var GlobalToggle = ({ attribute }) => {
  const { t } = useTranslation();
  const { mutateAsync } = useUpdateAttribute(attribute.id);
  const [categoryModalOpen, setCategoryModalOpen] = useState(false);
  const [selectedCategoryIds, setSelectedCategoryIds] = useState([]);
  const categories = attribute.product_categories ?? [];
  const isGlobal = !categories.length;
  const { product_categories: allCategories } = useProductCategories({
    limit: 999
  });
  const categoryOptions = (allCategories ?? []).map((cat) => ({
    label: cat.name,
    value: cat.id
  }));
  const handleToggle = async (checked) => {
    if (checked) {
      try {
        await mutateAsync({ product_category_ids: [] });
      } catch (err) {
        toast.error(err.message);
      }
    } else {
      setSelectedCategoryIds(categories.map((c) => c.id));
      setCategoryModalOpen(true);
    }
  };
  const handleSaveCategory = async () => {
    if (!selectedCategoryIds.length) return;
    try {
      await mutateAsync({
        product_category_ids: selectedCategoryIds
      });
      setCategoryModalOpen(false);
      setSelectedCategoryIds([]);
    } catch (err) {
      toast.error(err.message);
    }
  };
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx("div", { onClick: (e) => {
      e.preventDefault();
      e.stopPropagation();
    }, children: /* @__PURE__ */ jsx(
      Switch,
      {
        checked: isGlobal,
        onCheckedChange: handleToggle,
        size: "small"
      }
    ) }),
    categoryModalOpen && createPortal(
      /* @__PURE__ */ jsxs(
        "div",
        {
          className: "fixed inset-0 z-50 flex items-center justify-center",
          onClick: (e) => {
            e.preventDefault();
            e.stopPropagation();
          },
          children: [
            /* @__PURE__ */ jsx(
              "div",
              {
                className: "bg-ui-bg-overlay fixed inset-0",
                onClick: (e) => {
                  e.preventDefault();
                  e.stopPropagation();
                }
              }
            ),
            /* @__PURE__ */ jsxs("div", { className: "bg-ui-bg-base shadow-elevation-flyout relative flex w-full max-w-[400px] flex-col rounded-lg border", children: [
              /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-y-1 px-6 pt-6", children: [
                /* @__PURE__ */ jsx(Heading, { level: "h2", children: t("attributes.selectCategory.title") }),
                /* @__PURE__ */ jsx(Text, { size: "small", className: "text-ui-fg-subtle", children: t("attributes.selectCategory.description") })
              ] }),
              /* @__PURE__ */ jsx("div", { className: "px-6 py-4", children: /* @__PURE__ */ jsx(
                Combobox,
                {
                  options: categoryOptions,
                  value: selectedCategoryIds,
                  onChange: (val) => setSelectedCategoryIds(val)
                }
              ) }),
              /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-end gap-x-2 p-6", children: [
                /* @__PURE__ */ jsx(
                  Button,
                  {
                    variant: "secondary",
                    size: "small",
                    onClick: () => {
                      setCategoryModalOpen(false);
                      setSelectedCategoryIds([]);
                    },
                    children: t("actions.cancel")
                  }
                ),
                /* @__PURE__ */ jsx(
                  Button,
                  {
                    size: "small",
                    disabled: !selectedCategoryIds.length,
                    onClick: () => handleSaveCategory(),
                    children: t("actions.save")
                  }
                )
              ] })
            ] })
          ]
        }
      ),
      document.body
    )
  ] });
};
var AttributeActions = ({
  attribute
}) => {
  const { t } = useTranslation();
  const prompt = usePrompt();
  const { mutateAsync } = useDeleteAttribute(attribute.id);
  const [inUseOpen, setInUseOpen] = useState(false);
  const handleDelete = async () => {
    const res = await prompt({
      title: t("general.areYouSure"),
      description: t("attributes.delete.confirmation", {
        name: attribute.name
      }),
      confirmText: t("actions.delete"),
      cancelText: t("actions.cancel")
    });
    if (!res) return;
    try {
      await mutateAsync(void 0);
      toast.success(
        t("attributes.delete.successToast", { name: attribute.name })
      );
    } catch (err) {
      const isInUse = err.message?.includes("can't be deleted");
      if (isInUse) {
        setInUseOpen(true);
      } else {
        toast.error(err.message);
      }
    }
  };
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(
      ActionMenu,
      {
        groups: [
          {
            actions: [
              {
                label: t("actions.edit"),
                to: `${attribute.id}/edit`,
                icon: /* @__PURE__ */ jsx(PencilSquare, {})
              }
            ]
          },
          {
            actions: [
              {
                label: t("actions.delete"),
                onClick: handleDelete,
                icon: /* @__PURE__ */ jsx(Trash, {})
              }
            ]
          }
        ]
      }
    ),
    createPortal(
      /* @__PURE__ */ jsx(Prompt, { open: inUseOpen, variant: "confirmation", children: /* @__PURE__ */ jsxs(Prompt.Content, { children: [
        /* @__PURE__ */ jsxs(Prompt.Header, { children: [
          /* @__PURE__ */ jsx(Prompt.Title, { children: t("attributes.delete.title") }),
          /* @__PURE__ */ jsx(Prompt.Description, { children: t("attributes.delete.inUseMessage", {
            name: attribute.name
          }) })
        ] }),
        /* @__PURE__ */ jsx(Prompt.Footer, { children: /* @__PURE__ */ jsx(Prompt.Action, { onClick: () => setInUseOpen(false), children: t("attributes.delete.gotIt") }) })
      ] }) }),
      document.body
    )
  ] });
};
var columnHelper = createColumnHelper();
var useAttributeTableColumns = () => {
  const { t } = useTranslation();
  return useMemo(
    () => [
      columnHelper.accessor("name", {
        header: () => t("attributes.fields.productAttribute"),
        cell: ({ getValue }) => /* @__PURE__ */ jsx(TextCell, { text: getValue() })
      }),
      columnHelper.accessor("handle", {
        header: () => t("attributes.fields.handle"),
        cell: ({ getValue }) => /* @__PURE__ */ jsx(TextCell, { text: getValue() || "-" })
      }),
      columnHelper.accessor("is_filterable", {
        header: () => t("attributes.fields.filterable"),
        cell: ({ row }) => /* @__PURE__ */ jsx(FilterableToggle, { attribute: row.original })
      }),
      columnHelper.display({
        id: "is_global",
        header: () => t("attributes.fields.global"),
        cell: ({ row }) => /* @__PURE__ */ jsx(GlobalToggle, { attribute: row.original })
      }),
      columnHelper.display({
        id: "values",
        header: () => t("attributes.fields.values"),
        cell: ({ row }) => {
          const values = row.original.possible_values ?? [];
          if (!values.length) {
            return /* @__PURE__ */ jsx("span", { className: "text-ui-fg-muted", children: "-" });
          }
          const visible = values.slice(0, MAX_VISIBLE_VALUES);
          const remaining = values.length - MAX_VISIBLE_VALUES;
          return /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-x-1", children: [
            visible.map((v) => /* @__PURE__ */ jsx(Badge, { size: "2xsmall", color: "grey", children: v.value }, v.id)),
            remaining > 0 && /* @__PURE__ */ jsxs(Badge, { size: "2xsmall", color: "grey", children: [
              "+",
              remaining
            ] })
          ] });
        }
      }),
      columnHelper.display({
        id: "actions",
        cell: ({ row }) => /* @__PURE__ */ jsx(AttributeActions, { attribute: row.original })
      })
    ],
    [t]
  );
};

// src/pages/attributes/attribute-list/components/attribute-list-view/attribute-list-data-table.tsx
import { jsx as jsx2 } from "react/jsx-runtime";
var PAGE_SIZE = 20;
var AttributeListDataTable = () => {
  const { t } = useTranslation2();
  const { searchParams, raw } = useAttributeTableQuery({ pageSize: PAGE_SIZE });
  const { attributes, count, isPending, isError, error } = useAttributes(
    searchParams,
    {
      placeholderData: keepPreviousData
    }
  );
  const filters = useAttributeTableFilters();
  const columns = useAttributeTableColumns();
  const { table } = useDataTable({
    data: attributes ?? [],
    count,
    columns,
    getRowId: (row) => row.id,
    pageSize: PAGE_SIZE,
    enablePagination: true
  });
  if (isError) {
    throw error;
  }
  return /* @__PURE__ */ jsx2(
    _DataTable,
    {
      table,
      columns,
      count,
      pageSize: PAGE_SIZE,
      isLoading: isPending,
      filters,
      orderBy: [
        { key: "name", label: t("fields.name") },
        { key: "created_at", label: t("fields.createdAt") },
        { key: "updated_at", label: t("fields.updatedAt") }
      ],
      navigateTo: (row) => row.original.id,
      pagination: true,
      search: true,
      queryObject: raw,
      noRecords: {
        message: t("attributes.list.noRecordsMessage")
      },
      "data-testid": "attribute-list-table"
    }
  );
};

// src/pages/attributes/attribute-list/components/attribute-list-view/attribute-list-header.tsx
import { Children } from "react";
import { Button as Button2, Heading as Heading2 } from "@medusajs/ui";
import { useTranslation as useTranslation3 } from "react-i18next";
import { Link } from "react-router-dom";
import { Fragment as Fragment2, jsx as jsx3, jsxs as jsxs2 } from "react/jsx-runtime";
var AttributeListTitle = () => {
  const { t } = useTranslation3();
  return /* @__PURE__ */ jsx3(Heading2, { "data-testid": "attribute-list-table-heading", children: t("attributes.list.title") });
};
var AttributeListActions = ({
  children
}) => {
  const { t } = useTranslation3();
  return /* @__PURE__ */ jsx3("div", { className: "flex items-center justify-center gap-x-2", children: Children.count(children) > 0 ? children : /* @__PURE__ */ jsx3(
    Button2,
    {
      variant: "secondary",
      size: "small",
      asChild: true,
      "data-testid": "attribute-list-table-create-button",
      children: /* @__PURE__ */ jsx3(Link, { to: "create", children: t("actions.create") })
    }
  ) });
};
var AttributeListHeader = ({
  children
}) => {
  return /* @__PURE__ */ jsx3(
    "div",
    {
      className: "flex items-center justify-between px-6 py-4",
      "data-testid": "attribute-list-table-header",
      children: Children.count(children) > 0 ? children : /* @__PURE__ */ jsxs2(Fragment2, { children: [
        /* @__PURE__ */ jsx3(AttributeListTitle, {}),
        /* @__PURE__ */ jsx3(AttributeListActions, {})
      ] })
    }
  );
};

// src/pages/attributes/attribute-list/components/attribute-list-view/attribute-list-view.tsx
import { Fragment as Fragment3, jsx as jsx4, jsxs as jsxs3 } from "react/jsx-runtime";
var AttributeListView = ({
  children
}) => {
  return /* @__PURE__ */ jsx4(Container, { className: "divide-y p-0", children: Children2.count(children) > 0 ? children : /* @__PURE__ */ jsxs3(Fragment3, { children: [
    /* @__PURE__ */ jsx4(AttributeListHeader, {}),
    /* @__PURE__ */ jsx4(AttributeListDataTable, {})
  ] }) });
};

// src/pages/attributes/attribute-list/attribute-list.tsx
import { jsx as jsx5 } from "react/jsx-runtime";
var Root = ({ children }) => {
  return /* @__PURE__ */ jsx5(SingleColumnPage, { showMetadata: false, showJSON: false, hasOutlet: true, children: Children3.count(children) > 0 ? children : /* @__PURE__ */ jsx5(AttributeListView, {}) });
};
var AttributeListPage = Object.assign(Root, {
  Table: AttributeListView,
  Header: AttributeListHeader,
  HeaderTitle: AttributeListTitle,
  HeaderActions: AttributeListActions,
  DataTable: AttributeListDataTable
});

export {
  attributeListLoader,
  AttributeListPage
};
