import {
  TextCell,
  TextHeader
} from "./chunk-JHIMVLB2.js";
import "./chunk-HHD2VUED.js";
import "./chunk-2ZFELO2L.js";
import {
  useDateTableFilters
} from "./chunk-26OOAKQ6.js";
import "./chunk-S2WEYEQR.js";
import "./chunk-5ALC4Z2H.js";
import "./chunk-ZC2ME3UB.js";
import "./chunk-CMHI2RPL.js";
import "./chunk-UAE6XBYL.js";
import {
  formatProvider
} from "./chunk-VW56KWO2.js";
import "./chunk-LFX6R456.js";
import "./chunk-PHOCVOZ5.js";
import "./chunk-TKGWSUEI.js";
import {
  KeyboundForm
} from "./chunk-SITRHMZZ.js";
import {
  RouteFocusModal,
  useRouteModal
} from "./chunk-GDWBOQI5.js";
import "./chunk-3QSRE5LS.js";
import "./chunk-FQERBIVS.js";
import {
  _DataTable,
  useDataTable
} from "./chunk-7TQNE3E2.js";
import "./chunk-YN3FGNJM.js";
import "./chunk-KCHYLLVG.js";
import "./chunk-CVXKASWV.js";
import {
  useQueryParams
} from "./chunk-THHRRYRS.js";
import "./chunk-LRD242C7.js";
import "./chunk-52KJSIHS.js";
import "./chunk-INNFZYX2.js";
import "./chunk-LAVHRER2.js";
import "./chunk-QHQWEERJ.js";
import "./chunk-Y7QKP6QU.js";
import "./chunk-RLRWDHME.js";
import "./chunk-K5324KIX.js";
import "./chunk-FV76G2D7.js";
import "./chunk-GHDLST2P.js";
import "./chunk-YVYYOBAE.js";
import "./chunk-L2NJPDUD.js";
import "./chunk-P7UBW2EI.js";
import "./chunk-MR6REQKT.js";
import "./chunk-EPSDO2MJ.js";
import "./chunk-BHEU34FL.js";
import "./chunk-W34KDYZA.js";
import "./chunk-II3CLUXA.js";
import "./chunk-XKEYHWBS.js";
import "./chunk-J2XUEO2E.js";
import "./chunk-656G74I2.js";
import "./chunk-VWPNMEOE.js";
import {
  useFulfillmentProviders,
  useStockLocation,
  useUpdateStockLocationFulfillmentProviders
} from "./chunk-O72AIZUN.js";
import "./chunk-VUWAOX7H.js";
import "./chunk-5DKUSZQ7.js";
import "./chunk-DIAWPVYS.js";
import "./chunk-4U2BLH45.js";
import "./chunk-YAUGB4LD.js";
import "./chunk-A5DJIOHN.js";
import "./chunk-RHKRREUU.js";
import "./chunk-ZA2KFUFR.js";
import "./chunk-DTGEFKK4.js";
import "./chunk-NBMM2TZK.js";

// src/pages/settings/locations/[location_id]/fulfillment-providers/index.tsx
import { useParams } from "react-router-dom";

// src/pages/settings/locations/[location_id]/fulfillment-providers/_components/edit-fulfillment-providers-form.tsx
import { Button, Checkbox, toast } from "@medusajs/ui";
import { keepPreviousData } from "@tanstack/react-query";
import {
  createColumnHelper as createColumnHelper2
} from "@tanstack/react-table";
import { useMemo as useMemo2, useState } from "react";
import { useTranslation } from "react-i18next";
import * as zod from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";

// src/hooks/table/columns/use-fulfillment-provider-table-columns.tsx
import { createColumnHelper } from "@tanstack/react-table";
import { useMemo } from "react";
import { jsx } from "react/jsx-runtime";
var columnHelper = createColumnHelper();
var useFulfillmentProviderTableColumns = () => {
  return useMemo(
    () => [
      columnHelper.accessor("id", {
        header: () => /* @__PURE__ */ jsx(TextHeader, { text: "Provider" }),
        cell: ({ getValue }) => /* @__PURE__ */ jsx(TextCell, { text: formatProvider(getValue()) })
      })
    ],
    []
  );
};

// src/hooks/table/query/use-fulfillment-providers-table-query.tsx
var useFulfillmentProvidersTableQuery = ({
  prefix,
  pageSize = 20
}) => {
  const queryObject = useQueryParams(
    ["offset", "q", "stock_location_id"],
    prefix
  );
  const { offset, q, stock_location_id } = queryObject;
  const searchParams = {
    limit: pageSize,
    offset: offset ? Number(offset) : 0,
    stock_location_id,
    q
  };
  return {
    searchParams,
    raw: queryObject
  };
};

// src/pages/settings/locations/[location_id]/fulfillment-providers/_components/edit-fulfillment-providers-form.tsx
import { jsx as jsx2, jsxs } from "react/jsx-runtime";
var EditFulfillmentProvidersFormSchema = zod.object({
  fulfillment_providers: zod.array(zod.string()).optional()
});
var PAGE_SIZE = 50;
var LocationEditFulfillmentProvidersForm = ({
  location
}) => {
  const { t } = useTranslation();
  const { handleSuccess } = useRouteModal();
  const form = useForm({
    defaultValues: {
      fulfillment_providers: location.fulfillment_providers?.map((fp) => fp.id) ?? []
    },
    resolver: zodResolver(EditFulfillmentProvidersFormSchema)
  });
  const { setValue } = form;
  const initialState = location.fulfillment_providers?.reduce((acc, curr) => {
    acc[curr.id] = true;
    return acc;
  }, {}) ?? {};
  const [rowSelection, setRowSelection] = useState(initialState);
  const handleRowSelectionChange = (updater) => {
    const ids = typeof updater === "function" ? updater(rowSelection) : updater;
    setValue("fulfillment_providers", Object.keys(ids), {
      shouldDirty: true,
      shouldTouch: true
    });
    setRowSelection(ids);
  };
  const { raw } = useFulfillmentProvidersTableQuery({
    pageSize: PAGE_SIZE
  });
  const { fulfillment_providers, count, isLoading } = useFulfillmentProviders(
    {},
    { placeholderData: keepPreviousData }
  );
  const filters = useDateTableFilters();
  const columns = useColumns();
  const { table } = useDataTable({
    data: fulfillment_providers ?? [],
    columns,
    count,
    enablePagination: true,
    enableRowSelection: true,
    rowSelection: {
      state: rowSelection,
      updater: handleRowSelectionChange
    },
    getRowId: (row) => row.id,
    pageSize: PAGE_SIZE
  });
  const { mutateAsync, isPending: isMutating } = useUpdateStockLocationFulfillmentProviders(location.id);
  const handleSubmit = form.handleSubmit(async (data) => {
    const originalIds = location.fulfillment_providers?.map((sc) => sc.id);
    const arr = data.fulfillment_providers ?? [];
    await mutateAsync(
      {
        add: arr.filter((i) => !originalIds?.includes(i)),
        remove: originalIds?.filter((i) => !arr.includes(i))
      },
      {
        onSuccess: ({ stock_location }) => {
          toast.success(t("stockLocations.fulfillmentProviders.successToast"));
          handleSuccess(`/settings/locations/${stock_location.id}`);
        },
        onError: (e) => {
          toast.error(e.message);
        }
      }
    );
  });
  return /* @__PURE__ */ jsx2(RouteFocusModal.Form, { form, children: /* @__PURE__ */ jsxs(KeyboundForm, { onSubmit: handleSubmit, className: "flex size-full flex-col", children: [
    /* @__PURE__ */ jsx2(RouteFocusModal.Header, {}),
    /* @__PURE__ */ jsx2(RouteFocusModal.Body, { className: "flex flex-1 flex-col overflow-auto", children: /* @__PURE__ */ jsx2(
      _DataTable,
      {
        table,
        columns,
        pageSize: PAGE_SIZE,
        isLoading,
        count,
        filters,
        search: "autofocus",
        pagination: true,
        orderBy: [{ key: "id", label: t("fields.id") }],
        queryObject: raw,
        layout: "fill"
      }
    ) }),
    /* @__PURE__ */ jsx2(RouteFocusModal.Footer, { children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-end gap-x-2", children: [
      /* @__PURE__ */ jsx2(RouteFocusModal.Close, { asChild: true, children: /* @__PURE__ */ jsx2(Button, { size: "small", variant: "secondary", type: "button", children: t("actions.cancel") }) }),
      /* @__PURE__ */ jsx2(Button, { size: "small", isLoading: isMutating, type: "submit", children: t("actions.save") })
    ] }) })
  ] }) });
};
var columnHelper2 = createColumnHelper2();
var useColumns = () => {
  const columns = useFulfillmentProviderTableColumns();
  return useMemo2(
    () => [
      columnHelper2.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();
              }
            }
          );
        }
      }),
      ...columns
    ],
    [columns]
  );
};

// src/pages/settings/locations/[location_id]/fulfillment-providers/index.tsx
import { jsx as jsx3 } from "react/jsx-runtime";
var LocationFulfillmentProviders = () => {
  const { location_id } = useParams();
  const { stock_location, isPending, isError, error } = useStockLocation(
    location_id,
    { fields: "id,*fulfillment_providers" }
  );
  const ready = !isPending && !!stock_location;
  if (isError) {
    throw error;
  }
  return /* @__PURE__ */ jsx3(RouteFocusModal, { children: ready && /* @__PURE__ */ jsx3(LocationEditFulfillmentProvidersForm, { location: stock_location }) });
};
var Component = LocationFulfillmentProviders;
export {
  Component
};
