import {
  useCountries,
  useCountryTableColumns,
  useCountryTableQuery
} from "./chunk-TUJIAA5O.js";
import {
  countries
} from "./chunk-JRTZWK77.js";
import "./chunk-FQERBIVS.js";
import {
  _DataTable,
  useDataTable
} from "./chunk-KYPPQGGE.js";
import "./chunk-ZMC7BKLT.js";
import "./chunk-KAZ5BYTQ.js";
import "./chunk-634XVU3D.js";
import "./chunk-TKGWSUEI.js";
import {
  KeyboundForm
} from "./chunk-U2ZFCAPX.js";
import "./chunk-INNFZYX2.js";
import "./chunk-Y7QKP6QU.js";
import "./chunk-HKDFWQ6Q.js";
import "./chunk-SESTTUVM.js";
import "./chunk-THHRRYRS.js";
import "./chunk-UZWFZMOX.js";
import "./chunk-XQNVC4Q7.js";
import {
  RouteFocusModal,
  useRouteModal
} from "./chunk-FWJLS7XD.js";
import "./chunk-3QSRE5LS.js";
import {
  useRegion,
  useUpdateRegion
} from "./chunk-ESPLVOFC.js";
import "./chunk-VDKOJ5WD.js";
import "./chunk-RHKRREUU.js";
import "./chunk-ZA2KFUFR.js";
import "./chunk-ZBWL72TB.js";
import "./chunk-NBMM2TZK.js";

// src/pages/regions/region-add-countries/region-add-countries.tsx
import { useParams } from "react-router-dom";

// src/pages/regions/region-add-countries/components/add-countries-form/add-countries-form.tsx
import { zodResolver } from "@hookform/resolvers/zod";
import {
  createColumnHelper
} from "@tanstack/react-table";
import { useEffect, useMemo, useState } from "react";
import { useForm } from "react-hook-form";
import { useTranslation } from "react-i18next";
import * as zod from "zod";
import { Button, Checkbox, toast } from "@medusajs/ui";
import { jsx, jsxs } from "react/jsx-runtime";
var AddCountriesSchema = zod.object({
  countries: zod.array(zod.string()).min(1)
});
var PAGE_SIZE = 50;
var PREFIX = "ac";
var AddCountriesForm = ({ region }) => {
  const { t } = useTranslation();
  const { handleSuccess } = useRouteModal();
  const [rowSelection, setRowSelection] = useState({});
  const form = useForm({
    defaultValues: {
      countries: []
    },
    resolver: zodResolver(AddCountriesSchema)
  });
  const { setValue } = form;
  useEffect(() => {
    const ids = Object.keys(rowSelection).filter((k) => rowSelection[k]);
    setValue("countries", ids, {
      shouldDirty: true,
      shouldTouch: true
    });
  }, [rowSelection, setValue]);
  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: (row) => {
      return region.countries?.findIndex((c) => c.iso_2 === row.original.iso_2) === -1;
    },
    getRowId: (row) => row.iso_2,
    pageSize: PAGE_SIZE,
    rowSelection: {
      state: rowSelection,
      updater: setRowSelection
    },
    prefix: PREFIX
  });
  const { mutateAsync, isPending: isLoading } = useUpdateRegion(region.id);
  const handleSubmit = form.handleSubmit(async (values) => {
    const payload = [
      ...region.countries?.map((c) => c.iso_2) ?? [],
      ...values.countries
    ];
    await mutateAsync(
      {
        countries: payload
      },
      {
        onSuccess: () => {
          toast.success(t("regions.toast.countries"));
          handleSuccess();
        },
        onError: (error) => {
          toast.error(error.message);
        }
      }
    );
  });
  return /* @__PURE__ */ jsx(RouteFocusModal.Form, { form, "data-testid": "region-add-countries-form", children: /* @__PURE__ */ jsxs(
    KeyboundForm,
    {
      onSubmit: handleSubmit,
      className: "flex h-full flex-col overflow-hidden",
      children: [
        /* @__PURE__ */ jsx(RouteFocusModal.Header, { "data-testid": "region-add-countries-form-header" }),
        /* @__PURE__ */ jsx(RouteFocusModal.Body, { className: "overflow-hidden", "data-testid": "region-add-countries-form-body", children: /* @__PURE__ */ jsx(
          _DataTable,
          {
            table,
            columns,
            pageSize: PAGE_SIZE,
            count,
            search: "autofocus",
            pagination: true,
            layout: "fill",
            orderBy: [
              { key: "display_name", label: t("fields.name") },
              { key: "iso_2", label: t("fields.code") }
            ],
            queryObject: raw,
            prefix: PREFIX,
            "data-testid": "region-add-countries-form-table"
          }
        ) }),
        /* @__PURE__ */ jsxs(RouteFocusModal.Footer, { "data-testid": "region-add-countries-form-footer", children: [
          /* @__PURE__ */ jsx(RouteFocusModal.Close, { asChild: true, children: /* @__PURE__ */ jsx(Button, { size: "small", variant: "secondary", "data-testid": "region-add-countries-form-cancel-button", children: t("actions.cancel") }) }),
          /* @__PURE__ */ jsx(Button, { size: "small", isLoading, type: "submit", "data-testid": "region-add-countries-form-add-button", children: t("actions.add") })
        ] })
      ]
    }
  ) });
};
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-add-countries-form-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-add-countries-form-select-checkbox-${row.original.iso_2}`
            }
          );
        }
      }),
      ...base
    ],
    [base]
  );
};

// src/pages/regions/region-add-countries/region-add-countries.tsx
import { jsx as jsx2 } from "react/jsx-runtime";
var RegionAddCountries = () => {
  const { id } = useParams();
  const {
    region,
    isPending: isLoading,
    isError,
    error
  } = useRegion(id, {
    fields: "*payment_providers"
  });
  if (isError) {
    throw error;
  }
  return /* @__PURE__ */ jsx2(RouteFocusModal, { "data-testid": "region-add-countries-modal", children: !isLoading && region && /* @__PURE__ */ jsx2(AddCountriesForm, { region }) });
};
export {
  RegionAddCountries as Component
};
