"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { z } from "zod";
import { DataTable } from "@open-mercato/ui/backend/DataTable";
import { RowActions } from "@open-mercato/ui/backend/RowActions";
import { Button } from "@open-mercato/ui/primitives/button";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle
} from "@open-mercato/ui/primitives/dialog";
import { Input } from "@open-mercato/ui/primitives/input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from "@open-mercato/ui/primitives/select";
import { Label } from "@open-mercato/ui/primitives/label";
import { SwitchField } from "@open-mercato/ui/primitives/switch-field";
import { CrudForm } from "@open-mercato/ui/backend/CrudForm";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { apiCall, readApiResultOrThrow, withScopedApiRequestHeaders } from "@open-mercato/ui/backend/utils/apiCall";
import { buildOptimisticLockHeader } from "@open-mercato/ui/backend/utils/optimisticLock";
import { surfaceRecordConflict } from "@open-mercato/ui/backend/conflicts";
import { raiseCrudError } from "@open-mercato/ui/backend/utils/serverErrors";
import { useOrganizationScopeVersion } from "@open-mercato/shared/lib/frontend/useOrganizationScope";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { useConfirmDialog } from "@open-mercato/ui/backend/confirm-dialog";
import {
  listShippingProviders
} from "../lib/providers/index.js";
import { isRecord } from "@open-mercato/shared/lib/utils";
import { renderProviderFieldInput } from "./ProviderFieldInput.js";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("sales");
const shippingFormSchema = z.object({
  name: z.string().trim().min(1),
  code: z.string().trim().min(1),
  providerKey: z.string().trim().optional(),
  description: z.string().optional(),
  carrierCode: z.string().optional(),
  serviceLevel: z.string().optional(),
  estimatedTransitDays: z.coerce.number().min(0).optional(),
  baseRateNet: z.coerce.number().min(0),
  baseRateGross: z.coerce.number().min(0).optional(),
  currencyCode: z.string().trim().optional(),
  isActive: z.boolean().optional(),
  providerSettings: z.record(z.string(), z.unknown()).optional()
});
const DEFAULT_FORM = {
  name: "",
  code: "",
  providerKey: "",
  description: "",
  carrierCode: "",
  serviceLevel: "",
  estimatedTransitDays: void 0,
  baseRateNet: 0,
  baseRateGross: 0,
  currencyCode: "",
  isActive: true,
  providerSettings: {}
};
function FlatRateSettingsEditor(props) {
  const { value, onChange, translations, currencyCode } = props;
  const rates = Array.isArray(value.rates) ? value.rates : [];
  const applyBaseRate = value.applyBaseRate !== false;
  const metrics = [
    { value: "item_count", label: "Item count" },
    { value: "weight", label: "Total weight" },
    { value: "volume", label: "Total volume" },
    { value: "subtotal", label: "Subtotal" }
  ];
  const updateRates = (nextRates) => {
    onChange({ ...value, rates: nextRates });
  };
  const updateRate = (index, key, nextValue) => {
    const next = rates.map(
      (rate, idx) => idx === index ? { ...rate, [key]: nextValue } : rate
    );
    updateRates(next);
  };
  const addRate = () => {
    updateRates([
      ...rates,
      {
        id: crypto.randomUUID?.() ?? String(Date.now()),
        name: "",
        metric: "item_count",
        min: 0,
        max: null,
        amountNet: 0,
        amountGross: 0,
        currencyCode: currencyCode ?? ""
      }
    ]);
  };
  const removeRate = (index) => {
    updateRates(rates.filter((_, idx) => idx !== index));
  };
  return /* @__PURE__ */ jsxs("div", { className: "space-y-3 rounded-md border border-dashed border-border p-3", children: [
    /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
      /* @__PURE__ */ jsx("p", { className: "text-sm font-medium", children: translations.title }),
      /* @__PURE__ */ jsx(Button, { size: "sm", variant: "outline", type: "button", onClick: addRate, children: translations.add })
    ] }),
    /* @__PURE__ */ jsx("div", { className: "space-y-3", children: rates.length === 0 ? /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: translations.add }) : rates.map((rate, index) => /* @__PURE__ */ jsxs("div", { className: "rounded-md border border-border p-3 space-y-2", children: [
      /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3", children: [
        /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
          /* @__PURE__ */ jsx(Label, { className: "text-xs uppercase text-muted-foreground", children: translations.metric }),
          /* @__PURE__ */ jsxs(
            Select,
            {
              value: rate.metric ?? "item_count",
              onValueChange: (value2) => updateRate(index, "metric", value2),
              children: [
                /* @__PURE__ */ jsx(SelectTrigger, { children: /* @__PURE__ */ jsx(SelectValue, {}) }),
                /* @__PURE__ */ jsx(SelectContent, { children: metrics.map((opt) => /* @__PURE__ */ jsx(SelectItem, { value: opt.value, children: opt.label }, opt.value)) })
              ]
            }
          )
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
          /* @__PURE__ */ jsx(Label, { className: "text-xs uppercase text-muted-foreground", children: translations.min }),
          /* @__PURE__ */ jsx(
            Input,
            {
              type: "number",
              value: rate.min ?? "",
              onChange: (evt) => updateRate(index, "min", evt.target.value === "" ? null : Number(evt.target.value))
            }
          )
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
          /* @__PURE__ */ jsx(Label, { className: "text-xs uppercase text-muted-foreground", children: translations.max }),
          /* @__PURE__ */ jsx(
            Input,
            {
              type: "number",
              value: rate.max ?? "",
              onChange: (evt) => updateRate(index, "max", evt.target.value === "" ? null : Number(evt.target.value))
            }
          )
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
          /* @__PURE__ */ jsx(Label, { className: "text-xs uppercase text-muted-foreground", children: translations.amountNet }),
          /* @__PURE__ */ jsx(
            Input,
            {
              type: "number",
              value: rate.amountNet ?? "",
              onChange: (evt) => updateRate(index, "amountNet", evt.target.value === "" ? null : Number(evt.target.value))
            }
          )
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
          /* @__PURE__ */ jsx(Label, { className: "text-xs uppercase text-muted-foreground", children: translations.amountGross }),
          /* @__PURE__ */ jsx(
            Input,
            {
              type: "number",
              value: rate.amountGross ?? "",
              onChange: (evt) => updateRate(index, "amountGross", evt.target.value === "" ? null : Number(evt.target.value))
            }
          )
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
          /* @__PURE__ */ jsx(Label, { className: "text-xs uppercase text-muted-foreground", children: translations.currency }),
          /* @__PURE__ */ jsx(
            Input,
            {
              type: "text",
              value: rate.currencyCode ?? currencyCode ?? "",
              onChange: (evt) => updateRate(index, "currencyCode", evt.target.value?.toUpperCase?.() ?? "")
            }
          )
        ] })
      ] }),
      /* @__PURE__ */ jsx("div", { className: "flex justify-end", children: /* @__PURE__ */ jsx(Button, { type: "button", variant: "ghost", size: "sm", onClick: () => removeRate(index), children: translations.remove }) })
    ] }, rate.id ?? index)) }),
    /* @__PURE__ */ jsx(
      SwitchField,
      {
        id: "apply-base-rate",
        label: translations.applyBaseRate,
        flip: true,
        checked: applyBaseRate,
        onCheckedChange: (checked) => onChange({ ...value, applyBaseRate: checked })
      }
    )
  ] });
}
function createShippingProviderSettingsRenderer(params) {
  const { providers, selectPrompt, noFieldsLabel, flatRateLabels } = params;
  return function ShippingProviderSettingsField({
    value,
    setValue,
    values
  }) {
    const providerKey = values && typeof values.providerKey === "string" && values.providerKey.trim().length ? values.providerKey : null;
    const provider = providers.find((entry) => entry.key === providerKey);
    const previousKey = React.useRef(providerKey);
    React.useEffect(() => {
      if (providerKey !== previousKey.current) {
        const defaults = provider?.settings?.defaults ?? null;
        setValue(defaults && typeof defaults === "object" ? defaults : {});
        previousKey.current = providerKey;
      }
    }, [providerKey, provider, setValue]);
    if (!provider) {
      return /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: selectPrompt });
    }
    const settings = isRecord(value) ? value : {};
    const fields = provider.settings?.fields ?? [];
    if (provider.key === "flat-rate") {
      return /* @__PURE__ */ jsx(
        FlatRateSettingsEditor,
        {
          value: settings,
          onChange: (next) => setValue(next),
          translations: flatRateLabels,
          currencyCode: typeof values?.currencyCode === "string" ? values.currencyCode : ""
        }
      );
    }
    if (!fields.length) {
      return /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: noFieldsLabel });
    }
    return /* @__PURE__ */ jsx("div", { className: "space-y-4", children: fields.map((field) => {
      const fieldValue = settings[field.key];
      return /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
        /* @__PURE__ */ jsxs(Label, { htmlFor: field.key, className: "text-sm font-medium", children: [
          field.label,
          field.required ? " *" : ""
        ] }),
        field.description ? /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: field.description }) : null,
        renderProviderFieldInput({
          field,
          value: fieldValue,
          onChange: (next) => setValue({ ...settings, [field.key]: next })
        })
      ] }, field.key);
    }) });
  };
}
function ShippingMethodsSettings() {
  const t = useT();
  const scopeVersion = useOrganizationScopeVersion();
  const { confirm, ConfirmDialogElement } = useConfirmDialog();
  const providers = React.useMemo(() => listShippingProviders(), []);
  const providerOptions = React.useMemo(
    () => providers.map((provider) => ({ value: provider.key, label: provider.label })),
    [providers]
  );
  const flatRateLabels = React.useMemo(() => ({
    title: t("sales.config.shippingMethods.form.ratesTitle", "Rates"),
    add: t("sales.config.shippingMethods.form.addRate", "Add rate"),
    metric: t("sales.config.shippingMethods.form.metric", "Metric"),
    min: t("sales.config.shippingMethods.form.min", "Min"),
    max: t("sales.config.shippingMethods.form.max", "Max"),
    amountNet: t("sales.config.shippingMethods.form.amountNet", "Amount (net)"),
    amountGross: t("sales.config.shippingMethods.form.amountGross", "Amount (gross)"),
    currency: t("sales.config.shippingMethods.form.currency", "Currency"),
    remove: t("sales.config.shippingMethods.form.removeRate", "Remove"),
    applyBaseRate: t(
      "sales.config.shippingMethods.form.applyBaseRate",
      "Always include the base rate"
    )
  }), [t]);
  const ProviderSettingsField = React.useMemo(
    () => createShippingProviderSettingsRenderer({
      providers,
      selectPrompt: t(
        "sales.config.shippingMethods.form.selectProvider",
        "Choose a provider to configure settings."
      ),
      noFieldsLabel: t("sales.config.shippingMethods.form.noSettings", "No configurable settings."),
      flatRateLabels
    }),
    [flatRateLabels, providers, t]
  );
  const translations = React.useMemo(() => ({
    title: t("sales.config.shippingMethods.title", "Shipping methods"),
    description: t(
      "sales.config.shippingMethods.description",
      "Manage carriers, providers, and default shipping prices."
    ),
    actions: {
      add: t("sales.config.shippingMethods.actions.add", "Add shipping method"),
      edit: t("sales.config.shippingMethods.actions.edit", "Edit"),
      delete: t("sales.config.shippingMethods.actions.delete", "Delete"),
      deleteConfirm: t("sales.config.shippingMethods.actions.deleteConfirm", 'Delete "{{name}}"?'),
      refresh: t("sales.config.shippingMethods.actions.refresh", "Refresh")
    },
    table: {
      name: t("sales.config.shippingMethods.table.name", "Name"),
      code: t("sales.config.shippingMethods.table.code", "Code"),
      provider: t("sales.config.shippingMethods.table.provider", "Provider"),
      rate: t("sales.config.shippingMethods.table.rate", "Base rate"),
      currency: t("sales.config.shippingMethods.table.currency", "Currency"),
      active: t("sales.config.shippingMethods.table.active", "Active"),
      statusActive: t("sales.config.shippingMethods.table.statusActive", "Active"),
      statusInactive: t("sales.config.shippingMethods.table.statusInactive", "Inactive"),
      updatedAt: t("sales.config.shippingMethods.table.updatedAt", "Updated"),
      empty: t("sales.config.shippingMethods.table.empty", "No shipping methods yet."),
      search: t("sales.config.shippingMethods.table.search", "Search shipping methods\u2026")
    },
    form: {
      createTitle: t("sales.config.shippingMethods.form.createTitle", "Add shipping method"),
      editTitle: t("sales.config.shippingMethods.form.editTitle", "Edit shipping method"),
      name: t("sales.config.shippingMethods.form.name", "Name"),
      code: t("sales.config.shippingMethods.form.code", "Code"),
      provider: t("sales.config.shippingMethods.form.provider", "Provider"),
      description: t("sales.config.shippingMethods.form.description", "Description"),
      carrierCode: t("sales.config.shippingMethods.form.carrierCode", "Carrier"),
      serviceLevel: t("sales.config.shippingMethods.form.serviceLevel", "Service level"),
      estimatedTransitDays: t(
        "sales.config.shippingMethods.form.estimatedTransitDays",
        "Transit days"
      ),
      baseRateNet: t("sales.config.shippingMethods.form.baseRateNet", "Base rate (net)"),
      baseRateGross: t("sales.config.shippingMethods.form.baseRateGross", "Base rate (gross)"),
      currencyCode: t("sales.config.shippingMethods.form.currencyCode", "Currency"),
      isActive: t("sales.config.shippingMethods.form.isActive", "Active"),
      providerSettings: t("sales.config.shippingMethods.form.providerSettings", "Provider settings"),
      save: t("sales.config.shippingMethods.form.save", "Save"),
      cancel: t("sales.config.shippingMethods.form.cancel", "Cancel")
    },
    messages: {
      saved: t("sales.config.shippingMethods.messages.saved", "Shipping method saved."),
      deleted: t("sales.config.shippingMethods.messages.deleted", "Shipping method deleted.")
    },
    errors: {
      load: t("sales.config.shippingMethods.errors.load", "Failed to load shipping methods."),
      save: t("sales.config.shippingMethods.errors.save", "Failed to save shipping method."),
      delete: t("sales.config.shippingMethods.errors.delete", "Failed to delete shipping method.")
    }
  }), [t]);
  const [entries, setEntries] = React.useState([]);
  const [loading, setLoading] = React.useState(false);
  const [dialog, setDialog] = React.useState(null);
  const [formValues, setFormValues] = React.useState(DEFAULT_FORM);
  const [search, setSearch] = React.useState("");
  const [submitting, setSubmitting] = React.useState(false);
  const loadEntries = React.useCallback(async () => {
    setLoading(true);
    try {
      const payload = await readApiResultOrThrow(
        "/api/sales/shipping-methods?pageSize=100",
        void 0,
        { errorMessage: translations.errors.load, fallback: { items: [] } }
      );
      const items = Array.isArray(payload.items) ? payload.items : [];
      setEntries(
        items.map((item) => {
          const providerKey = typeof item.providerKey === "string" ? item.providerKey : typeof item?.provider_key === "string" ? item.provider_key : null;
          const provider = providers.find((entry) => entry.key === providerKey);
          const baseRateGross = typeof item.baseRateGross === "number" ? item.baseRateGross : Number(item?.base_rate_gross ?? item.baseRateGross ?? 0) || 0;
          const baseRateNet = typeof item.baseRateNet === "number" ? item.baseRateNet : Number(item?.base_rate_net ?? item.baseRateNet ?? 0) || 0;
          const currency = typeof item.currencyCode === "string" ? item.currencyCode : typeof item?.currency_code === "string" ? item.currency_code : null;
          return {
            id: String(item.id ?? ""),
            name: typeof item.name === "string" && item.name.length ? item.name : "\u2014",
            code: typeof item.code === "string" ? item.code : "",
            providerKey,
            providerLabel: provider?.label ?? null,
            carrierCode: typeof item.carrierCode === "string" ? item.carrierCode : null,
            description: typeof item.description === "string" ? item.description : null,
            serviceLevel: typeof item.serviceLevel === "string" ? item.serviceLevel : null,
            estimatedTransitDays: typeof item?.estimatedTransitDays === "number" ? item.estimatedTransitDays : typeof item?.estimated_transit_days === "number" ? item.estimated_transit_days : null,
            baseRateNet,
            baseRateGross,
            currencyCode: currency,
            isActive: typeof item.isActive === "boolean" ? item.isActive : typeof item?.is_active === "boolean" ? item.is_active : false,
            updatedAt: typeof item.updatedAt === "string" ? item.updatedAt : null,
            providerSettings: item && typeof item.providerSettings === "object" ? item.providerSettings : null
          };
        })
      );
    } catch (err) {
      logger.error("sales.shipping-methods.list failed", { err });
      flash(translations.errors.load, "error");
    } finally {
      setLoading(false);
    }
  }, [providers, translations.errors.load]);
  React.useEffect(() => {
    void loadEntries();
  }, [loadEntries, scopeVersion]);
  const openCreate = React.useCallback(() => {
    const defaultProvider = providerOptions[0]?.value ?? "";
    setFormValues({
      ...DEFAULT_FORM,
      providerKey: defaultProvider,
      providerSettings: {}
    });
    setDialog({ mode: "create" });
  }, [providerOptions]);
  const openEdit = React.useCallback((entry) => {
    setFormValues({
      name: entry.name,
      code: entry.code,
      providerKey: entry.providerKey ?? "",
      description: entry.description ?? "",
      carrierCode: entry.carrierCode ?? "",
      serviceLevel: entry.serviceLevel ?? "",
      estimatedTransitDays: entry.estimatedTransitDays ?? void 0,
      baseRateNet: entry.baseRateNet,
      baseRateGross: entry.baseRateGross,
      currencyCode: entry.currencyCode ?? "",
      isActive: entry.isActive,
      providerSettings: entry.providerSettings ?? {}
    });
    setDialog({ mode: "edit", entry });
  }, []);
  const closeDialog = React.useCallback(() => {
    setDialog(null);
  }, []);
  const deleteEntry = React.useCallback(async (entry) => {
    const message = translations.actions.deleteConfirm.replace("{{name}}", entry.name);
    const confirmed = await confirm({
      title: message,
      variant: "destructive"
    });
    if (!confirmed) return;
    try {
      const headers = buildOptimisticLockHeader(entry.updatedAt);
      const call = await withScopedApiRequestHeaders(headers, () => apiCall("/api/sales/shipping-methods", {
        method: "DELETE",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ id: entry.id })
      }));
      if (!call.ok) {
        if (surfaceRecordConflict({ status: call.status, body: call.result }, t)) return;
        await raiseCrudError(call.response, translations.errors.delete);
      }
      flash(translations.messages.deleted, "success");
      await loadEntries();
    } catch (err) {
      logger.error("sales.shipping-methods.delete failed", { err });
      const message2 = err instanceof Error ? err.message : translations.errors.delete;
      flash(message2, "error");
    }
  }, [confirm, loadEntries, translations.actions.deleteConfirm, translations.errors.delete, translations.messages.deleted]);
  const columns = React.useMemo(() => [
    {
      accessorKey: "name",
      header: translations.table.name,
      cell: ({ row }) => /* @__PURE__ */ jsxs("div", { className: "flex flex-col", children: [
        /* @__PURE__ */ jsx("span", { className: "font-medium", children: row.original.name }),
        /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: row.original.code })
      ] })
    },
    {
      accessorKey: "providerKey",
      header: translations.table.provider,
      cell: ({ row }) => /* @__PURE__ */ jsx("span", { className: "text-sm", children: row.original.providerLabel ?? row.original.providerKey ?? "\u2014" })
    },
    {
      accessorKey: "rate",
      header: translations.table.rate,
      cell: ({ row }) => /* @__PURE__ */ jsxs("span", { className: "text-sm", children: [
        row.original.baseRateGross.toFixed(2),
        " ",
        row.original.currencyCode ?? ""
      ] })
    },
    {
      accessorKey: "isActive",
      header: translations.table.active,
      cell: ({ row }) => /* @__PURE__ */ jsx("span", { className: "text-sm", children: row.original.isActive ? translations.table.statusActive : translations.table.statusInactive })
    },
    {
      accessorKey: "updatedAt",
      header: translations.table.updatedAt,
      cell: ({ row }) => /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: row.original.updatedAt ? new Date(row.original.updatedAt).toLocaleString() : "\u2014" })
    }
  ], [translations]);
  const handleSubmit = React.useCallback(async (values) => {
    if (!dialog) return;
    setSubmitting(true);
    const payload = {
      name: values.name.trim(),
      code: values.code.trim().toLowerCase(),
      description: values.description?.trim() || void 0,
      carrierCode: values.carrierCode?.trim() || void 0,
      providerKey: values.providerKey?.trim() || void 0,
      serviceLevel: values.serviceLevel?.trim() || void 0,
      estimatedTransitDays: values.estimatedTransitDays === void 0 || values.estimatedTransitDays === null ? void 0 : Number(values.estimatedTransitDays),
      baseRateNet: Number(values.baseRateNet ?? 0),
      baseRateGross: values.baseRateGross === void 0 || values.baseRateGross === null ? Number(values.baseRateNet ?? 0) : Number(values.baseRateGross),
      currencyCode: values.currencyCode?.trim().toUpperCase() || void 0,
      isActive: values.isActive ?? true,
      providerSettings: isRecord(values.providerSettings) ? values.providerSettings : void 0
    };
    const path = "/api/sales/shipping-methods";
    const method = dialog.mode === "create" ? "POST" : "PUT";
    if (dialog.mode === "edit") payload.id = dialog.entry.id;
    try {
      const saveShippingMethod = () => apiCall(path, {
        method,
        headers: { "content-type": "application/json" },
        body: JSON.stringify(payload)
      });
      const headers = buildOptimisticLockHeader(dialog.mode === "edit" ? dialog.entry.updatedAt : null);
      const call = await withScopedApiRequestHeaders(headers, saveShippingMethod);
      if (!call.ok) {
        if (surfaceRecordConflict({ status: call.status, body: call.result }, t)) return;
        await raiseCrudError(call.response, translations.errors.save);
      }
      flash(translations.messages.saved, "success");
      await loadEntries();
      closeDialog();
    } catch (err) {
      logger.error("sales.shipping-methods.save failed", { err });
      const message = err instanceof Error ? err.message : translations.errors.save;
      flash(message, "error");
    } finally {
      setSubmitting(false);
    }
  }, [closeDialog, dialog, loadEntries, translations.errors.save, translations.messages.saved]);
  const fields = React.useMemo(() => [
    { id: "name", label: translations.form.name, type: "text", required: true },
    { id: "code", label: translations.form.code, type: "text", required: true },
    {
      id: "providerKey",
      label: translations.form.provider,
      type: "select",
      required: false,
      options: providerOptions
    },
    { id: "carrierCode", label: translations.form.carrierCode, type: "text" },
    { id: "serviceLevel", label: translations.form.serviceLevel, type: "text" },
    {
      id: "estimatedTransitDays",
      label: translations.form.estimatedTransitDays,
      type: "number",
      layout: "half"
    },
    {
      id: "baseRateNet",
      label: translations.form.baseRateNet,
      type: "number",
      required: true,
      layout: "half"
    },
    {
      id: "baseRateGross",
      label: translations.form.baseRateGross,
      type: "number",
      required: false,
      layout: "half"
    },
    {
      id: "currencyCode",
      label: translations.form.currencyCode,
      type: "text",
      layout: "half"
    },
    { id: "description", label: translations.form.description, type: "textarea" },
    { id: "isActive", label: translations.form.isActive, type: "checkbox" },
    {
      id: "providerSettings",
      label: translations.form.providerSettings,
      type: "custom",
      component: ProviderSettingsField
    }
  ], [ProviderSettingsField, providerOptions, translations.form.baseRateGross, translations.form.baseRateNet, translations.form.carrierCode, translations.form.code, translations.form.currencyCode, translations.form.description, translations.form.estimatedTransitDays, translations.form.isActive, translations.form.name, translations.form.provider, translations.form.providerSettings, translations.form.serviceLevel]);
  const filteredEntries = React.useMemo(() => {
    if (!search.trim()) return entries;
    const term = search.trim().toLowerCase();
    return entries.filter(
      (entry) => entry.name.toLowerCase().includes(term) || entry.code.toLowerCase().includes(term) || (entry.providerLabel ?? "").toLowerCase().includes(term) || (entry.providerKey ?? "").toLowerCase().includes(term)
    );
  }, [entries, search]);
  return /* @__PURE__ */ jsxs("section", { className: "rounded border bg-card text-card-foreground shadow-sm", children: [
    /* @__PURE__ */ jsxs("div", { className: "border-b px-6 py-4 space-y-1", children: [
      /* @__PURE__ */ jsx("h2", { className: "text-lg font-medium", children: translations.title }),
      /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: translations.description })
    ] }),
    /* @__PURE__ */ jsx("div", { className: "px-2 py-4 sm:px-4", children: /* @__PURE__ */ jsx(
      DataTable,
      {
        embedded: true,
        isLoading: loading,
        columns,
        data: filteredEntries,
        searchValue: search,
        onSearchChange: setSearch,
        searchPlaceholder: translations.table.search,
        emptyState: /* @__PURE__ */ jsx("p", { className: "py-8 text-center text-sm text-muted-foreground", children: translations.table.empty }),
        actions: /* @__PURE__ */ jsx(Button, { size: "sm", onClick: openCreate, children: translations.actions.add }),
        refreshButton: {
          label: translations.actions.refresh,
          onRefresh: () => {
            void loadEntries();
          },
          isRefreshing: loading
        },
        rowActions: (row) => /* @__PURE__ */ jsx(
          RowActions,
          {
            items: [
              { id: "edit", label: translations.actions.edit, onSelect: () => openEdit(row) },
              { id: "delete", label: translations.actions.delete, destructive: true, onSelect: () => deleteEntry(row) }
            ]
          }
        )
      }
    ) }),
    /* @__PURE__ */ jsx(Dialog, { open: dialog !== null, onOpenChange: (next) => !next && closeDialog(), children: /* @__PURE__ */ jsxs(DialogContent, { className: "max-w-4xl", children: [
      /* @__PURE__ */ jsx(DialogHeader, { children: /* @__PURE__ */ jsx(DialogTitle, { children: dialog?.mode === "edit" ? translations.form.editTitle : translations.form.createTitle }) }),
      /* @__PURE__ */ jsx(
        CrudForm,
        {
          schema: shippingFormSchema,
          fields,
          initialValues: formValues,
          optimisticLockUpdatedAt: dialog?.mode === "edit" ? dialog.entry.updatedAt : null,
          submitLabel: translations.form.save,
          cancelHref: void 0,
          embedded: true,
          onSubmit: handleSubmit,
          isLoading: submitting,
          twoColumn: true,
          extraActions: /* @__PURE__ */ jsx(Button, { type: "button", variant: "ghost", onClick: closeDialog, children: translations.form.cancel })
        }
      )
    ] }) }),
    ConfirmDialogElement
  ] });
}
export {
  ShippingMethodsSettings
};
//# sourceMappingURL=ShippingMethodsSettings.js.map
