import {
  useLocalesTableColumns,
  useLocalesTableQuery
} from "./chunk-6PNOUH6F.mjs";
import {
  _DataTable,
  useDataTable
} from "./chunk-7TWTWTDT.mjs";
import {
  KeyboundForm
} from "./chunk-6HTZNHPT.mjs";
import {
  RouteFocusModal,
  useRouteModal
} from "./chunk-ULMMKZ3U.mjs";
import {
  useLocales
} from "./chunk-OW2UL5FI.mjs";
import {
  useUpdateStore
} from "./chunk-VCSSQVPD.mjs";

// src/routes/store/store-add-locales/components/add-locales-form/add-locales-form.tsx
import { z } from "zod";
import { useTranslation } from "react-i18next";
import { keepPreviousData } from "@tanstack/react-query";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import {
  createColumnHelper
} from "@tanstack/react-table";
import { useMemo, useState } from "react";
import { Button, Checkbox, Hint, toast, Tooltip } from "@medusajs/ui";
import { jsx, jsxs } from "react/jsx-runtime";
var AddLocalesSchema = z.object({
  locales: z.array(z.string()).min(1)
});
var PAGE_SIZE = 50;
var PREFIX = "al";
var AddLocalesForm = ({ store }) => {
  const { t } = useTranslation();
  const { handleSuccess } = useRouteModal();
  const { raw, searchParams } = useLocalesTableQuery({
    pageSize: PAGE_SIZE,
    prefix: PREFIX
  });
  const {
    locales,
    count,
    isPending: isLoading,
    isError,
    error
  } = useLocales(searchParams, {
    placeholderData: keepPreviousData
  });
  const form = useForm({
    defaultValues: {
      locales: []
    },
    resolver: zodResolver(AddLocalesSchema)
  });
  const [rowSelection, setRowSelection] = useState({});
  const { setValue } = form;
  const updater = (fn) => {
    const updated = typeof fn === "function" ? fn(rowSelection) : fn;
    const ids = Object.keys(updated);
    setValue("locales", ids, {
      shouldDirty: true,
      shouldTouch: true
    });
    setRowSelection(updated);
  };
  const preSelectedRows = store.supported_locales?.map((l) => l.locale_code) ?? [];
  const columns = useColumns();
  const { table } = useDataTable({
    data: locales ?? [],
    columns,
    count,
    getRowId: (row) => row.code,
    enableRowSelection: (row) => !preSelectedRows.includes(row.original.code),
    enablePagination: true,
    pageSize: PAGE_SIZE,
    prefix: PREFIX,
    rowSelection: {
      state: rowSelection,
      updater
    }
  });
  const { mutateAsync, isPending } = useUpdateStore(store.id);
  const handleSubmit = form.handleSubmit(async (data) => {
    const locales2 = Array.from(
      /* @__PURE__ */ new Set([...data.locales, ...preSelectedRows])
    );
    await mutateAsync(
      {
        supported_locales: locales2.map((l) => ({
          locale_code: l
        }))
      },
      {
        onSuccess: () => {
          toast.success(t("store.toast.localesUpdated"));
          handleSuccess();
        },
        onError: (error2) => {
          toast.error(error2.message);
        }
      }
    );
  });
  if (isError) {
    throw error;
  }
  return /* @__PURE__ */ jsx(RouteFocusModal.Form, { form, children: /* @__PURE__ */ jsxs(
    KeyboundForm,
    {
      onSubmit: handleSubmit,
      className: "flex h-full flex-col overflow-hidden",
      children: [
        /* @__PURE__ */ jsx(RouteFocusModal.Header, { children: /* @__PURE__ */ jsx("div", { className: "flex flex-1 items-center justify-between", children: /* @__PURE__ */ jsx("div", { className: "flex items-center", children: form.formState.errors.locales && /* @__PURE__ */ jsx(Hint, { variant: "error", children: form.formState.errors.locales.message }) }) }) }),
        /* @__PURE__ */ jsx(RouteFocusModal.Body, { className: "flex flex-1 flex-col overflow-hidden", children: /* @__PURE__ */ jsx(
          _DataTable,
          {
            table,
            pageSize: PAGE_SIZE,
            count,
            columns,
            layout: "fill",
            pagination: true,
            search: "autofocus",
            prefix: PREFIX,
            orderBy: [
              { key: "name", label: t("fields.name") },
              { key: "code", label: t("fields.code") }
            ],
            isLoading,
            queryObject: raw
          }
        ) }),
        /* @__PURE__ */ jsx(RouteFocusModal.Footer, { children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-end gap-x-2", children: [
          /* @__PURE__ */ jsx(RouteFocusModal.Close, { asChild: true, children: /* @__PURE__ */ jsx(Button, { size: "small", variant: "secondary", children: t("actions.cancel") }) }),
          /* @__PURE__ */ jsx(Button, { size: "small", type: "submit", isLoading: isPending, children: t("actions.save") })
        ] }) })
      ]
    }
  ) });
};
var columnHelper = createColumnHelper();
var useColumns = () => {
  const { t } = useTranslation();
  const base = useLocalesTableColumns();
  return useMemo(
    () => [
      columnHelper.display({
        id: "select",
        header: ({ table }) => {
          return /* @__PURE__ */ jsx(
            Checkbox,
            {
              checked: table.getIsSomePageRowsSelected() ? "indeterminate" : table.getIsAllPageRowsSelected(),
              onCheckedChange: (value) => table.toggleAllPageRowsSelected(!!value)
            }
          );
        },
        cell: ({ row }) => {
          const isPreSelected = !row.getCanSelect();
          const isSelected = row.getIsSelected() || isPreSelected;
          const Component = /* @__PURE__ */ jsx(
            Checkbox,
            {
              checked: isSelected,
              disabled: isPreSelected,
              onCheckedChange: (value) => row.toggleSelected(!!value),
              onClick: (e) => {
                e.stopPropagation();
              }
            }
          );
          if (isPreSelected) {
            return /* @__PURE__ */ jsx(Tooltip, { content: t("store.localeAlreadyAdded"), side: "right", children: Component });
          }
          return Component;
        }
      }),
      ...base
    ],
    [t, base]
  );
};

export {
  AddLocalesForm
};
