import {
  VisuallyHidden
} from "./chunk-54TMLQH3.js";
import {
  useSalesChannelTableColumns,
  useSalesChannelTableEmptyState,
  useSalesChannelTableFilters,
  useSalesChannelTableQuery
} from "./chunk-CKNQJPAG.js";
import "./chunk-MDABSESI.js";
import "./chunk-54RTJBYO.js";
import {
  DataTable
} from "./chunk-OB4NOV4M.js";
import "./chunk-TKGWSUEI.js";
import {
  KeyboundForm
} from "./chunk-U2ZFCAPX.js";
import "./chunk-BDGZ4EQO.js";
import "./chunk-LAVHRER2.js";
import "./chunk-Y7QKP6QU.js";
import "./chunk-THHRRYRS.js";
import "./chunk-UZWFZMOX.js";
import "./chunk-XQNVC4Q7.js";
import {
  RouteFocusModal,
  useRouteModal
} from "./chunk-FWJLS7XD.js";
import "./chunk-3QSRE5LS.js";
import {
  useStockLocation,
  useUpdateStockLocationSalesChannels
} from "./chunk-EPHVGD5Z.js";
import {
  useSalesChannels
} from "./chunk-DL2ZIXBO.js";
import "./chunk-5CK6XEFV.js";
import "./chunk-RHKRREUU.js";
import "./chunk-ZA2KFUFR.js";
import "./chunk-ZBWL72TB.js";
import "./chunk-NBMM2TZK.js";

// src/pages/locations/location-sales-channels/location-sales-channels.tsx
import { useParams } from "react-router-dom";

// src/pages/locations/location-sales-channels/components/edit-sales-channels-form/edit-sales-channels-form.tsx
import { zodResolver } from "@hookform/resolvers/zod";
import {
  Button,
  Checkbox,
  createDataTableColumnHelper,
  toast
} from "@medusajs/ui";
import { keepPreviousData } from "@tanstack/react-query";
import { useMemo, useState } from "react";
import { useForm } from "react-hook-form";
import { useTranslation } from "react-i18next";
import * as zod from "zod";
import { jsx, jsxs } from "react/jsx-runtime";
var EditSalesChannelsSchema = zod.object({
  sales_channels: zod.array(zod.string()).optional()
});
var PAGE_SIZE = 20;
var PREFIX = "sc";
var LocationEditSalesChannelsForm = ({
  location
}) => {
  const { t } = useTranslation();
  const { handleSuccess } = useRouteModal();
  const form = useForm({
    defaultValues: {
      sales_channels: location.sales_channels?.map((sc) => sc.id) ?? []
    },
    resolver: zodResolver(EditSalesChannelsSchema)
  });
  const { setValue } = form;
  const [rowSelection, setRowSelection] = useState(
    getInitialState(location)
  );
  const onRowSelectionChange = (selection) => {
    const ids = Object.keys(selection);
    setValue("sales_channels", ids, {
      shouldDirty: true,
      shouldTouch: true
    });
    setRowSelection(selection);
  };
  const searchParams = useSalesChannelTableQuery({
    pageSize: PAGE_SIZE,
    prefix: PREFIX
  });
  const { sales_channels, count, isPending, isError, error } = useSalesChannels(
    {
      ...searchParams
    },
    {
      placeholderData: keepPreviousData
    }
  );
  const filters = useSalesChannelTableFilters();
  const columns = useColumns();
  const emptyState = useSalesChannelTableEmptyState();
  const { mutateAsync, isPending: isMutating } = useUpdateStockLocationSalesChannels(location.id);
  const handleSubmit = form.handleSubmit(async (data) => {
    const originalIds = location.sales_channels?.map((sc) => sc.id);
    const arr = data.sales_channels ?? [];
    await mutateAsync(
      {
        add: arr.filter((i) => !originalIds?.includes(i)),
        remove: originalIds?.filter((i) => !arr.includes(i))
      },
      {
        onSuccess: () => {
          toast.success(t("stockLocations.salesChannels.successToast"));
          handleSuccess(`/settings/locations/${location.id}`);
        },
        onError: (e) => {
          toast.error(e.message);
        }
      }
    );
  });
  if (isError) {
    throw error;
  }
  return /* @__PURE__ */ jsx(RouteFocusModal.Form, { form, "data-testid": "location-sales-channels-form", children: /* @__PURE__ */ jsxs(KeyboundForm, { onSubmit: handleSubmit, className: "flex h-full flex-col", children: [
    /* @__PURE__ */ jsxs(RouteFocusModal.Header, { "data-testid": "location-sales-channels-form-header", children: [
      /* @__PURE__ */ jsx(RouteFocusModal.Title, { asChild: true, children: /* @__PURE__ */ jsx(VisuallyHidden, { children: t("stockLocations.salesChannels.header") }) }),
      /* @__PURE__ */ jsx(RouteFocusModal.Description, { asChild: true, children: /* @__PURE__ */ jsx(VisuallyHidden, { children: t("stockLocations.salesChannels.hint") }) })
    ] }),
    /* @__PURE__ */ jsx(RouteFocusModal.Body, { className: "flex flex-1 flex-col overflow-auto", "data-testid": "location-sales-channels-form-body", children: /* @__PURE__ */ jsx(
      DataTable,
      {
        data: sales_channels,
        columns,
        filters,
        emptyState,
        prefix: PREFIX,
        rowSelection: {
          state: rowSelection,
          onRowSelectionChange
        },
        pageSize: PAGE_SIZE,
        isLoading: isPending,
        rowCount: count,
        layout: "fill",
        getRowId: (row) => row.id,
        "data-testid": "location-sales-channels-form-table"
      }
    ) }),
    /* @__PURE__ */ jsx(RouteFocusModal.Footer, { "data-testid": "location-sales-channels-form-footer", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-end gap-x-2", children: [
      /* @__PURE__ */ jsx(RouteFocusModal.Close, { asChild: true, children: /* @__PURE__ */ jsx(Button, { size: "small", variant: "secondary", type: "button", "data-testid": "location-sales-channels-form-cancel-button", children: t("actions.cancel") }) }),
      /* @__PURE__ */ jsx(Button, { size: "small", isLoading: isMutating, type: "submit", "data-testid": "location-sales-channels-form-save-button", children: t("actions.save") })
    ] }) })
  ] }) });
};
var columnHelper = createDataTableColumnHelper();
var useColumns = () => {
  const base = useSalesChannelTableColumns();
  return useMemo(
    () => [
      columnHelper.select({
        header: ({ table }) => {
          return /* @__PURE__ */ jsx("div", { "data-testid": "location-sales-channels-form-table-select-all-header", children: /* @__PURE__ */ jsx(
            Checkbox,
            {
              checked: table.getIsSomePageRowsSelected() ? "indeterminate" : table.getIsAllPageRowsSelected(),
              onCheckedChange: (value) => table.toggleAllPageRowsSelected(!!value),
              "data-testid": "location-sales-channels-form-table-select-all-checkbox"
            }
          ) });
        },
        cell: ({ row }) => {
          return /* @__PURE__ */ jsx("div", { "data-testid": `location-sales-channels-form-table-row-${row.index}-select-cell`, children: /* @__PURE__ */ jsx(
            Checkbox,
            {
              checked: row.getIsSelected(),
              onCheckedChange: (value) => row.toggleSelected(!!value),
              onClick: (e) => {
                e.stopPropagation();
              },
              "data-testid": `location-sales-channels-form-table-row-${row.index}-select-checkbox`
            }
          ) });
        }
      }),
      ...base
    ],
    [base]
  );
};
function getInitialState(location) {
  return location.sales_channels?.reduce((acc, curr) => {
    acc[curr.id] = true;
    return acc;
  }, {}) ?? {};
}

// src/pages/locations/location-sales-channels/location-sales-channels.tsx
import { jsx as jsx2 } from "react/jsx-runtime";
var LocationSalesChannels = () => {
  const { location_id } = useParams();
  const { stock_location, isPending, isError, error } = useStockLocation(
    location_id,
    {
      fields: "id,*sales_channels"
    }
  );
  const ready = !isPending && !!stock_location;
  if (isError) {
    throw error;
  }
  return /* @__PURE__ */ jsx2(RouteFocusModal, { "data-testid": "location-sales-channels-modal", children: ready && /* @__PURE__ */ jsx2(LocationEditSalesChannelsForm, { location: stock_location }) });
};
export {
  LocationSalesChannels as Component
};
