import {
  GEO_ZONE_STACKED_MODAL_ID
} from "./chunk-BCU3FKP2.js";
import {
  countries
} from "./chunk-JRTZWK77.js";
import {
  StackedFocusModal,
  useStackedModal
} from "./chunk-GDWBOQI5.js";
import {
  Form
} from "./chunk-3QSRE5LS.js";
import {
  _DataTable,
  useDataTable
} from "./chunk-7TQNE3E2.js";
import {
  useQueryParams
} from "./chunk-THHRRYRS.js";

// src/pages/settings/locations/_common/components/geo-zone-form/geo-zone-form.tsx
import { Button as Button2, Checkbox } from "@medusajs/ui";
import {
  createColumnHelper as createColumnHelper2
} from "@tanstack/react-table";
import { useEffect, useMemo as useMemo2, useState } from "react";
import { useFieldArray } from "react-hook-form";
import { useTranslation as useTranslation3 } from "react-i18next";
import { z } from "zod";

// src/components/common/chip-group/chip-group.tsx
import { XMarkMini } from "@medusajs/icons";
import { Button, clx } from "@medusajs/ui";
import { Children, createContext, useContext } from "react";
import { useTranslation } from "react-i18next";
import { jsx, jsxs } from "react/jsx-runtime";
var GroupContext = createContext(null);
var useGroupContext = () => {
  const context = useContext(GroupContext);
  if (!context) {
    throw new Error("useGroupContext must be used within a ChipGroup component");
  }
  return context;
};
var Group = ({
  onClearAll,
  onRemove,
  variant = "component",
  className,
  children
}) => {
  const { t } = useTranslation();
  const showClearAll = !!onClearAll && Children.count(children) > 0;
  return /* @__PURE__ */ jsx(GroupContext.Provider, { value: { onRemove, variant }, children: /* @__PURE__ */ jsxs(
    "ul",
    {
      role: "application",
      className: clx("flex flex-wrap items-center gap-2", className),
      children: [
        children,
        showClearAll && /* @__PURE__ */ jsx("li", { children: /* @__PURE__ */ jsx(
          Button,
          {
            size: "small",
            variant: "transparent",
            type: "button",
            onClick: onClearAll,
            className: "text-ui-fg-muted active:text-ui-fg-subtle",
            children: t("actions.clearAll")
          }
        ) })
      ]
    }
  ) });
};
var Chip = ({ index, className, children }) => {
  const { onRemove, variant } = useGroupContext();
  return /* @__PURE__ */ jsxs(
    "li",
    {
      className: clx(
        "bg-ui-bg-component shadow-borders-base flex items-stretch divide-x overflow-hidden rounded-md",
        {
          "bg-ui-bg-component": variant === "component",
          "bg-ui-bg-base-": variant === "base"
        },
        className
      ),
      children: [
        /* @__PURE__ */ jsx("span", { className: "txt-compact-small-plus text-ui-fg-subtle flex items-center justify-center px-2 py-1", children }),
        !!onRemove && /* @__PURE__ */ jsx(
          "button",
          {
            onClick: () => onRemove(index),
            type: "button",
            className: clx(
              "text-ui-fg-muted active:text-ui-fg-subtle transition-fg flex items-center justify-center p-1",
              {
                "hover:bg-ui-bg-component-hover active:bg-ui-bg-component-pressed": variant === "component",
                "hover:bg-ui-bg-base-hover active:bg-ui-bg-base-pressed": variant === "base"
              }
            ),
            children: /* @__PURE__ */ jsx(XMarkMini, {})
          }
        )
      ]
    }
  );
};
var ChipGroup = Object.assign(Group, { Chip });

// src/pages/settings/regions/_common/hooks/use-countries.tsx
var acceptedOrderKeys = ["name", "code"];
var useCountries = ({
  countries: countries2,
  q,
  order = "name",
  limit,
  offset = 0
}) => {
  const data = countries2.slice(offset, offset + limit);
  if (order) {
    const direction = order.startsWith("-") ? -1 : 1;
    const key = order.replace("-", "");
    if (!acceptedOrderKeys.includes(key)) {
      console.log("The key ${key} is not a valid order key");
      throw new Response(
        JSON.stringify(`The key ${key} is not a valid order key`),
        { status: 500, headers: { "Content-Type": "application/json" } }
      );
    }
    const sortKey = key === "code" ? "iso_2" : "name";
    data.sort((a, b) => {
      if (a[sortKey] === null && b[sortKey] === null) {
        return 0;
      }
      if (a[sortKey] === null) {
        return direction;
      }
      if (b[sortKey] === null) {
        return -direction;
      }
      return a[sortKey] > b[sortKey] ? direction : -direction;
    });
  }
  if (q) {
    const query = q.toLowerCase();
    const results = countries2.filter(
      (c) => c.name.toLowerCase().includes(query) || c.iso_2.toLowerCase().includes(query)
    );
    return {
      countries: results,
      count: results.length
    };
  }
  return {
    countries: data,
    count: countries2.length
  };
};

// src/pages/settings/regions/_common/hooks/use-country-table-columns.tsx
import { createColumnHelper } from "@tanstack/react-table";
import { useMemo } from "react";
import { useTranslation as useTranslation2 } from "react-i18next";
import { jsx as jsx2 } from "react/jsx-runtime";
var columnHelper = createColumnHelper();
var useCountryTableColumns = () => {
  const { t } = useTranslation2();
  return useMemo(
    () => [
      columnHelper.accessor("display_name", {
        header: t("fields.name"),
        cell: ({ getValue }) => getValue()
      }),
      columnHelper.accessor("iso_2", {
        header: t("fields.code"),
        cell: ({ getValue }) => /* @__PURE__ */ jsx2("span", { className: "uppercase", children: getValue() })
      })
    ],
    [t]
  );
};

// src/pages/settings/regions/_common/hooks/use-country-table-query.tsx
var useCountryTableQuery = ({
  pageSize,
  prefix
}) => {
  const raw = useQueryParams(["order", "q", "offset"], prefix);
  const { offset, order, q } = raw;
  const searchParams = {
    limit: pageSize,
    offset: offset ? parseInt(offset, 10) : 0,
    order,
    q
  };
  return {
    searchParams,
    raw
  };
};

// src/pages/settings/locations/_common/components/geo-zone-form/geo-zone-form.tsx
import { jsx as jsx3, jsxs as jsxs2 } from "react/jsx-runtime";
var GeoZoneSchema = z.object({
  countries: z.array(
    z.object({ iso_2: z.string().min(2), display_name: z.string() })
  )
});
var GeoZoneFormImpl = ({
  form
}) => {
  const castForm = form;
  const { t } = useTranslation3();
  const { fields, remove, replace } = useFieldArray({
    control: castForm.control,
    name: "countries",
    keyName: "iso_2"
  });
  const handleClearAll = () => {
    replace([]);
  };
  validateForm(form);
  return /* @__PURE__ */ jsx3(
    Form.Field,
    {
      control: form.control,
      name: "countries",
      render: () => {
        return /* @__PURE__ */ jsxs2(Form.Item, { children: [
          /* @__PURE__ */ jsxs2("div", { className: "flex items-center justify-between gap-x-4", children: [
            /* @__PURE__ */ jsxs2("div", { children: [
              /* @__PURE__ */ jsx3(Form.Label, { children: t("stockLocations.serviceZones.manageAreas.label") }),
              /* @__PURE__ */ jsx3(Form.Hint, { children: t("stockLocations.serviceZones.manageAreas.hint") })
            ] }),
            /* @__PURE__ */ jsx3(StackedFocusModal.Trigger, { asChild: true, children: /* @__PURE__ */ jsx3(Button2, { size: "small", variant: "secondary", type: "button", children: t("stockLocations.serviceZones.manageAreas.action") }) })
          ] }),
          /* @__PURE__ */ jsx3(Form.ErrorMessage, {}),
          /* @__PURE__ */ jsx3(Form.Control, { className: "mt-0", children: fields.length > 0 && /* @__PURE__ */ jsx3(
            ChipGroup,
            {
              onClearAll: handleClearAll,
              onRemove: remove,
              className: "py-4",
              children: fields.map((field, index) => /* @__PURE__ */ jsx3(ChipGroup.Chip, { index, children: field.display_name }, field.iso_2))
            }
          ) })
        ] });
      }
    }
  );
};
var PREFIX = "ac";
var PAGE_SIZE = 50;
var AreaStackedModal = ({
  form
}) => {
  const castForm = form;
  const { t } = useTranslation3();
  const { getValues, setValue } = castForm;
  const { setIsOpen, getIsOpen } = useStackedModal();
  const open = getIsOpen(GEO_ZONE_STACKED_MODAL_ID);
  const [selection, setSelection] = useState({});
  const [state, setState] = useState(
    []
  );
  const { searchParams, raw } = useCountryTableQuery({
    pageSize: PAGE_SIZE,
    prefix: PREFIX
  });
  const { countries: countries2, count } = useCountries({
    countries: countries.map((c) => ({
      display_name: c.display_name,
      name: c.name,
      iso_2: c.iso_2,
      iso_3: c.iso_3,
      num_code: c.num_code
    })),
    ...searchParams
  });
  useEffect(() => {
    if (!open) {
      return;
    }
    const countries3 = getValues("countries");
    if (countries3) {
      setState(
        countries3.map((country) => ({
          iso_2: country.iso_2,
          display_name: country.display_name
        }))
      );
      setSelection(
        countries3.reduce(
          (acc, country) => ({
            ...acc,
            [country.iso_2]: true
          }),
          {}
        )
      );
    }
  }, [open, getValues]);
  const updater = (fn) => {
    const value = typeof fn === "function" ? fn(selection) : fn;
    const ids = Object.keys(value);
    const addedIdsSet = new Set(ids.filter((id) => value[id] && !selection[id]));
    const addedCountries = [];
    if (addedIdsSet.size > 0) {
      const countriesToAdd = countries2?.filter((country) => addedIdsSet.has(country.iso_2)) ?? [];
      for (const country of countriesToAdd) {
        addedCountries.push({
          iso_2: country.iso_2,
          display_name: country.display_name
        });
      }
    }
    setState((prev) => {
      const filteredPrev = prev.filter((country) => value[country.iso_2]);
      return Array.from(/* @__PURE__ */ new Set([...filteredPrev, ...addedCountries]));
    });
    setSelection(value);
  };
  const handleAdd = () => {
    setValue("countries", state, {
      shouldDirty: true,
      shouldTouch: true
    });
    setIsOpen(GEO_ZONE_STACKED_MODAL_ID, false);
  };
  const columns = useColumns();
  const { table } = useDataTable({
    data: countries2 || [],
    columns,
    count,
    enablePagination: true,
    enableRowSelection: true,
    getRowId: (row) => row.iso_2,
    pageSize: PAGE_SIZE,
    rowSelection: {
      state: selection,
      updater
    },
    prefix: PREFIX
  });
  validateForm(form);
  return /* @__PURE__ */ jsxs2(StackedFocusModal.Content, { className: "flex flex-col overflow-hidden", children: [
    /* @__PURE__ */ jsxs2(StackedFocusModal.Header, { children: [
      /* @__PURE__ */ jsx3(StackedFocusModal.Title, { asChild: true, children: /* @__PURE__ */ jsx3("span", { className: "sr-only", children: t("stockLocations.serviceZones.manageAreas.label") }) }),
      /* @__PURE__ */ jsx3(StackedFocusModal.Description, { asChild: true, children: /* @__PURE__ */ jsx3("span", { className: "sr-only", children: t("stockLocations.serviceZones.manageAreas.hint") }) })
    ] }),
    /* @__PURE__ */ jsx3(StackedFocusModal.Body, { className: "flex-1 overflow-hidden", children: /* @__PURE__ */ jsx3(
      _DataTable,
      {
        table,
        columns,
        pageSize: PAGE_SIZE,
        count,
        search: true,
        pagination: true,
        layout: "fill",
        orderBy: [
          { key: "display_name", label: t("fields.name") },
          { key: "iso_2", label: t("fields.code") }
        ],
        queryObject: raw,
        prefix: PREFIX
      }
    ) }),
    /* @__PURE__ */ jsx3(StackedFocusModal.Footer, { children: /* @__PURE__ */ jsxs2("div", { className: "flex items-center justify-end gap-x-2", children: [
      /* @__PURE__ */ jsx3(StackedFocusModal.Close, { type: "button", asChild: true, children: /* @__PURE__ */ jsx3(Button2, { variant: "secondary", size: "small", children: t("actions.cancel") }) }),
      /* @__PURE__ */ jsx3(Button2, { size: "small", type: "button", onClick: handleAdd, children: t("actions.save") })
    ] }) })
  ] });
};
var columnHelper2 = createColumnHelper2();
var useColumns = () => {
  const base = useCountryTableColumns();
  return useMemo2(
    () => [
      columnHelper2.display({
        id: "select",
        header: ({ table }) => {
          return /* @__PURE__ */ jsx3(
            Checkbox,
            {
              checked: table.getIsSomePageRowsSelected() ? "indeterminate" : table.getIsAllPageRowsSelected(),
              onCheckedChange: (value) => table.toggleAllPageRowsSelected(!!value)
            }
          );
        },
        cell: ({ row }) => {
          const isPreselected = !row.getCanSelect();
          return /* @__PURE__ */ jsx3(
            Checkbox,
            {
              checked: row.getIsSelected() || isPreselected,
              disabled: isPreselected,
              onCheckedChange: (value) => row.toggleSelected(!!value),
              onClick: (e) => {
                e.stopPropagation();
              }
            }
          );
        }
      }),
      ...base
    ],
    [base]
  );
};
function validateForm(form) {
  if (form.getValues("countries") === void 0) {
    throw new Error(
      "The form does not have a field named 'countries'. This field is required to use the GeoZoneForm component."
    );
  }
}
var GeoZoneForm = Object.assign(GeoZoneFormImpl, {
  AreaDrawer: AreaStackedModal
});

export {
  GeoZoneForm
};
