import {
  formatProvider
} from "./chunk-VW56KWO2.js";
import {
  TextCell,
  TextHeader
} from "./chunk-JHIMVLB2.js";
import "./chunk-PHOCVOZ5.js";
import "./chunk-FQERBIVS.js";
import {
  _DataTable,
  useDataTable
} from "./chunk-ULJ3OMWU.js";
import "./chunk-YBZWO4ZV.js";
import "./chunk-KAZ5BYTQ.js";
import "./chunk-3EF54XFY.js";
import "./chunk-TKGWSUEI.js";
import {
  KeyboundForm
} from "./chunk-U2ZFCAPX.js";
import "./chunk-INNFZYX2.js";
import "./chunk-LAVHRER2.js";
import "./chunk-Y7QKP6QU.js";
import "./chunk-BE5QWX5N.js";
import "./chunk-2ZFELO2L.js";
import "./chunk-RT6L7JXU.js";
import {
  useDateTableFilters
} from "./chunk-26OOAKQ6.js";
import "./chunk-ZQZHFMD7.js";
import "./chunk-6TFS6ET5.js";
import "./chunk-25YTS3TI.js";
import "./chunk-CMHI2RPL.js";
import "./chunk-S2WEYEQR.js";
import "./chunk-WSR2ZXAJ.js";
import "./chunk-KBYZLKI4.js";
import "./chunk-YWWUOGJA.js";
import {
  useQueryParams
} from "./chunk-THHRRYRS.js";
import "./chunk-UZWFZMOX.js";
import "./chunk-XQNVC4Q7.js";
import {
  RouteFocusModal,
  useRouteModal
} from "./chunk-OV7R2AH5.js";
import "./chunk-3QSRE5LS.js";
import "./chunk-3MDRW5MA.js";
import "./chunk-MFL2TZ3W.js";
import "./chunk-YNIIYGL4.js";
import "./chunk-CBHNHLUZ.js";
import "./chunk-VME3CJER.js";
import "./chunk-XMVTX2EN.js";
import "./chunk-5PUHROK4.js";
import "./chunk-TPPONKYW.js";
import "./chunk-DF3OGJAK.js";
import "./chunk-XRDP2SYY.js";
import "./chunk-FNBKEF54.js";
import "./chunk-EHQESDH2.js";
import "./chunk-XKVXLDSJ.js";
import "./chunk-XDZGOUCR.js";
import "./chunk-K4BGK3CO.js";
import "./chunk-YYTI5JIC.js";
import "./chunk-HAFZQK53.js";
import "./chunk-IJWG755C.js";
import "./chunk-M3YP3NX4.js";
import "./chunk-UU2RQMXS.js";
import "./chunk-O4STPJR2.js";
import "./chunk-R74OHYTB.js";
import "./chunk-22XJUSMM.js";
import {
  useFulfillmentProviders,
  useStockLocation,
  useUpdateStockLocationFulfillmentProviders
} from "./chunk-OFKUNYQJ.js";
import "./chunk-W5UPPL3W.js";
import "./chunk-LC6TM5OT.js";
import "./chunk-7SJC6BWZ.js";
import "./chunk-N4JU7GWK.js";
import "./chunk-52BRBQMY.js";
import "./chunk-BA2HXHTW.js";
import "./chunk-RHKRREUU.js";
import "./chunk-ZA2KFUFR.js";
import "./chunk-RIN4CBRB.js";
import "./chunk-NBMM2TZK.js";

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

// src/pages/locations/location-fulfillment-providers/components/edit-fulfillment-providers-form/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 as useTranslation2 } 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 { useTranslation } from "react-i18next";
import { jsx } from "react/jsx-runtime";
var columnHelper = createColumnHelper();
var useFulfillmentProviderTableColumns = () => {
  const { t } = useTranslation();
  return useMemo(
    () => [
      columnHelper.accessor("id", {
        header: () => /* @__PURE__ */ jsx(TextHeader, { text: "Provider" }),
        cell: ({ getValue }) => /* @__PURE__ */ jsx(TextCell, { text: formatProvider(getValue()) })
      })
    ],
    [t]
  );
};

// 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/locations/location-fulfillment-providers/components/edit-fulfillment-providers-form/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 } = useTranslation2();
  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 { searchParams, raw } = useFulfillmentProvidersTableQuery({
    pageSize: PAGE_SIZE
  });
  const { fulfillment_providers, count, isLoading, isError, error } = useFulfillmentProviders(
    { ...searchParams, is_enabled: true },
    { 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);
        }
      }
    );
  });
  if (isError) {
    throw error;
  }
  return /* @__PURE__ */ jsx2(RouteFocusModal.Form, { form, "data-testid": "location-fulfillment-providers-form", children: /* @__PURE__ */ jsxs(KeyboundForm, { onSubmit: handleSubmit, className: "flex size-full flex-col", children: [
    /* @__PURE__ */ jsx2(RouteFocusModal.Header, { "data-testid": "location-fulfillment-providers-form-header" }),
    /* @__PURE__ */ jsx2(RouteFocusModal.Body, { className: "flex flex-1 flex-col overflow-auto", "data-testid": "location-fulfillment-providers-form-body", 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",
        "data-testid": "location-fulfillment-providers-form-table"
      }
    ) }),
    /* @__PURE__ */ jsx2(RouteFocusModal.Footer, { "data-testid": "location-fulfillment-providers-form-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", "data-testid": "location-fulfillment-providers-form-cancel-button", children: t("actions.cancel") }) }),
      /* @__PURE__ */ jsx2(Button, { size: "small", isLoading: isMutating, type: "submit", "data-testid": "location-fulfillment-providers-form-save-button", 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/locations/location-fulfillment-providers/location-fulfillment-providers.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, { "data-testid": "location-fulfillment-providers-modal", children: ready && /* @__PURE__ */ jsx3(LocationEditFulfillmentProvidersForm, { location: stock_location }) });
};
export {
  LocationFulfillmentProviders as Component
};
