import {
  ListSummary
} from "./chunk-4F5GP7J7.js";
import {
  SidebarLink
} from "./chunk-4GPAS5GW.js";
import {
  getFormattedAddress
} from "./chunk-W6Y3PPU5.js";
import {
  PlaceholderCell
} from "./chunk-PHOCVOZ5.js";
import {
  TwoColumnPage
} from "./chunk-V5J73NPW.js";
import {
  DataTable
} from "./chunk-UQITHKTH.js";
import {
  useQueryParams
} from "./chunk-THHRRYRS.js";
import {
  stockLocationsQueryKeys,
  useStockLocations
} from "./chunk-OFKUNYQJ.js";
import {
  queryClient
} from "./chunk-RHKRREUU.js";
import {
  sdk
} from "./chunk-RIN4CBRB.js";

// src/pages/locations/location-list/location-list.tsx
import { Children } from "react";
import { ShoppingBag, TruckFast } from "@medusajs/icons";
import { Container, Heading } from "@medusajs/ui";
import { useTranslation as useTranslation2 } from "react-i18next";

// src/pages/locations/location-list/constants.ts
var LOCATION_LIST_FIELDS = "name,*sales_channels,*address,*fulfillment_sets,*fulfillment_sets.service_zones,*fulfillment_sets.service_zones.shipping_options,*fulfillment_sets.service_zones.shipping_options.shipping_profile";

// src/pages/locations/location-list/use-location-list-table-columns.tsx
import { PencilSquare, Trash } from "@medusajs/icons";
import {
  createDataTableColumnHelper,
  StatusBadge,
  toast,
  usePrompt
} from "@medusajs/ui";
import { useTranslation } from "react-i18next";
import { useMemo } from "react";
import { useNavigate } from "react-router-dom";
import { jsx } from "react/jsx-runtime";
var columnHelper = createDataTableColumnHelper();
var useLocationListTableColumns = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const prompt = usePrompt();
  const handleDelete = async (location) => {
    const result = await prompt({
      title: t("general.areYouSure"),
      description: t("stockLocations.delete.confirmation", {
        name: location.name
      }),
      confirmText: t("actions.remove"),
      cancelText: t("actions.cancel")
    });
    if (!result) {
      return;
    }
    try {
      await sdk.admin.stockLocation.delete(location.id);
      queryClient.invalidateQueries({
        queryKey: stockLocationsQueryKeys.lists()
      });
      queryClient.invalidateQueries({
        queryKey: stockLocationsQueryKeys.detail(location.id)
      });
      toast.success(
        t("stockLocations.delete.successToast", {
          name: location.name
        })
      );
    } catch (e) {
      toast.error(e.message);
    }
  };
  return useMemo(
    () => [
      columnHelper.accessor("name", {
        header: t("fields.name"),
        cell: ({ getValue }) => {
          const name = getValue();
          if (!name) {
            return /* @__PURE__ */ jsx(PlaceholderCell, {});
          }
          return /* @__PURE__ */ jsx("span", { className: "text-ui-fg-subtle text-small truncate", children: name });
        }
      }),
      columnHelper.accessor("address", {
        header: t("fields.address"),
        cell: ({ getValue, row }) => {
          const address = getValue();
          const location = row.original;
          if (!address) {
            return /* @__PURE__ */ jsx(PlaceholderCell, {});
          }
          return /* @__PURE__ */ jsx("div", { className: "flex flex-col", children: /* @__PURE__ */ jsx("span", { className: "text-ui-fg-subtle text-small truncate", children: getFormattedAddress({
            address: location.address
          }).join(", ") }) });
        }
      }),
      columnHelper.accessor("fulfillment_sets", {
        id: "shipping_fulfillment",
        header: t("stockLocations.fulfillmentSets.shipping.header"),
        cell: ({ getValue }) => {
          const fulfillmentSets = getValue();
          const shippingSet = fulfillmentSets?.find(
            (f) => f.type === "shipping" /* Shipping */
          );
          const fulfillmentSetExists = !!shippingSet;
          return /* @__PURE__ */ jsx(StatusBadge, { color: fulfillmentSetExists ? "green" : "grey", children: t(
            fulfillmentSetExists ? "statuses.enabled" : "statuses.disabled"
          ) });
        }
      }),
      columnHelper.accessor("fulfillment_sets", {
        id: "pickup_fulfillment",
        header: t("stockLocations.fulfillmentSets.pickup.header"),
        cell: ({ getValue }) => {
          const fulfillmentSets = getValue();
          const pickupSet = fulfillmentSets?.find(
            (f) => f.type === "pickup" /* Pickup */
          );
          const fulfillmentSetExists = !!pickupSet;
          return /* @__PURE__ */ jsx(StatusBadge, { color: fulfillmentSetExists ? "green" : "grey", children: t(
            fulfillmentSetExists ? "statuses.enabled" : "statuses.disabled"
          ) });
        }
      }),
      columnHelper.accessor("sales_channels", {
        header: t("stockLocations.salesChannels.label"),
        cell: ({ getValue }) => {
          const salesChannels = getValue();
          if (!salesChannels?.length) {
            return /* @__PURE__ */ jsx(PlaceholderCell, {});
          }
          return /* @__PURE__ */ jsx("div", { className: "flex items-center", children: /* @__PURE__ */ jsx(
            ListSummary,
            {
              inline: true,
              n: 1,
              list: salesChannels.map((s) => s.name)
            }
          ) });
        }
      }),
      columnHelper.action({
        actions: (ctx) => {
          const location = ctx.row.original;
          return [
            [
              {
                icon: /* @__PURE__ */ jsx(PencilSquare, {}),
                label: t("actions.edit"),
                onClick: () => {
                  navigate(`/settings/locations/${location.id}/edit`);
                }
              }
            ],
            [
              {
                icon: /* @__PURE__ */ jsx(Trash, {}),
                label: t("actions.delete"),
                onClick: () => handleDelete(location)
              }
            ]
          ];
        }
      })
    ],
    []
  );
};

// src/pages/locations/location-list/use-location-list-table-query.tsx
var useLocationListTableQuery = ({
  pageSize = 20,
  prefix
}) => {
  const queryObject = useQueryParams(["order", "offset", "q"], prefix);
  const { offset, ...rest } = queryObject;
  const searchParams = {
    limit: pageSize,
    offset: offset ? Number(offset) : 0,
    ...rest
  };
  return searchParams;
};

// src/pages/locations/location-list/location-list.tsx
import { keepPreviousData } from "@tanstack/react-query";
import { jsx as jsx2, jsxs } from "react/jsx-runtime";
var PAGE_SIZE = 20;
var PREFIX = "loc";
var LocationListContent = () => {
  const { t } = useTranslation2();
  const searchParams = useLocationListTableQuery({
    pageSize: PAGE_SIZE,
    prefix: PREFIX
  });
  const {
    stock_locations: stockLocations = [],
    count,
    isError,
    error,
    isLoading
  } = useStockLocations(
    {
      fields: LOCATION_LIST_FIELDS,
      ...searchParams
    },
    {
      placeholderData: keepPreviousData
    }
  );
  const columns = useLocationListTableColumns();
  if (isError) {
    throw error;
  }
  return /* @__PURE__ */ jsx2(
    Container,
    {
      className: "flex flex-col divide-y p-0",
      "data-testid": "location-list-container",
      children: /* @__PURE__ */ jsx2(
        DataTable,
        {
          data: stockLocations,
          columns,
          rowCount: count,
          pageSize: PAGE_SIZE,
          getRowId: (row) => row.id,
          heading: t("stockLocations.domain"),
          subHeading: t("stockLocations.list.description"),
          emptyState: {
            empty: {
              heading: t("stockLocations.list.noRecordsMessage"),
              description: t("stockLocations.list.noRecordsMessageEmpty")
            },
            filtered: {
              heading: t("stockLocations.list.noRecordsMessage"),
              description: t("stockLocations.list.noRecordsMessageFiltered")
            }
          },
          actions: [
            {
              label: t("actions.create"),
              to: "create"
            }
          ],
          isLoading,
          rowHref: (row) => `/settings/locations/${row.id}`,
          enableSearch: true,
          prefix: PREFIX,
          layout: "fill",
          "data-testid": "location-list-table"
        }
      )
    }
  );
};
var LinksSection = () => {
  const { t } = useTranslation2();
  return /* @__PURE__ */ jsxs(Container, { className: "p-0", "data-testid": "location-list-sidebar", children: [
    /* @__PURE__ */ jsx2(
      "div",
      {
        className: "flex items-center justify-between px-6 py-4",
        "data-testid": "location-list-sidebar-header",
        children: /* @__PURE__ */ jsx2(Heading, { level: "h2", "data-testid": "location-list-sidebar-heading", children: t("stockLocations.sidebar.header") })
      }
    ),
    /* @__PURE__ */ jsx2(
      SidebarLink,
      {
        to: "/settings/locations/shipping-profiles",
        labelKey: t("stockLocations.sidebar.shippingProfiles.label"),
        descriptionKey: t(
          "stockLocations.sidebar.shippingProfiles.description"
        ),
        icon: /* @__PURE__ */ jsx2(ShoppingBag, {}),
        "data-testid": "location-list-sidebar-shipping-profiles-link"
      }
    ),
    /* @__PURE__ */ jsx2(
      SidebarLink,
      {
        to: "/settings/locations/shipping-option-types",
        labelKey: t("stockLocations.sidebar.shippingOptionTypes.label"),
        descriptionKey: t(
          "stockLocations.sidebar.shippingOptionTypes.description"
        ),
        icon: /* @__PURE__ */ jsx2(TruckFast, {}),
        "data-testid": "location-list-sidebar-shipping-option-types-link"
      }
    )
  ] });
};
var Root = ({ children }) => {
  return Children.count(children) > 0 ? /* @__PURE__ */ jsx2(TwoColumnPage, { showJSON: true, children }) : /* @__PURE__ */ jsxs(TwoColumnPage, { showJSON: true, children: [
    /* @__PURE__ */ jsx2(TwoColumnPage.Main, { children: /* @__PURE__ */ jsx2(LocationListContent, {}) }),
    /* @__PURE__ */ jsx2(TwoColumnPage.Sidebar, { children: /* @__PURE__ */ jsx2(LinksSection, {}) })
  ] });
};
var LocationListPage = Object.assign(Root, {
  Main: TwoColumnPage.Main,
  Sidebar: TwoColumnPage.Sidebar,
  Content: LocationListContent,
  LinksSection
});

export {
  LocationListPage
};
