import {
  useCountries,
  useCountryTableColumns,
  useCountryTableQuery
} from "./chunk-TUJIAA5O.js";
import {
  formatProvider
} from "./chunk-VW56KWO2.js";
import {
  countries
} from "./chunk-JRTZWK77.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 {
  currencies
} from "./chunk-IQPN4PZJ.js";
import {
  useComboboxData
} from "./chunk-AEFDAU3Y.js";
import {
  Combobox
} from "./chunk-AW77UWCZ.js";
import "./chunk-TKGWSUEI.js";
import {
  KeyboundForm
} from "./chunk-U2ZFCAPX.js";
import "./chunk-INNFZYX2.js";
import {
  useDocumentDirection
} from "./chunk-Y7QKP6QU.js";
import "./chunk-KBYZLKI4.js";
import "./chunk-YWWUOGJA.js";
import "./chunk-THHRRYRS.js";
import "./chunk-UZWFZMOX.js";
import "./chunk-XQNVC4Q7.js";
import {
  RouteFocusModal,
  StackedFocusModal,
  useRouteModal,
  useStackedModal
} from "./chunk-OV7R2AH5.js";
import {
  Form
} from "./chunk-3QSRE5LS.js";
import {
  useCreateRegion
} from "./chunk-W5UPPL3W.js";
import {
  useStore
} from "./chunk-LC6TM5OT.js";
import "./chunk-7SJC6BWZ.js";
import "./chunk-RHKRREUU.js";
import "./chunk-ZA2KFUFR.js";
import {
  sdk
} from "./chunk-RIN4CBRB.js";
import "./chunk-NBMM2TZK.js";

// src/pages/regions/region-create/components/create-region-form/create-region-form.tsx
import { zodResolver } from "@hookform/resolvers/zod";
import { XMarkMini } from "@medusajs/icons";
import {
  Button,
  Checkbox,
  Heading,
  Input,
  Select,
  Switch,
  Text,
  clx,
  toast
} from "@medusajs/ui";
import { createColumnHelper } from "@tanstack/react-table";
import { useMemo, useState } from "react";
import { useForm, useWatch } from "react-hook-form";
import { useTranslation } from "react-i18next";
import * as zod from "zod";
import { jsx, jsxs } from "react/jsx-runtime";
var CreateRegionSchema = zod.object({
  name: zod.string().min(1),
  currency_code: zod.string().min(2, "Select a currency"),
  automatic_taxes: zod.boolean(),
  is_tax_inclusive: zod.boolean(),
  countries: zod.array(zod.object({ code: zod.string(), name: zod.string() })),
  payment_providers: zod.array(zod.string()).min(1)
});
var PREFIX = "cr";
var PAGE_SIZE = 50;
var STACKED_MODAL_ID = "countries-modal";
var CreateRegionForm = ({ currencies: currencies2 }) => {
  const { setIsOpen } = useStackedModal();
  const [rowSelection, setRowSelection] = useState({});
  const { handleSuccess } = useRouteModal();
  const direction = useDocumentDirection();
  const form = useForm({
    defaultValues: {
      name: "",
      currency_code: "",
      automatic_taxes: true,
      is_tax_inclusive: false,
      countries: [],
      payment_providers: []
    },
    resolver: zodResolver(CreateRegionSchema)
  });
  const selectedCountries = useWatch({
    control: form.control,
    name: "countries",
    defaultValue: []
  });
  const { t } = useTranslation();
  const { mutateAsync: createRegion, isPending: isPendingRegion } = useCreateRegion();
  const handleSubmit = form.handleSubmit(async (values) => {
    await createRegion(
      {
        name: values.name,
        countries: values.countries.map((c) => c.code),
        currency_code: values.currency_code,
        payment_providers: values.payment_providers,
        automatic_taxes: values.automatic_taxes,
        is_tax_inclusive: values.is_tax_inclusive
      },
      {
        onSuccess: ({ region }) => {
          toast.success(t("regions.toast.create"));
          handleSuccess(`../${region.id}`);
        },
        onError: (e) => {
          toast.error(e.message);
        }
      }
    );
  });
  const { searchParams, raw } = useCountryTableQuery({
    pageSize: PAGE_SIZE,
    prefix: PREFIX
  });
  const { countries: countries2, count } = useCountries({
    countries: countries.map((c, i) => ({
      display_name: c.display_name,
      name: c.name,
      id: i,
      iso_2: c.iso_2,
      iso_3: c.iso_3,
      num_code: c.num_code,
      region_id: null,
      region: {}
    })),
    ...searchParams
  });
  const columns = useColumns();
  const { table } = useDataTable({
    data: countries2 || [],
    columns,
    count,
    enablePagination: true,
    enableRowSelection: true,
    rowSelection: {
      state: rowSelection,
      updater: setRowSelection
    },
    getRowId: (row) => row.iso_2,
    pageSize: PAGE_SIZE,
    prefix: PREFIX
  });
  const saveCountries = () => {
    const selected = Object.keys(rowSelection).filter(
      (key) => rowSelection[key]
    );
    form.setValue(
      "countries",
      selected.map((key) => ({
        code: key,
        name: countries.find((c) => c.iso_2 === key).display_name
      })),
      { shouldDirty: true, shouldTouch: true }
    );
    setIsOpen(STACKED_MODAL_ID, false);
  };
  const removeCountry = (code) => {
    const update = selectedCountries.filter((c) => c.code !== code);
    const ids = update.map((c) => c.code).reduce((acc, c) => {
      acc[c] = true;
      return acc;
    }, {});
    form.setValue("countries", update, {
      shouldDirty: true,
      shouldTouch: true
    });
    setRowSelection(ids);
  };
  const clearCountries = () => {
    form.setValue("countries", [], { shouldDirty: true, shouldTouch: true });
    setRowSelection({});
  };
  const comboboxProviders = useComboboxData({
    queryFn: (params) => sdk.admin.payments.paymentProviders.query({
      ...params,
      is_enabled: true,
      id: []
    }),
    queryKey: ["payment_providers"],
    getOptions: (data) => data.payment_providers.map((pp) => ({
      label: formatProvider(pp.id),
      value: pp.id
    }))
  });
  return /* @__PURE__ */ jsx(RouteFocusModal.Form, { form, "data-testid": "region-create-form", children: /* @__PURE__ */ jsxs(
    KeyboundForm,
    {
      className: "flex h-full flex-col overflow-hidden",
      onSubmit: handleSubmit,
      children: [
        /* @__PURE__ */ jsx(RouteFocusModal.Header, { "data-testid": "region-create-form-header" }),
        /* @__PURE__ */ jsx(
          RouteFocusModal.Body,
          {
            className: "flex overflow-hidden",
            "data-testid": "region-create-form-body",
            children: /* @__PURE__ */ jsx(
              "div",
              {
                className: clx(
                  "flex h-full w-full flex-col items-center overflow-y-auto p-16"
                ),
                id: "form-section",
                children: /* @__PURE__ */ jsxs("div", { className: "flex w-full max-w-[720px] flex-col gap-y-8", children: [
                  /* @__PURE__ */ jsxs("div", { "data-testid": "region-create-form-header-section", children: [
                    /* @__PURE__ */ jsx(Heading, { "data-testid": "region-create-form-heading", children: t("regions.createRegion") }),
                    /* @__PURE__ */ jsx(
                      Text,
                      {
                        size: "small",
                        className: "text-ui-fg-subtle",
                        "data-testid": "region-create-form-hint",
                        children: t("regions.createRegionHint")
                      }
                    )
                  ] }),
                  /* @__PURE__ */ jsx("div", { className: "flex flex-col gap-y-4", children: /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-1 gap-4 md:grid-cols-2", children: [
                    /* @__PURE__ */ jsx(
                      Form.Field,
                      {
                        control: form.control,
                        name: "name",
                        render: ({ field }) => {
                          return /* @__PURE__ */ jsxs(Form.Item, { "data-testid": "region-create-form-name-item", children: [
                            /* @__PURE__ */ jsx(Form.Label, { "data-testid": "region-create-form-name-label", children: t("fields.name") }),
                            /* @__PURE__ */ jsx(Form.Control, { "data-testid": "region-create-form-name-control", children: /* @__PURE__ */ jsx(
                              Input,
                              {
                                ...field,
                                "data-testid": "region-create-form-name-input"
                              }
                            ) }),
                            /* @__PURE__ */ jsx(Form.ErrorMessage, { "data-testid": "region-create-form-name-error" })
                          ] });
                        }
                      }
                    ),
                    /* @__PURE__ */ jsx(
                      Form.Field,
                      {
                        control: form.control,
                        name: "currency_code",
                        render: ({ field: { onChange, ref, ...field } }) => {
                          return /* @__PURE__ */ jsxs(Form.Item, { "data-testid": "region-create-form-currency-item", children: [
                            /* @__PURE__ */ jsx(Form.Label, { "data-testid": "region-create-form-currency-label", children: t("fields.currency") }),
                            /* @__PURE__ */ jsx(Form.Control, { "data-testid": "region-create-form-currency-control", children: /* @__PURE__ */ jsxs(
                              Select,
                              {
                                dir: direction,
                                ...field,
                                onValueChange: onChange,
                                "data-testid": "region-create-form-currency-select",
                                children: [
                                  /* @__PURE__ */ jsx(
                                    Select.Trigger,
                                    {
                                      ref,
                                      "data-testid": "region-create-form-currency-select-trigger",
                                      children: /* @__PURE__ */ jsx(Select.Value, {})
                                    }
                                  ),
                                  /* @__PURE__ */ jsx(Select.Content, { "data-testid": "region-create-form-currency-select-content", children: currencies2.map((currency) => /* @__PURE__ */ jsx(
                                    Select.Item,
                                    {
                                      value: currency.code,
                                      "data-testid": `region-create-form-currency-select-option-${currency.code}`,
                                      children: currency.name
                                    },
                                    currency.code
                                  )) })
                                ]
                              }
                            ) }),
                            /* @__PURE__ */ jsx(Form.ErrorMessage, { "data-testid": "region-create-form-currency-error" })
                          ] });
                        }
                      }
                    )
                  ] }) }),
                  /* @__PURE__ */ jsx(
                    Form.Field,
                    {
                      control: form.control,
                      name: "automatic_taxes",
                      render: ({ field: { value, onChange, ...field } }) => {
                        return /* @__PURE__ */ jsx(Form.Item, { "data-testid": "region-create-form-automatic-taxes-item", children: /* @__PURE__ */ jsxs("div", { children: [
                          /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between", children: [
                            /* @__PURE__ */ jsx(Form.Label, { "data-testid": "region-create-form-automatic-taxes-label", children: t("fields.automaticTaxes") }),
                            /* @__PURE__ */ jsx(Form.Control, { "data-testid": "region-create-form-automatic-taxes-control", children: /* @__PURE__ */ jsx(
                              Switch,
                              {
                                dir: "ltr",
                                className: "rtl:rotate-180",
                                ...field,
                                checked: value,
                                onCheckedChange: onChange,
                                "data-testid": "region-create-form-automatic-taxes-switch"
                              }
                            ) })
                          ] }),
                          /* @__PURE__ */ jsx(Form.Hint, { "data-testid": "region-create-form-automatic-taxes-hint", children: t("regions.automaticTaxesHint") }),
                          /* @__PURE__ */ jsx(Form.ErrorMessage, { "data-testid": "region-create-form-automatic-taxes-error" })
                        ] }) });
                      }
                    }
                  ),
                  /* @__PURE__ */ jsx(
                    Form.Field,
                    {
                      control: form.control,
                      name: "is_tax_inclusive",
                      render: ({ field: { value, onChange, ...field } }) => {
                        return /* @__PURE__ */ jsx(Form.Item, { "data-testid": "region-create-form-tax-inclusive-item", children: /* @__PURE__ */ jsxs("div", { children: [
                          /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between", children: [
                            /* @__PURE__ */ jsx(Form.Label, { "data-testid": "region-create-form-tax-inclusive-label", children: t("fields.taxInclusivePricing") }),
                            /* @__PURE__ */ jsx(Form.Control, { "data-testid": "region-create-form-tax-inclusive-control", children: /* @__PURE__ */ jsx(
                              Switch,
                              {
                                className: "rtl:rotate-180",
                                dir: "ltr",
                                ...field,
                                checked: value,
                                onCheckedChange: onChange,
                                "data-testid": "region-create-form-tax-inclusive-switch"
                              }
                            ) })
                          ] }),
                          /* @__PURE__ */ jsx(Form.Hint, { "data-testid": "region-create-form-tax-inclusive-hint", children: t("regions.taxInclusiveHint") }),
                          /* @__PURE__ */ jsx(Form.ErrorMessage, { "data-testid": "region-create-form-tax-inclusive-error" })
                        ] }) });
                      }
                    }
                  ),
                  /* @__PURE__ */ jsx("div", { className: "bg-ui-border-base h-px w-full" }),
                  /* @__PURE__ */ jsxs(
                    "div",
                    {
                      className: "flex flex-col gap-y-4",
                      "data-testid": "region-create-form-countries-section",
                      children: [
                        /* @__PURE__ */ jsxs("div", { "data-testid": "region-create-form-countries-header", children: [
                          /* @__PURE__ */ jsx(
                            Text,
                            {
                              size: "small",
                              leading: "compact",
                              weight: "plus",
                              "data-testid": "region-create-form-countries-label",
                              children: t("fields.countries")
                            }
                          ),
                          /* @__PURE__ */ jsx(
                            Text,
                            {
                              size: "small",
                              className: "text-ui-fg-subtle",
                              "data-testid": "region-create-form-countries-hint",
                              children: t("regions.countriesHint")
                            }
                          )
                        ] }),
                        selectedCountries.length > 0 && /* @__PURE__ */ jsxs(
                          "div",
                          {
                            className: "flex flex-wrap gap-2",
                            "data-testid": "region-create-form-countries-selected",
                            children: [
                              selectedCountries.map((country) => /* @__PURE__ */ jsx(
                                CountryTag,
                                {
                                  country,
                                  onRemove: removeCountry
                                },
                                country.code
                              )),
                              /* @__PURE__ */ jsx(
                                Button,
                                {
                                  variant: "transparent",
                                  size: "small",
                                  className: "text-ui-fg-muted hover:text-ui-fg-subtle",
                                  onClick: clearCountries,
                                  "data-testid": "region-create-form-countries-clear-all-button",
                                  children: t("actions.clearAll")
                                }
                              )
                            ]
                          }
                        ),
                        /* @__PURE__ */ jsxs(
                          StackedFocusModal,
                          {
                            id: STACKED_MODAL_ID,
                            "data-testid": "region-create-form-countries-modal",
                            children: [
                              /* @__PURE__ */ jsx("div", { className: "flex items-center justify-end", children: /* @__PURE__ */ jsx(StackedFocusModal.Trigger, { asChild: true, children: /* @__PURE__ */ jsx(
                                Button,
                                {
                                  variant: "secondary",
                                  size: "small",
                                  "data-testid": "region-create-form-countries-add-button",
                                  children: t("regions.addCountries")
                                }
                              ) }) }),
                              /* @__PURE__ */ jsx(StackedFocusModal.Content, { "data-testid": "region-create-form-countries-modal-content", children: /* @__PURE__ */ jsxs("div", { className: "flex size-full flex-col overflow-hidden", children: [
                                /* @__PURE__ */ jsx(StackedFocusModal.Header, { "data-testid": "region-create-form-countries-modal-header", children: /* @__PURE__ */ jsx(StackedFocusModal.Title, { asChild: true, children: /* @__PURE__ */ jsx("span", { className: "sr-only", children: t("regions.addCountries") }) }) }),
                                /* @__PURE__ */ jsx(
                                  StackedFocusModal.Body,
                                  {
                                    className: "overflow-hidden",
                                    "data-testid": "region-create-form-countries-modal-body",
                                    children: /* @__PURE__ */ jsx(
                                      _DataTable,
                                      {
                                        table,
                                        columns,
                                        count,
                                        pageSize: PAGE_SIZE,
                                        orderBy: [
                                          { key: "display_name", label: t("fields.name") },
                                          { key: "iso_2", label: t("fields.code") }
                                        ],
                                        pagination: true,
                                        search: "autofocus",
                                        layout: "fill",
                                        queryObject: raw,
                                        prefix: PREFIX,
                                        "data-testid": "region-create-form-countries-modal-table"
                                      }
                                    )
                                  }
                                ),
                                /* @__PURE__ */ jsx(StackedFocusModal.Footer, { "data-testid": "region-create-form-countries-modal-footer", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-end gap-x-2", children: [
                                  /* @__PURE__ */ jsx(StackedFocusModal.Close, { asChild: true, children: /* @__PURE__ */ jsx(
                                    Button,
                                    {
                                      variant: "secondary",
                                      size: "small",
                                      "data-testid": "region-create-form-countries-modal-cancel-button",
                                      children: t("actions.cancel")
                                    }
                                  ) }),
                                  /* @__PURE__ */ jsx(
                                    Button,
                                    {
                                      size: "small",
                                      type: "button",
                                      onClick: saveCountries,
                                      "data-testid": "region-create-form-countries-modal-save-button",
                                      children: t("actions.save")
                                    }
                                  )
                                ] }) })
                              ] }) })
                            ]
                          }
                        )
                      ]
                    }
                  ),
                  /* @__PURE__ */ jsx("div", { className: "bg-ui-border-base h-px w-full" }),
                  /* @__PURE__ */ jsxs(
                    "div",
                    {
                      className: "flex flex-col gap-y-4",
                      "data-testid": "region-create-form-payment-providers-section",
                      children: [
                        /* @__PURE__ */ jsxs("div", { "data-testid": "region-create-form-payment-providers-header", children: [
                          /* @__PURE__ */ jsx(
                            Text,
                            {
                              size: "small",
                              leading: "compact",
                              weight: "plus",
                              "data-testid": "region-create-form-payment-providers-label",
                              children: t("fields.providers")
                            }
                          ),
                          /* @__PURE__ */ jsx(
                            Text,
                            {
                              size: "small",
                              className: "text-ui-fg-subtle",
                              "data-testid": "region-create-form-payment-providers-hint",
                              children: t("regions.providersHint")
                            }
                          )
                        ] }),
                        /* @__PURE__ */ jsx("div", { className: "grid grid-cols-1 gap-4 md:grid-cols-2", children: /* @__PURE__ */ jsx(
                          Form.Field,
                          {
                            control: form.control,
                            name: "payment_providers",
                            render: ({ field }) => {
                              return /* @__PURE__ */ jsxs(Form.Item, { "data-testid": "region-create-form-payment-providers-item", children: [
                                /* @__PURE__ */ jsx(Form.Label, { "data-testid": "region-create-form-payment-providers-item-label", children: t("fields.paymentProviders") }),
                                /* @__PURE__ */ jsx(Form.Control, { "data-testid": "region-create-form-payment-providers-item-control", children: /* @__PURE__ */ jsx(
                                  Combobox,
                                  {
                                    forceHideInput: true,
                                    options: comboboxProviders.options,
                                    fetchNextPage: comboboxProviders.fetchNextPage,
                                    ...field,
                                    "data-testid": "region-create-form-payment-providers-combobox"
                                  }
                                ) }),
                                /* @__PURE__ */ jsx(Form.ErrorMessage, { "data-testid": "region-create-form-payment-providers-item-error" })
                              ] });
                            }
                          }
                        ) })
                      ]
                    }
                  )
                ] })
              }
            )
          }
        ),
        /* @__PURE__ */ jsxs(RouteFocusModal.Footer, { "data-testid": "region-create-form-footer", children: [
          /* @__PURE__ */ jsx(RouteFocusModal.Close, { asChild: true, children: /* @__PURE__ */ jsx(
            Button,
            {
              size: "small",
              variant: "secondary",
              "data-testid": "region-create-form-cancel-button",
              children: t("actions.cancel")
            }
          ) }),
          /* @__PURE__ */ jsx(
            Button,
            {
              size: "small",
              type: "submit",
              isLoading: isPendingRegion,
              "data-testid": "region-create-form-save-button",
              children: t("actions.save")
            }
          )
        ] })
      ]
    }
  ) });
};
var columnHelper = createColumnHelper();
var useColumns = () => {
  const base = useCountryTableColumns();
  return useMemo(
    () => [
      columnHelper.display({
        id: "select",
        header: ({ table }) => {
          return /* @__PURE__ */ jsx(
            Checkbox,
            {
              checked: table.getIsSomePageRowsSelected() ? "indeterminate" : table.getIsAllPageRowsSelected(),
              onCheckedChange: (value) => table.toggleAllPageRowsSelected(!!value),
              "data-testid": "region-create-form-countries-modal-select-all-checkbox"
            }
          );
        },
        cell: ({ row }) => {
          const isPreselected = !row.getCanSelect();
          return /* @__PURE__ */ jsx(
            Checkbox,
            {
              checked: row.getIsSelected() || isPreselected,
              disabled: isPreselected,
              onCheckedChange: (value) => row.toggleSelected(!!value),
              onClick: (e) => {
                e.stopPropagation();
              },
              "data-testid": `region-create-form-countries-modal-select-checkbox-${row.original.iso_2}`
            }
          );
        }
      }),
      ...base
    ],
    [base]
  );
};
var CountryTag = ({
  country,
  onRemove
}) => {
  return /* @__PURE__ */ jsxs(
    "div",
    {
      className: "bg-ui-bg-field shadow-borders-base transition-fg hover:bg-ui-bg-field-hover flex h-7 items-center overflow-hidden rounded-md",
      "data-testid": `region-create-form-country-tag-${country.code}`,
      children: [
        /* @__PURE__ */ jsx(
          "div",
          {
            className: "txt-compact-small-plus flex h-full select-none items-center justify-center px-2 py-0.5",
            "data-testid": `region-create-form-country-tag-${country.code}-name`,
            children: country.name
          }
        ),
        /* @__PURE__ */ jsx(
          "button",
          {
            type: "button",
            onClick: () => onRemove(country.code),
            className: "focus-visible:bg-ui-bg-field-hover transition-fg hover:bg-ui-bg-field-hover flex h-full w-7 items-center justify-center border-l outline-none",
            "data-testid": `region-create-form-country-tag-${country.code}-remove-button`,
            children: /* @__PURE__ */ jsx(XMarkMini, { className: "text-ui-fg-muted" })
          }
        )
      ]
    }
  );
};

// src/pages/regions/region-create/region-create.tsx
import { jsx as jsx2 } from "react/jsx-runtime";
var RegionCreate = () => {
  const { store, isPending: isLoading, isError, error } = useStore();
  const storeCurrencies = (store?.supported_currencies ?? []).map(
    (c) => currencies[c.currency_code.toUpperCase()]
  );
  if (isError) {
    throw error;
  }
  return /* @__PURE__ */ jsx2(RouteFocusModal, { "data-testid": "region-create-modal", children: !isLoading && store && /* @__PURE__ */ jsx2(CreateRegionForm, { currencies: storeCurrencies }) });
};
export {
  RegionCreate as Component
};
