import {
  FulfillmentStatusCell,
  FulfillmentStatusHeader,
  PaymentStatusCell,
  PaymentStatusHeader
} from "./chunk-TZSOL34K.js";
import {
  DateCell,
  DateHeader
} from "./chunk-25LYVP3C.js";
import {
  TextCell,
  TextHeader
} from "./chunk-JHIMVLB2.js";
import {
  getStylizedAmount
} from "./chunk-PXYDR7WQ.js";
import {
  _DataTable,
  useDataTable
} from "./chunk-KYPPQGGE.js";
import {
  SingleColumnPage
} from "./chunk-H6MYB7GB.js";
import {
  useOrderTableQuery
} from "./chunk-3B6MTW5G.js";
import {
  useOrderGroups
} from "./chunk-VYMODH6P.js";
import {
  useSellers
} from "./chunk-LEG67A2R.js";
import {
  useCustomers
} from "./chunk-PRBE5CM3.js";
import {
  useSalesChannels
} from "./chunk-DL2ZIXBO.js";

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

// src/pages/orders/order-list/components/order-list-table/order-list-table.tsx
import { Children as Children2 } from "react";
import { Container } from "@medusajs/ui";

// src/pages/orders/order-list/components/order-list-table/order-list-header.tsx
import { Children } from "react";
import { useTranslation } from "react-i18next";
import { Heading } from "@medusajs/ui";
import { jsx } from "react/jsx-runtime";
var OrderListTitle = () => {
  const { t } = useTranslation();
  return /* @__PURE__ */ jsx(Heading, { "data-testid": "orders-heading", children: t("orders.domain") });
};
var OrderListActions = ({
  children
}) => {
  return /* @__PURE__ */ jsx("div", { className: "flex items-center justify-center gap-x-2", children: Children.count(children) > 0 ? children : null });
};
var OrderListHeader = ({
  children
}) => {
  return /* @__PURE__ */ jsx(
    "div",
    {
      className: "flex items-center justify-between px-6 py-4",
      "data-testid": "orders-header",
      children: Children.count(children) > 0 ? children : /* @__PURE__ */ jsx(OrderListTitle, {})
    }
  );
};

// src/pages/orders/order-list/components/order-list-table/order-list-data-table.tsx
import { IconButton, clx } from "@medusajs/ui";
import { TriangleRightMini } from "@medusajs/icons";
import { keepPreviousData } from "@tanstack/react-query";
import { createColumnHelper } from "@tanstack/react-table";
import { useMemo as useMemo2 } from "react";
import { useTranslation as useTranslation3 } from "react-i18next";

// src/pages/orders/order-list/const.ts
var DEFAULT_PROPERTIES = [
  "id",
  "display_id",
  "customer_id",
  "seller_count",
  "total",
  "created_at",
  "orders.id",
  "orders.status",
  "orders.created_at",
  "orders.email",
  "orders.display_id",
  "orders.custom_display_id",
  "orders.payment_status",
  "orders.fulfillment_status",
  "orders.total",
  "orders.currency_code"
];
var DEFAULT_RELATIONS = [
  "*orders.payment_collections",
  "*orders.customer",
  "*orders.sales_channel",
  "*orders.seller"
];
var DEFAULT_FIELDS = `${DEFAULT_PROPERTIES.join(
  ","
)},${DEFAULT_RELATIONS.join(",")}`;

// src/pages/orders/order-list/components/order-list-table/use-order-table-filters.tsx
import { useMemo } from "react";
import { useTranslation as useTranslation2 } from "react-i18next";
var useOrderGroupTableFilters = () => {
  const { t } = useTranslation2();
  const { customers } = useCustomers({
    limit: 1e3,
    fields: "id,first_name,last_name,email"
  });
  const { sellers } = useSellers({
    limit: 1e3,
    fields: "id,name"
  });
  const { sales_channels } = useSalesChannels({
    limit: 1e3,
    fields: "id,name"
  });
  return useMemo(() => {
    const filters = [];
    if (customers?.length) {
      filters.push({
        key: "customer_id",
        label: t("fields.customer"),
        type: "select",
        multiple: true,
        searchable: true,
        options: customers.map((c) => ({
          label: [c.first_name, c.last_name].filter(Boolean).join(" ") || c.email,
          value: c.id
        }))
      });
    }
    if (sellers?.length) {
      filters.push({
        key: "seller_id",
        label: "Seller",
        type: "select",
        multiple: true,
        searchable: true,
        options: sellers.map((s) => ({
          label: s.name,
          value: s.id
        }))
      });
    }
    if (sales_channels?.length) {
      filters.push({
        key: "sales_channel_id",
        label: t("fields.salesChannel"),
        type: "select",
        multiple: true,
        searchable: true,
        options: sales_channels.map((s) => ({
          label: s.name,
          value: s.id
        }))
      });
    }
    filters.push({
      key: "status",
      label: t("fields.status"),
      type: "select",
      multiple: true,
      options: [
        { label: "Pending", value: "pending" },
        { label: "Completed", value: "completed" },
        { label: "Canceled", value: "canceled" },
        { label: "Requires action", value: "requires_action" }
      ]
    });
    filters.push(
      {
        key: "created_at",
        label: t("fields.createdAt"),
        type: "date"
      },
      {
        key: "updated_at",
        label: t("fields.updatedAt"),
        type: "date"
      }
    );
    return filters;
  }, [customers, sellers, sales_channels, t]);
};

// src/pages/orders/order-list/components/order-list-table/order-list-data-table.tsx
import { jsx as jsx2, jsxs } from "react/jsx-runtime";
var PAGE_SIZE = 20;
function transformOrderGroups(orderGroups, t) {
  return orderGroups.map((group) => {
    const orders = group.orders ?? [];
    const orderIds = orders.map((o) => `#${o.display_id}`).join(", ");
    const firstOrder = orders[0];
    const customerName = firstOrder?.customer ? `${firstOrder.customer.first_name ?? ""} ${firstOrder.customer.last_name ?? ""}`.trim() : "-";
    const currencyCode = firstOrder?.currency_code ?? "usd";
    const children = orders.map((order) => {
      const name = order.customer ? `${order.customer.first_name ?? ""} ${order.customer.last_name ?? ""}`.trim() : "-";
      return {
        _type: "order",
        id: order.id,
        display_id: `#${order.display_id}`,
        order_ids: "",
        vendor: order.seller?.name ?? "-",
        created_at: new Date(order.created_at),
        updated_at: new Date(order.updated_at),
        customer_name: name,
        payment_status: order.payment_status ?? null,
        fulfillment_status: order.fulfillment_status ?? null,
        total: order.total ?? null,
        currency_code: order.currency_code ?? "usd",
        children: []
      };
    });
    return {
      _type: "group",
      id: group.id,
      display_id: `#G${group.display_id}`,
      order_ids: orderIds,
      vendor: t("orders.fields.vendorsCount", { count: group.seller_count }),
      created_at: new Date(group.created_at),
      updated_at: new Date(group.updated_at),
      customer_name: customerName,
      payment_status: null,
      fulfillment_status: null,
      total: group.total ?? null,
      currency_code: currencyCode,
      children
    };
  });
}
var OrderListDataTable = () => {
  const { t } = useTranslation3();
  const { searchParams, raw } = useOrderTableQuery({
    pageSize: PAGE_SIZE
  });
  const { order_groups, count, isError, error, isLoading } = useOrderGroups(
    {
      ...searchParams,
      fields: DEFAULT_FIELDS
    },
    {
      placeholderData: keepPreviousData
    }
  );
  const rows = useMemo2(
    () => transformOrderGroups(order_groups ?? [], t),
    [order_groups, t]
  );
  const filters = useOrderGroupTableFilters();
  const columns = useColumns();
  const { table } = useDataTable({
    data: rows,
    columns,
    enablePagination: true,
    enableExpandableRows: true,
    getSubRows: (row) => row.children,
    getRowId: (row) => row.id,
    count,
    pageSize: PAGE_SIZE
  });
  if (isError) {
    throw error;
  }
  return /* @__PURE__ */ jsx2(
    _DataTable,
    {
      columns,
      table,
      pagination: true,
      navigateTo: (row) => row.original._type === "order" ? `/orders/${row.original.id}` : "",
      count,
      search: true,
      filters,
      isLoading,
      pageSize: PAGE_SIZE,
      orderBy: [
        { key: "display_id", label: t("orders.fields.displayId") },
        { key: "created_at", label: t("fields.createdAt") },
        { key: "updated_at", label: t("fields.updatedAt") }
      ],
      queryObject: raw,
      noRecords: {
        message: t("orders.list.noRecordsMessage")
      }
    }
  );
};
var columnHelper = createColumnHelper();
var useColumns = () => {
  const { t } = useTranslation3();
  return useMemo2(
    () => [
      columnHelper.accessor("display_id", {
        header: () => /* @__PURE__ */ jsx2(TextHeader, { text: t("orders.fields.groupId") }),
        cell: ({ row, getValue }) => {
          if (row.original._type === "order") {
            return null;
          }
          const expandHandler = row.getToggleExpandedHandler();
          return /* @__PURE__ */ jsxs("div", { className: "flex size-full items-center gap-x-2 overflow-hidden", children: [
            /* @__PURE__ */ jsx2("div", { className: "flex size-7 items-center justify-center", children: row.getCanExpand() ? /* @__PURE__ */ jsx2(
              IconButton,
              {
                type: "button",
                onClick: (e) => {
                  e.stopPropagation();
                  e.preventDefault();
                  expandHandler();
                },
                size: "small",
                variant: "transparent",
                className: "text-ui-fg-subtle",
                children: /* @__PURE__ */ jsx2(
                  TriangleRightMini,
                  {
                    className: clx({
                      "rotate-90 transition-transform will-change-transform": row.getIsExpanded()
                    })
                  }
                )
              }
            ) : null }),
            /* @__PURE__ */ jsx2("span", { className: "truncate", children: getValue() })
          ] });
        }
      }),
      columnHelper.accessor("order_ids", {
        header: () => /* @__PURE__ */ jsx2(TextHeader, { text: t("orders.fields.orderIds") }),
        cell: ({ row, getValue }) => {
          if (row.original._type === "group") {
            return /* @__PURE__ */ jsx2(TextCell, { text: getValue() });
          }
          return /* @__PURE__ */ jsx2(TextCell, { text: row.original.display_id });
        }
      }),
      columnHelper.accessor("vendor", {
        header: () => /* @__PURE__ */ jsx2(TextHeader, { text: t("orders.fields.vendor") }),
        cell: ({ getValue }) => /* @__PURE__ */ jsx2(TextCell, { text: getValue() })
      }),
      columnHelper.accessor("created_at", {
        header: () => /* @__PURE__ */ jsx2(DateHeader, {}),
        cell: ({ getValue }) => /* @__PURE__ */ jsx2(DateCell, { date: getValue() })
      }),
      columnHelper.accessor("customer_name", {
        header: () => /* @__PURE__ */ jsx2(TextHeader, { text: t("fields.customer") }),
        cell: ({ getValue }) => /* @__PURE__ */ jsx2(TextCell, { text: getValue() })
      }),
      columnHelper.accessor("payment_status", {
        header: () => /* @__PURE__ */ jsx2(PaymentStatusHeader, {}),
        cell: ({ row, getValue }) => {
          if (row.original._type === "group") {
            return null;
          }
          const status = getValue();
          if (!status) return "-";
          return /* @__PURE__ */ jsx2(PaymentStatusCell, { status });
        }
      }),
      columnHelper.accessor("fulfillment_status", {
        header: () => /* @__PURE__ */ jsx2(FulfillmentStatusHeader, {}),
        cell: ({ row, getValue }) => {
          if (row.original._type === "group") {
            return null;
          }
          const status = getValue();
          if (!status) return "-";
          return /* @__PURE__ */ jsx2(FulfillmentStatusCell, { status });
        }
      }),
      columnHelper.accessor("total", {
        header: () => /* @__PURE__ */ jsx2(TextHeader, { text: t("fields.total") }),
        cell: ({ row, getValue }) => {
          const total = getValue();
          if (total == null) return "-";
          return /* @__PURE__ */ jsx2(
            TextCell,
            {
              text: getStylizedAmount(total, row.original.currency_code)
            }
          );
        }
      })
    ],
    [t]
  );
};

// src/pages/orders/order-list/components/order-list-table/order-list-table.tsx
import { Fragment, jsx as jsx3, jsxs as jsxs2 } from "react/jsx-runtime";
var OrderListTable = ({ children }) => {
  return /* @__PURE__ */ jsx3(Container, { className: "divide-y p-0", "data-testid": "orders-container", children: Children2.count(children) > 0 ? children : /* @__PURE__ */ jsxs2(Fragment, { children: [
    /* @__PURE__ */ jsx3(OrderListHeader, {}),
    /* @__PURE__ */ jsx3(OrderListDataTable, {})
  ] }) });
};

// src/pages/orders/order-list/order-list.tsx
import { jsx as jsx4 } from "react/jsx-runtime";
var Root = ({ children }) => {
  return /* @__PURE__ */ jsx4(SingleColumnPage, { hasOutlet: false, "data-testid": "orders-list-page", children: Children3.count(children) > 0 ? children : /* @__PURE__ */ jsx4(OrderListTable, {}) });
};
var OrderListPage = Object.assign(Root, {
  Table: OrderListTable,
  Header: OrderListHeader,
  HeaderTitle: OrderListTitle,
  HeaderActions: OrderListActions,
  DataTable: OrderListDataTable
});

export {
  OrderListPage
};
