import {
  useCountries,
  useCountryTableColumns,
  useCountryTableQuery
} from "./chunk-TUJIAA5O.js";
import {
  ListSummary
} from "./chunk-4F5GP7J7.js";
import {
  formatProvider
} from "./chunk-VW56KWO2.js";
import {
  SectionRow
} from "./chunk-3XPXUIK3.js";
import {
  _DataTable,
  useDataTable
} from "./chunk-ULJ3OMWU.js";
import {
  SingleColumnPage
} from "./chunk-XIZLPYEE.js";
import {
  currencies
} from "./chunk-IQPN4PZJ.js";
import {
  SingleColumnPageSkeleton
} from "./chunk-INNFZYX2.js";
import {
  ActionMenu
} from "./chunk-BDGZ4EQO.js";
import {
  useDeleteRegion,
  useRegion,
  useUpdateRegion
} from "./chunk-W5UPPL3W.js";
import {
  usePricePreferences
} from "./chunk-7SJC6BWZ.js";

// src/pages/regions/region-detail/region-detail.tsx
import { Children } from "react";
import { useLoaderData, useParams } from "react-router-dom";

// src/pages/regions/region-detail/components/region-country-section/region-country-section.tsx
import { PlusMini, Trash } from "@medusajs/icons";
import { Checkbox, Container, Heading, toast, usePrompt } from "@medusajs/ui";
import {
  createColumnHelper
} from "@tanstack/react-table";
import { useMemo, useState } from "react";
import { useTranslation } from "react-i18next";

// src/pages/regions/region-detail/components/region-country-section/helpers.ts
var convertToStaticCountries = (apiCountries) => {
  if (!apiCountries) {
    return [];
  }
  return apiCountries.filter((c) => {
    const requiredFields = [
      "iso_2",
      "iso_3",
      "num_code",
      "name",
      "display_name"
    ];
    return requiredFields.every((field) => !!c[field]);
  }).map(({ ...country }) => country);
};

// src/pages/regions/region-detail/components/region-country-section/region-country-section.tsx
import { jsx, jsxs } from "react/jsx-runtime";
var PREFIX = "c";
var PAGE_SIZE = 10;
var RegionCountrySection = ({ region }) => {
  const { t } = useTranslation();
  const prompt = usePrompt();
  const [rowSelection, setRowSelection] = useState({});
  const { searchParams, raw } = useCountryTableQuery({
    pageSize: PAGE_SIZE,
    prefix: PREFIX
  });
  const { countries, count } = useCountries({
    countries: convertToStaticCountries(region.countries),
    ...searchParams
  });
  const columns = useColumns();
  const { table } = useDataTable({
    data: countries || [],
    columns,
    count,
    enablePagination: true,
    enableRowSelection: true,
    getRowId: (row) => row.iso_2,
    pageSize: PAGE_SIZE,
    rowSelection: {
      state: rowSelection,
      updater: setRowSelection
    },
    prefix: PREFIX,
    meta: {
      region
    }
  });
  const { mutateAsync } = useUpdateRegion(region.id);
  const handleRemoveCountries = async () => {
    const ids = Object.keys(rowSelection).filter((k) => rowSelection[k]);
    const res = await prompt({
      title: t("general.areYouSure"),
      description: t("regions.removeCountriesWarning", {
        count: ids.length
      }),
      verificationText: t("actions.remove"),
      verificationInstruction: t("general.typeToConfirm"),
      cancelText: t("actions.cancel"),
      confirmText: t("actions.remove")
    });
    if (!res) {
      return;
    }
    const payload = region.countries?.filter((c) => !ids.includes(c.iso_2)).map((c) => c.iso_2);
    await mutateAsync(
      {
        countries: payload
      },
      {
        onSuccess: () => {
          toast.success(t("regions.toast.countries"));
        },
        onError: (e) => {
          toast.error(e.message);
        }
      }
    );
  };
  return /* @__PURE__ */ jsxs(Container, { className: "divide-y p-0", "data-testid": "region-country-section-container", children: [
    /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between px-6 py-4", "data-testid": "region-country-section-header", children: [
      /* @__PURE__ */ jsx(Heading, { level: "h2", "data-testid": "region-country-section-heading", children: t("fields.countries") }),
      /* @__PURE__ */ jsx(
        ActionMenu,
        {
          groups: [
            {
              actions: [
                {
                  label: t("regions.addCountries"),
                  icon: /* @__PURE__ */ jsx(PlusMini, {}),
                  to: "countries/add"
                }
              ]
            }
          ],
          "data-testid": "region-country-section-action-menu"
        }
      )
    ] }),
    /* @__PURE__ */ jsx(
      _DataTable,
      {
        table,
        columns,
        pageSize: PAGE_SIZE,
        count,
        orderBy: [
          { key: "display_name", label: t("fields.name") },
          { key: "iso_2", label: t("fields.code") }
        ],
        search: true,
        pagination: true,
        queryObject: raw,
        prefix: PREFIX,
        commands: [
          {
            action: handleRemoveCountries,
            label: t("actions.remove"),
            shortcut: "r"
          }
        ],
        "data-testid": "region-country-section-table"
      }
    )
  ] });
};
var CountryActions = ({
  country,
  region
}) => {
  const { t } = useTranslation();
  const prompt = usePrompt();
  const { mutateAsync } = useUpdateRegion(region.id);
  const payload = region.countries?.filter((c) => c.iso_2 !== country.iso_2).map((c) => c.iso_2).filter((iso) => iso !== void 0);
  const handleRemove = async () => {
    const res = await prompt({
      title: t("general.areYouSure"),
      description: t("regions.removeCountryWarning", {
        name: country.display_name
      }),
      verificationText: country.display_name,
      verificationInstruction: t("general.typeToConfirm"),
      cancelText: t("actions.cancel"),
      confirmText: t("actions.remove")
    });
    if (!res) {
      return;
    }
    await mutateAsync(
      {
        countries: payload
      },
      {
        onSuccess: () => {
          toast.success(t("regions.toast.countries"));
        },
        onError: (e) => {
          toast.error(e.message);
        }
      }
    );
  };
  return /* @__PURE__ */ jsx(
    ActionMenu,
    {
      groups: [
        {
          actions: [
            {
              label: t("actions.remove"),
              onClick: handleRemove,
              icon: /* @__PURE__ */ jsx(Trash, {})
            }
          ]
        }
      ],
      "data-testid": `region-country-section-action-menu-${country.iso_2}`
    }
  );
};
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-country-section-select-all-checkbox"
            }
          );
        },
        cell: ({ row }) => {
          return /* @__PURE__ */ jsx(
            Checkbox,
            {
              checked: row.getIsSelected(),
              onCheckedChange: (value) => row.toggleSelected(!!value),
              onClick: (e) => {
                e.stopPropagation();
              },
              "data-testid": `region-country-section-select-checkbox-${row.original.iso_2}`
            }
          );
        }
      }),
      ...base,
      columnHelper.display({
        id: "actions",
        cell: ({ row, table }) => {
          const { region } = table.options.meta;
          return /* @__PURE__ */ jsx(CountryActions, { country: row.original, region });
        }
      })
    ],
    [base]
  );
};

// src/pages/regions/region-detail/components/region-general-section/region-general-section.tsx
import { PencilSquare, Trash as Trash2 } from "@medusajs/icons";
import { Badge, Container as Container2, Heading as Heading2, Text, toast as toast2, usePrompt as usePrompt2 } from "@medusajs/ui";
import { useTranslation as useTranslation2 } from "react-i18next";
import { useNavigate } from "react-router-dom";
import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
var RegionGeneralSection = ({
  region,
  pricePreferences
}) => {
  const { t } = useTranslation2();
  const pricePreferenceForRegion = pricePreferences?.find(
    (preference) => preference.attribute === "region_id" && preference.value === region.id
  );
  return /* @__PURE__ */ jsxs2(Container2, { className: "divide-y p-0", "data-testid": "region-general-section-container", children: [
    /* @__PURE__ */ jsxs2("div", { className: "flex items-center justify-between px-6 py-4", "data-testid": "region-general-section-header", children: [
      /* @__PURE__ */ jsx2(Heading2, { "data-testid": "region-general-section-name", children: region.name }),
      /* @__PURE__ */ jsx2(RegionActions, { region })
    ] }),
    /* @__PURE__ */ jsx2(
      SectionRow,
      {
        title: t("fields.currency"),
        value: /* @__PURE__ */ jsxs2("div", { className: "flex items-center gap-x-2", "data-testid": "region-general-section-currency-value", children: [
          /* @__PURE__ */ jsx2(Badge, { size: "2xsmall", className: "uppercase", "data-testid": "region-general-section-currency-badge", children: region.currency_code }),
          /* @__PURE__ */ jsx2(Text, { size: "small", leading: "compact", "data-testid": "region-general-section-currency-name", children: currencies[region.currency_code.toUpperCase()].name })
        ] }),
        "data-testid": "region-general-section-currency"
      }
    ),
    /* @__PURE__ */ jsx2(
      SectionRow,
      {
        title: t("fields.automaticTaxes"),
        value: region.automatic_taxes ? t("fields.true") : t("fields.false"),
        "data-testid": "region-general-section-automatic-taxes"
      }
    ),
    /* @__PURE__ */ jsx2(
      SectionRow,
      {
        title: t("fields.taxInclusivePricing"),
        value: pricePreferenceForRegion?.is_tax_inclusive ? t("fields.true") : t("fields.false"),
        "data-testid": "region-general-section-tax-inclusive-pricing"
      }
    ),
    /* @__PURE__ */ jsx2(
      SectionRow,
      {
        title: t("fields.paymentProviders"),
        value: /* @__PURE__ */ jsx2("div", { className: "inline-flex", "data-testid": "region-general-section-payment-providers-value", children: region.payment_providers?.length ? /* @__PURE__ */ jsx2(
          ListSummary,
          {
            list: region.payment_providers.map((p) => formatProvider(p.id))
          }
        ) : "-" }),
        "data-testid": "region-general-section-payment-providers"
      }
    )
  ] });
};
var RegionActions = ({ region }) => {
  const navigate = useNavigate();
  const { t } = useTranslation2();
  const { mutateAsync } = useDeleteRegion(region.id);
  const prompt = usePrompt2();
  const handleDelete = async () => {
    const res = await prompt({
      title: t("general.areYouSure"),
      description: t("regions.deleteRegionWarning", {
        name: region.name
      }),
      verificationText: region.name,
      verificationInstruction: t("general.typeToConfirm"),
      confirmText: t("actions.delete"),
      cancelText: t("actions.cancel")
    });
    if (!res) {
      return;
    }
    await mutateAsync(void 0, {
      onSuccess: () => {
        toast2.success(t("regions.toast.delete"));
        navigate("/settings/regions", { replace: true });
      },
      onError: (e) => {
        toast2.error(e.message);
      }
    });
  };
  return /* @__PURE__ */ jsx2(
    ActionMenu,
    {
      groups: [
        {
          actions: [
            {
              icon: /* @__PURE__ */ jsx2(PencilSquare, {}),
              label: t("actions.edit"),
              to: `/settings/regions/${region.id}/edit`
            }
          ]
        },
        {
          actions: [
            {
              icon: /* @__PURE__ */ jsx2(Trash2, {}),
              label: t("actions.delete"),
              onClick: handleDelete
            }
          ]
        }
      ],
      "data-testid": "region-general-section-action-menu"
    }
  );
};

// src/pages/regions/region-detail/constants.ts
var REGION_DETAIL_FIELDS = "*payment_providers,*countries,+automatic_taxes";

// src/pages/regions/region-detail/region-detail.tsx
import { jsx as jsx3, jsxs as jsxs3 } from "react/jsx-runtime";
var Root = ({ children }) => {
  const initialData = useLoaderData();
  const { id } = useParams();
  const {
    region,
    isPending: isLoading,
    isError: isRegionError,
    error: regionError
  } = useRegion(
    id,
    { fields: REGION_DETAIL_FIELDS },
    {
      initialData
    }
  );
  const {
    price_preferences: pricePreferences,
    isPending: isLoadingPreferences,
    isError: isPreferencesError,
    error: preferencesError
  } = usePricePreferences(
    {
      attribute: "region_id",
      value: id
    },
    { enabled: !!region }
  );
  if (isLoading || isLoadingPreferences || !region) {
    return /* @__PURE__ */ jsx3(SingleColumnPageSkeleton, { sections: 2, showJSON: true, showMetadata: true });
  }
  if (isRegionError) {
    throw regionError;
  }
  if (isPreferencesError) {
    throw preferencesError;
  }
  return Children.count(children) > 0 ? /* @__PURE__ */ jsx3(SingleColumnPage, { data: region, showMetadata: true, showJSON: true, children }) : /* @__PURE__ */ jsxs3(SingleColumnPage, { data: region, showMetadata: true, showJSON: true, children: [
    /* @__PURE__ */ jsx3(
      RegionGeneralSection,
      {
        region,
        pricePreferences: pricePreferences ?? []
      }
    ),
    /* @__PURE__ */ jsx3(RegionCountrySection, { region })
  ] });
};
var RegionDetailPage = Object.assign(Root, {
  GeneralSection: RegionGeneralSection,
  CountrySection: RegionCountrySection
});

export {
  REGION_DETAIL_FIELDS,
  RegionDetailPage
};
