import {
  useProductTypeTableColumns
} from "./chunk-ATKJ6XLW.mjs";
import {
  getFormattedShippingOptionLocationName
} from "./chunk-UC26CCHZ.mjs";
import {
  TextCell
} from "./chunk-DRHDNSJA.mjs";
import {
  DateCell
} from "./chunk-EJWRAUTW.mjs";
import {
  useProductTableColumns
} from "./chunk-4AKNAVPX.mjs";
import {
  _DataTable,
  useDataTable
} from "./chunk-7TWTWTDT.mjs";
import {
  useShippingOptionTableQuery
} from "./chunk-EJUI5JDF.mjs";
import {
  useProductTypeTableQuery
} from "./chunk-TDK3JDOB.mjs";
import {
  useShippingOptionTableFilters
} from "./chunk-3C6WQ7NH.mjs";
import {
  useProductTypeTableFilters
} from "./chunk-CBSCX7RE.mjs";
import {
  useProductTableQuery
} from "./chunk-R65S6ZZV.mjs";
import {
  useProductTableFilters
} from "./chunk-Q6PYDJZC.mjs";
import {
  StackedDrawer,
  StackedFocusModal
} from "./chunk-OV6YUU3D.mjs";
import {
  useProductTypes
} from "./chunk-QBIQEVTU.mjs";
import {
  useShippingOptions
} from "./chunk-HBXV7ENS.mjs";
import {
  useStockLocations
} from "./chunk-CDORR33H.mjs";
import {
  useProduct,
  useProducts
} from "./chunk-LA2ILUXH.mjs";

// src/routes/tax-regions/common/constants.ts
var TaxRateRuleReferenceType = /* @__PURE__ */ ((TaxRateRuleReferenceType2) => {
  TaxRateRuleReferenceType2["PRODUCT"] = "product";
  TaxRateRuleReferenceType2["PRODUCT_TYPE"] = "product_type";
  TaxRateRuleReferenceType2["SHIPPING_OPTION"] = "shipping_option";
  return TaxRateRuleReferenceType2;
})(TaxRateRuleReferenceType || {});

// src/routes/tax-regions/common/components/target-form/target-form.tsx
import { Button, Checkbox } from "@medusajs/ui";
import { keepPreviousData } from "@tanstack/react-query";
import {
  createColumnHelper as createColumnHelper2
} from "@tanstack/react-table";
import { useEffect, useMemo as useMemo2, useState } from "react";
import { useTranslation as useTranslation2 } from "react-i18next";
import { useSearchParams } from "react-router-dom";

// src/hooks/table/columns/use-shipping-option-table-columns.tsx
import { createColumnHelper } from "@tanstack/react-table";
import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import { jsx } from "react/jsx-runtime";
var columnHelper = createColumnHelper();
var useShippingOptionTableColumns = () => {
  const { t } = useTranslation();
  return useMemo(
    () => [
      columnHelper.accessor("name", {
        header: () => t("fields.name"),
        cell: ({ getValue }) => /* @__PURE__ */ jsx(TextCell, { text: getValue() })
      }),
      columnHelper.accessor("shipping_profile", {
        header: () => t("fields.shippingProfile"),
        cell: ({ row }) => /* @__PURE__ */ jsx(TextCell, { text: row.original.shipping_profile?.name || "N/A" })
      }),
      columnHelper.display({
        id: "location",
        header: () => t("fields.location"),
        cell: ({ row }) => {
          const locationName = getFormattedShippingOptionLocationName(
            row.original
          );
          return /* @__PURE__ */ jsx(TextCell, { text: locationName });
        }
      }),
      columnHelper.display({
        id: "service_zone",
        header: () => t("fields.serviceZone"),
        cell: ({ row }) => {
          const serviceZoneName = row.original.service_zone?.name;
          return /* @__PURE__ */ jsx(TextCell, { text: serviceZoneName || "N/A" });
        }
      }),
      columnHelper.display({
        id: "enabled_in_store",
        header: () => t("fields.enabledInStore"),
        cell: ({ row }) => {
          let text = "N/A";
          const val = row.original.rules?.find(
            (r) => r.attribute === "enabled_in_store"
          );
          if (val) {
            text = val.value === "true" ? "Yes" : "No";
          }
          return /* @__PURE__ */ jsx(TextCell, { text });
        }
      }),
      columnHelper.display({
        id: "is_return",
        header: () => t("fields.isReturn"),
        cell: ({ row }) => {
          let text = "N/A";
          const val = row.original.rules?.find(
            (r) => r.attribute === "is_return"
          );
          if (val) {
            text = val.value === "true" ? "Yes" : "No";
          }
          return /* @__PURE__ */ jsx(TextCell, { text });
        }
      }),
      columnHelper.accessor("created_at", {
        header: () => t("fields.createdAt"),
        cell: ({ getValue }) => {
          return /* @__PURE__ */ jsx(DateCell, { date: getValue() });
        }
      })
    ],
    [t]
  );
};

// src/routes/tax-regions/common/components/target-form/target-form.tsx
import { jsx as jsx2, jsxs } from "react/jsx-runtime";
function initRowSelection(state) {
  return state.reduce((acc, reference) => {
    acc[reference.value] = true;
    return acc;
  }, {});
}
var TargetForm = ({
  referenceType,
  type,
  setState,
  state
}) => {
  const { t } = useTranslation2();
  const Component = type === "focus" ? StackedFocusModal : StackedDrawer;
  const [intermediate, setIntermediate] = useState(state);
  const handleSave = () => {
    setState(intermediate);
  };
  return /* @__PURE__ */ jsxs("div", { className: "flex size-full flex-col overflow-hidden", children: [
    /* @__PURE__ */ jsx2(Component.Body, { className: "min-h-0 p-0", children: /* @__PURE__ */ jsx2(
      Table,
      {
        referenceType,
        initialRowState: initRowSelection(state),
        intermediate,
        setIntermediate
      }
    ) }),
    /* @__PURE__ */ jsxs(Component.Footer, { children: [
      /* @__PURE__ */ jsx2(Component.Close, { asChild: true, children: /* @__PURE__ */ jsx2(Button, { variant: "secondary", size: "small", type: "button", children: t("actions.cancel") }) }),
      /* @__PURE__ */ jsx2(Button, { type: "button", size: "small", onClick: handleSave, children: t("actions.save") })
    ] })
  ] });
};
var Table = ({ referenceType, ...props }) => {
  switch (referenceType) {
    // case TaxRateRuleReferenceType.CUSTOMER_GROUP:
    // return <CustomerGroupTable {...props} />
    case "product" /* PRODUCT */:
      return /* @__PURE__ */ jsx2(ProductTable, { ...props });
    // case TaxRateRuleReferenceType.PRODUCT_COLLECTION:
    // return <ProductCollectionTable {...props} />
    case "product_type" /* PRODUCT_TYPE */:
      return /* @__PURE__ */ jsx2(ProductTypeTable, { ...props });
    // case TaxRateRuleReferenceType.PRODUCT_TAG:
    // return <ProductTagTable {...props} />
    case "shipping_option" /* SHIPPING_OPTION */:
      return /* @__PURE__ */ jsx2(ShippingOptionTable, { ...props });
    default:
      return null;
  }
};
var PAGE_SIZE = 50;
var PREFIX_PRODUCT = "p";
var ProductTable = ({
  initialRowState,
  intermediate,
  setIntermediate
}) => {
  const { t } = useTranslation2();
  const [rowSelection, setRowSelection] = useState(initialRowState);
  useCleanupSearchParams();
  const { searchParams, raw } = useProductTableQuery({
    pageSize: PAGE_SIZE,
    prefix: PREFIX_PRODUCT
  });
  const { products, count, isLoading, isError, error } = useProducts(
    searchParams,
    {
      placeholderData: keepPreviousData
    }
  );
  const updater = (value) => {
    const state = typeof value === "function" ? value(rowSelection) : value;
    const currentIds = Object.keys(rowSelection);
    const ids = Object.keys(state);
    const newIds = ids.filter((id) => !currentIds.includes(id));
    const removedIds = currentIds.filter((id) => !ids.includes(id));
    const newProducts = products?.filter((p) => newIds.includes(p.id)).map((p) => ({
      value: p.id,
      label: p.title
    })) || [];
    const filteredIntermediate = intermediate.filter(
      (p) => !removedIds.includes(p.value)
    );
    setIntermediate([...filteredIntermediate, ...newProducts]);
    setRowSelection(state);
  };
  const filters = useProductTableFilters();
  const columns = useProductColumns();
  const { table } = useDataTable({
    data: products || [],
    columns,
    count,
    enablePagination: true,
    enableRowSelection: true,
    getRowId: (row) => row.id,
    rowSelection: {
      state: rowSelection,
      updater
    },
    pageSize: PAGE_SIZE,
    prefix: PREFIX_PRODUCT
  });
  if (isError) {
    throw error;
  }
  return /* @__PURE__ */ jsx2(
    _DataTable,
    {
      table,
      columns,
      pageSize: PAGE_SIZE,
      count,
      isLoading,
      filters,
      orderBy: [
        { key: "title", label: t("fields.title") },
        { key: "created_at", label: t("fields.createdAt") },
        { key: "updated_at", label: t("fields.updatedAt") }
      ],
      layout: "fill",
      pagination: true,
      search: true,
      prefix: PREFIX_PRODUCT,
      queryObject: raw
    }
  );
};
var pColumnHelper = createColumnHelper2();
var useProductColumns = () => {
  const base = useProductTableColumns();
  return useMemo2(
    () => [
      pColumnHelper.display({
        id: "select",
        header: ({ table }) => {
          return /* @__PURE__ */ jsx2(
            Checkbox,
            {
              checked: table.getIsSomePageRowsSelected() ? "indeterminate" : table.getIsAllPageRowsSelected(),
              onCheckedChange: (value) => table.toggleAllPageRowsSelected(!!value)
            }
          );
        },
        cell: ({ row }) => {
          return /* @__PURE__ */ jsx2(
            Checkbox,
            {
              checked: row.getIsSelected(),
              onCheckedChange: (value) => row.toggleSelected(!!value),
              onClick: (e) => {
                e.stopPropagation();
              }
            }
          );
        }
      }),
      ...base
    ],
    [base]
  );
};
var PREFIX_PRODUCT_TYPE = "pt";
var ProductTypeTable = ({
  initialRowState,
  intermediate,
  setIntermediate
}) => {
  const { t } = useTranslation2();
  const [rowSelection, setRowSelection] = useState(initialRowState);
  useCleanupSearchParams();
  const { searchParams, raw } = useProductTypeTableQuery({
    pageSize: PAGE_SIZE,
    prefix: PREFIX_PRODUCT_TYPE
  });
  const { product_types, count, isLoading, isError, error } = useProductTypes(
    searchParams,
    {
      placeholderData: keepPreviousData
    }
  );
  const updater = (value) => {
    const state = typeof value === "function" ? value(rowSelection) : value;
    const currentIds = Object.keys(rowSelection);
    const ids = Object.keys(state);
    const newIds = ids.filter((id) => !currentIds.includes(id));
    const removedIds = currentIds.filter((id) => !ids.includes(id));
    const newTypes = product_types?.filter((p) => newIds.includes(p.id)).map((p) => ({
      value: p.id,
      label: p.value
    })) || [];
    const filteredIntermediate = intermediate.filter(
      (p) => !removedIds.includes(p.value)
    );
    setIntermediate([...filteredIntermediate, ...newTypes]);
    setRowSelection(state);
  };
  const filters = useProductTypeTableFilters();
  const columns = useProductTypeColumns();
  const { table } = useDataTable({
    data: product_types || [],
    columns,
    count,
    enablePagination: true,
    enableRowSelection: true,
    getRowId: (row) => row.id,
    rowSelection: {
      state: rowSelection,
      updater
    },
    pageSize: PAGE_SIZE,
    prefix: PREFIX_PRODUCT_TYPE
  });
  if (isError) {
    throw error;
  }
  return /* @__PURE__ */ jsx2(
    _DataTable,
    {
      table,
      columns,
      pageSize: PAGE_SIZE,
      count,
      isLoading,
      filters,
      orderBy: [
        { key: "value", label: t("fields.value") },
        { key: "created_at", label: t("fields.createdAt") },
        { key: "updated_at", label: t("fields.updatedAt") }
      ],
      layout: "fill",
      pagination: true,
      search: true,
      prefix: PREFIX_PRODUCT_TYPE,
      queryObject: raw
    }
  );
};
var ptColumnHelper = createColumnHelper2();
var useProductTypeColumns = () => {
  const base = useProductTypeTableColumns();
  return useMemo2(
    () => [
      ptColumnHelper.display({
        id: "select",
        header: ({ table }) => {
          return /* @__PURE__ */ jsx2(
            Checkbox,
            {
              checked: table.getIsSomePageRowsSelected() ? "indeterminate" : table.getIsAllPageRowsSelected(),
              onCheckedChange: (value) => table.toggleAllPageRowsSelected(!!value)
            }
          );
        },
        cell: ({ row }) => {
          return /* @__PURE__ */ jsx2(
            Checkbox,
            {
              checked: row.getIsSelected(),
              onCheckedChange: (value) => row.toggleSelected(!!value),
              onClick: (e) => {
                e.stopPropagation();
              }
            }
          );
        }
      }),
      ...base
    ],
    [base]
  );
};
var PREFIX_SHIPPING_OPTION = "so";
var ShippingOptionTable = ({
  initialRowState,
  intermediate,
  setIntermediate
}) => {
  const { t } = useTranslation2();
  const [rowSelection, setRowSelection] = useState(initialRowState);
  useCleanupSearchParams();
  const { searchParams, raw } = useShippingOptionTableQuery({
    pageSize: PAGE_SIZE,
    prefix: PREFIX_SHIPPING_OPTION
  });
  const { shipping_options, count, isLoading, isError, error } = useShippingOptions(
    {
      ...searchParams,
      fields: "+service_zone.fulfillment_set.location.*"
    },
    {
      placeholderData: keepPreviousData
    }
  );
  const updater = (value) => {
    const state = typeof value === "function" ? value(rowSelection) : value;
    const currentIds = Object.keys(rowSelection);
    const ids = Object.keys(state);
    const newIds = ids.filter((id) => !currentIds.includes(id));
    const removedIds = currentIds.filter((id) => !ids.includes(id));
    const newShippingOptions = shipping_options?.filter((p) => newIds.includes(p.id)).map((p) => ({
      value: p.id,
      label: p.name
    })) || [];
    const filteredIntermediate = intermediate.filter(
      (p) => !removedIds.includes(p.value)
    );
    setIntermediate([...filteredIntermediate, ...newShippingOptions]);
    setRowSelection(state);
  };
  const { stock_locations } = useStockLocations({
    limit: 1e3
  });
  const filters = useShippingOptionTableFilters(stock_locations || []);
  const columns = useShippingOptionColumns();
  const { table } = useDataTable({
    data: shipping_options || [],
    columns,
    count,
    enablePagination: true,
    enableRowSelection: true,
    getRowId: (row) => row.id,
    rowSelection: {
      state: rowSelection,
      updater
    },
    pageSize: PAGE_SIZE,
    prefix: PREFIX_SHIPPING_OPTION
  });
  if (isError) {
    throw error;
  }
  return /* @__PURE__ */ jsx2(
    _DataTable,
    {
      table,
      columns,
      pageSize: PAGE_SIZE,
      count,
      isLoading,
      filters,
      orderBy: [
        { key: "name", label: t("fields.name") },
        { key: "created_at", label: t("fields.createdAt") },
        { key: "updated_at", label: t("fields.updatedAt") }
      ],
      layout: "fill",
      pagination: true,
      search: true,
      prefix: PREFIX_SHIPPING_OPTION,
      queryObject: raw
    }
  );
};
var soColumnHelper = createColumnHelper2();
var useShippingOptionColumns = () => {
  const base = useShippingOptionTableColumns();
  return useMemo2(
    () => [
      soColumnHelper.display({
        id: "select",
        header: ({ table }) => {
          return /* @__PURE__ */ jsx2(
            Checkbox,
            {
              checked: table.getIsSomePageRowsSelected() ? "indeterminate" : table.getIsAllPageRowsSelected(),
              onCheckedChange: (value) => table.toggleAllPageRowsSelected(!!value)
            }
          );
        },
        cell: ({ row }) => {
          return /* @__PURE__ */ jsx2(
            Checkbox,
            {
              checked: row.getIsSelected(),
              onCheckedChange: (value) => row.toggleSelected(!!value),
              onClick: (e) => {
                e.stopPropagation();
              }
            }
          );
        }
      }),
      ...base
    ],
    [base]
  );
};
var useCleanupSearchParams = () => {
  const [_, setSearchParams] = useSearchParams();
  useEffect(() => {
    return () => {
      setSearchParams({});
    };
  }, []);
};

// src/routes/tax-regions/common/components/target-item/target-item.tsx
import { XMarkMini } from "@medusajs/icons";
import { IconButton, Text } from "@medusajs/ui";
import { jsx as jsx3, jsxs as jsxs2 } from "react/jsx-runtime";
var TargetItem = ({
  index,
  label,
  onRemove,
  value
}) => {
  const { product } = useProduct(
    value,
    {
      // TODO: Remove exclusion once we avoid including unnecessary relations by default in the query config
      fields: "id,title,-type,-collection,-options,-tags,-images,-variants,-sales_channels"
    },
    { enabled: !label }
  );
  return /* @__PURE__ */ jsxs2("div", { className: "bg-ui-bg-field-component shadow-borders-base flex items-center justify-between gap-2 rounded-md px-2 py-0.5", children: [
    /* @__PURE__ */ jsx3(Text, { size: "small", leading: "compact", children: label || product?.title }),
    /* @__PURE__ */ jsx3(
      IconButton,
      {
        size: "small",
        variant: "transparent",
        type: "button",
        onClick: () => onRemove(index),
        children: /* @__PURE__ */ jsx3(XMarkMini, {})
      }
    )
  ] });
};

// src/routes/tax-regions/common/schemas.ts
import { z } from "zod";
var TaxRateRuleReferenceSchema = z.object({
  value: z.string(),
  label: z.string()
});
var TaxRateRuleTargetSchema = z.object({
  reference_type: z.nativeEnum(TaxRateRuleReferenceType),
  references: z.array(TaxRateRuleReferenceSchema)
});

// src/routes/tax-regions/common/utils.ts
var createTaxRulePayload = (target) => {
  return target.references.map((reference) => ({
    reference: target.reference_type,
    reference_id: reference.value
  }));
};

export {
  TaxRateRuleReferenceType,
  TargetForm,
  TargetItem,
  TaxRateRuleReferenceSchema,
  createTaxRulePayload
};
