import {
  formatProvider
} from "./chunk-VW56KWO2.js";
import {
  currencies
} from "./chunk-IQPN4PZJ.js";
import {
  useComboboxData
} from "./chunk-AEFDAU3Y.js";
import {
  Combobox
} from "./chunk-AW77UWCZ.js";
import {
  KeyboundForm
} from "./chunk-U2ZFCAPX.js";
import {
  useDocumentDirection
} from "./chunk-Y7QKP6QU.js";
import {
  RouteDrawer,
  useRouteModal
} from "./chunk-FWJLS7XD.js";
import {
  Form
} from "./chunk-3QSRE5LS.js";
import {
  useRegion,
  useUpdateRegion
} from "./chunk-ESPLVOFC.js";
import {
  useStore
} from "./chunk-FXWKGNRV.js";
import {
  usePricePreferences
} from "./chunk-VDKOJ5WD.js";
import "./chunk-RHKRREUU.js";
import "./chunk-ZA2KFUFR.js";
import {
  sdk
} from "./chunk-ZBWL72TB.js";
import "./chunk-NBMM2TZK.js";

// src/pages/regions/region-edit/region-edit.tsx
import { Heading } from "@medusajs/ui";
import { useTranslation as useTranslation2 } from "react-i18next";
import { useParams } from "react-router-dom";

// src/pages/regions/region-edit/components/edit-region-form/edit-region-form.tsx
import { Button, Input, Select, Switch, Text, toast } from "@medusajs/ui";
import { useForm } from "react-hook-form";
import { useTranslation } from "react-i18next";
import * as zod from "zod";
import { jsx, jsxs } from "react/jsx-runtime";
var EditRegionSchema = zod.object({
  name: zod.string().min(1),
  currency_code: zod.string(),
  payment_providers: zod.array(zod.string()),
  automatic_taxes: zod.boolean(),
  is_tax_inclusive: zod.boolean()
});
var EditRegionForm = ({
  region,
  currencies: currencies2,
  pricePreferences
}) => {
  const { t } = useTranslation();
  const { handleSuccess } = useRouteModal();
  const pricePreferenceForRegion = pricePreferences?.find(
    (preference) => preference.attribute === "region_id" && preference.value === region.id
  );
  const direction = useDocumentDirection();
  const form = useForm({
    defaultValues: {
      name: region.name,
      currency_code: region.currency_code.toUpperCase(),
      payment_providers: region.payment_providers?.map((pp) => pp.id) || [],
      automatic_taxes: region.automatic_taxes,
      is_tax_inclusive: pricePreferenceForRegion?.is_tax_inclusive || false
    }
  });
  const comboboxProviders = useComboboxData({
    queryKey: ["payment_providers"],
    queryFn: (params) => sdk.admin.payments.paymentProviders.query({
      ...params,
      is_enabled: true,
      id: []
    }),
    getOptions: (data) => data.payment_providers.map((pp) => ({
      label: formatProvider(pp.id),
      value: pp.id
    }))
  });
  const { mutateAsync: updateRegion, isPending: isPendingRegion } = useUpdateRegion(region.id);
  const handleSubmit = form.handleSubmit(async (values) => {
    await updateRegion(
      {
        name: values.name,
        automatic_taxes: values.automatic_taxes,
        currency_code: values.currency_code.toLowerCase(),
        payment_providers: values.payment_providers,
        is_tax_inclusive: values.is_tax_inclusive
      },
      {
        onSuccess: () => {
          toast.success(t("regions.toast.edit"));
          handleSuccess();
        },
        onError: (e) => {
          toast.error(e.message);
        }
      }
    );
  });
  return /* @__PURE__ */ jsx(RouteDrawer.Form, { form, "data-testid": "region-edit-form", children: /* @__PURE__ */ jsxs(
    KeyboundForm,
    {
      onSubmit: handleSubmit,
      className: "flex flex-1 flex-col overflow-hidden",
      children: [
        /* @__PURE__ */ jsx(
          RouteDrawer.Body,
          {
            className: "overflow-y-auto",
            "data-testid": "region-edit-form-body",
            children: /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-y-8", children: [
              /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-y-4", children: [
                /* @__PURE__ */ jsx(
                  Form.Field,
                  {
                    control: form.control,
                    name: "name",
                    render: ({ field }) => {
                      return /* @__PURE__ */ jsxs(Form.Item, { "data-testid": "region-edit-form-name-item", children: [
                        /* @__PURE__ */ jsx(Form.Label, { "data-testid": "region-edit-form-name-label", children: t("fields.name") }),
                        /* @__PURE__ */ jsx(Form.Control, { "data-testid": "region-edit-form-name-control", children: /* @__PURE__ */ jsx(
                          Input,
                          {
                            ...field,
                            "data-testid": "region-edit-form-name-input"
                          }
                        ) }),
                        /* @__PURE__ */ jsx(Form.ErrorMessage, { "data-testid": "region-edit-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-edit-form-currency-item", children: [
                        /* @__PURE__ */ jsx(Form.Label, { "data-testid": "region-edit-form-currency-label", children: t("fields.currency") }),
                        /* @__PURE__ */ jsx(Form.Control, { "data-testid": "region-edit-form-currency-control", children: /* @__PURE__ */ jsxs(
                          Select,
                          {
                            dir: direction,
                            onValueChange: onChange,
                            ...field,
                            "data-testid": "region-edit-form-currency-select",
                            children: [
                              /* @__PURE__ */ jsx(
                                Select.Trigger,
                                {
                                  ref,
                                  "data-testid": "region-edit-form-currency-select-trigger",
                                  children: /* @__PURE__ */ jsx(Select.Value, {})
                                }
                              ),
                              /* @__PURE__ */ jsx(Select.Content, { "data-testid": "region-edit-form-currency-select-content", children: currencies2.map((c) => /* @__PURE__ */ jsx(
                                Select.Item,
                                {
                                  value: c.code,
                                  "data-testid": `region-edit-form-currency-select-option-${c.code}`,
                                  children: c.code.toUpperCase()
                                },
                                c.code
                              )) })
                            ]
                          }
                        ) }),
                        /* @__PURE__ */ jsx(Form.ErrorMessage, { "data-testid": "region-edit-form-currency-error" })
                      ] });
                    }
                  }
                )
              ] }),
              /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-y-4", children: [
                /* @__PURE__ */ jsx(
                  Form.Field,
                  {
                    control: form.control,
                    name: "automatic_taxes",
                    render: ({ field: { value, onChange, ...field } }) => {
                      return /* @__PURE__ */ jsx(Form.Item, { "data-testid": "region-edit-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-edit-form-automatic-taxes-label", children: t("fields.automaticTaxes") }),
                          /* @__PURE__ */ jsx(Form.Control, { "data-testid": "region-edit-form-automatic-taxes-control", children: /* @__PURE__ */ jsx(
                            Switch,
                            {
                              dir: "ltr",
                              className: "rtl:rotate-180",
                              ...field,
                              checked: value,
                              onCheckedChange: onChange,
                              "data-testid": "region-edit-form-automatic-taxes-switch"
                            }
                          ) })
                        ] }),
                        /* @__PURE__ */ jsx(Form.Hint, { "data-testid": "region-edit-form-automatic-taxes-hint", children: t("regions.automaticTaxesHint") }),
                        /* @__PURE__ */ jsx(Form.ErrorMessage, { "data-testid": "region-edit-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-edit-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-edit-form-tax-inclusive-label", children: t("fields.taxInclusivePricing") }),
                          /* @__PURE__ */ jsx(Form.Control, { "data-testid": "region-edit-form-tax-inclusive-control", children: /* @__PURE__ */ jsx(
                            Switch,
                            {
                              dir: "ltr",
                              className: "rtl:rotate-180",
                              ...field,
                              checked: value,
                              onCheckedChange: onChange,
                              "data-testid": "region-edit-form-tax-inclusive-switch"
                            }
                          ) })
                        ] }),
                        /* @__PURE__ */ jsx(Form.Hint, { "data-testid": "region-edit-form-tax-inclusive-hint", children: t("regions.taxInclusiveHint") }),
                        /* @__PURE__ */ jsx(Form.ErrorMessage, { "data-testid": "region-edit-form-tax-inclusive-error" })
                      ] }) });
                    }
                  }
                )
              ] }),
              /* @__PURE__ */ jsxs(
                "div",
                {
                  className: "flex flex-col gap-y-4",
                  "data-testid": "region-edit-form-payment-providers-section",
                  children: [
                    /* @__PURE__ */ jsxs("div", { "data-testid": "region-edit-form-payment-providers-header", children: [
                      /* @__PURE__ */ jsx(
                        Text,
                        {
                          size: "small",
                          leading: "compact",
                          weight: "plus",
                          "data-testid": "region-edit-form-payment-providers-label",
                          children: "Providers"
                        }
                      ),
                      /* @__PURE__ */ jsx(
                        Text,
                        {
                          size: "small",
                          className: "text-ui-fg-subtle",
                          "data-testid": "region-edit-form-payment-providers-hint",
                          children: t("regions.providersHint")
                        }
                      )
                    ] }),
                    /* @__PURE__ */ jsx(
                      Form.Field,
                      {
                        control: form.control,
                        name: "payment_providers",
                        render: ({ field }) => {
                          return /* @__PURE__ */ jsxs(Form.Item, { "data-testid": "region-edit-form-payment-providers-item", children: [
                            /* @__PURE__ */ jsx(Form.Label, { "data-testid": "region-edit-form-payment-providers-item-label", children: t("fields.paymentProviders") }),
                            /* @__PURE__ */ jsx(Form.Control, { "data-testid": "region-edit-form-payment-providers-item-control", children: /* @__PURE__ */ jsx(
                              Combobox,
                              {
                                forceHideInput: true,
                                options: comboboxProviders.options,
                                fetchNextPage: comboboxProviders.fetchNextPage,
                                ...field,
                                "data-testid": "region-edit-form-payment-providers-combobox"
                              }
                            ) }),
                            /* @__PURE__ */ jsx(Form.ErrorMessage, { "data-testid": "region-edit-form-payment-providers-item-error" })
                          ] });
                        }
                      }
                    )
                  ]
                }
              )
            ] })
          }
        ),
        /* @__PURE__ */ jsx(RouteDrawer.Footer, { "data-testid": "region-edit-form-footer", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-x-2", children: [
          /* @__PURE__ */ jsx(RouteDrawer.Close, { asChild: true, children: /* @__PURE__ */ jsx(
            Button,
            {
              size: "small",
              variant: "secondary",
              "data-testid": "region-edit-form-cancel-button",
              children: t("actions.cancel")
            }
          ) }),
          /* @__PURE__ */ jsx(
            Button,
            {
              size: "small",
              type: "submit",
              isLoading: isPendingRegion,
              "data-testid": "region-edit-form-save-button",
              children: t("actions.save")
            }
          )
        ] }) })
      ]
    }
  ) });
};

// src/pages/regions/region-edit/region-edit.tsx
import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
var RegionEdit = () => {
  const { t } = useTranslation2();
  const { id } = useParams();
  const {
    region,
    isPending: isRegionLoading,
    isError: isRegionError,
    error: regionError
  } = useRegion(id, {
    fields: "*payment_providers,*countries,+automatic_taxes"
  });
  const {
    store,
    isPending: isStoreLoading,
    isError: isStoreError,
    error: storeError
  } = useStore();
  const {
    price_preferences: pricePreferences = [],
    isPending: isPreferenceLoading,
    isError: isPreferenceError,
    error: preferenceError
  } = usePricePreferences(
    {
      attribute: "region_id",
      value: id
    },
    { enabled: !!region }
  );
  const isLoading = isRegionLoading || isStoreLoading || isPreferenceLoading;
  const storeCurrencies = (store?.supported_currencies ?? []).map(
    (c) => currencies[c.currency_code.toUpperCase()]
  );
  if (isRegionError) {
    throw regionError;
  }
  if (isStoreError) {
    throw storeError;
  }
  if (isPreferenceError) {
    throw preferenceError;
  }
  return /* @__PURE__ */ jsxs2(RouteDrawer, { "data-testid": "region-edit-drawer", children: [
    /* @__PURE__ */ jsx2(RouteDrawer.Header, { "data-testid": "region-edit-drawer-header", children: /* @__PURE__ */ jsx2(Heading, { "data-testid": "region-edit-drawer-heading", children: t("regions.editRegion") }) }),
    !isLoading && region && /* @__PURE__ */ jsx2(
      EditRegionForm,
      {
        region,
        currencies: storeCurrencies,
        pricePreferences
      }
    )
  ] });
};
export {
  RegionEdit as Component
};
