import {
  SectionRow
} from "./chunk-3XPXUIK3.js";
import {
  SingleColumnPage
} from "./chunk-XIZLPYEE.js";
import {
  SingleColumnPageSkeleton
} from "./chunk-INNFZYX2.js";
import {
  ActionMenu
} from "./chunk-BDGZ4EQO.js";
import {
  useProductTypes
} from "./chunk-5PUHROK4.js";
import {
  useCommissionRate,
  useDeleteCommissionRate,
  useUpdateCommissionRate
} from "./chunk-EHQESDH2.js";
import {
  useShippingOptions
} from "./chunk-O4STPJR2.js";
import {
  useProducts
} from "./chunk-BA2HXHTW.js";

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

// src/pages/commission-rates/commission-rate-detail/components/commission-rate-general-section/commission-rate-general-section.tsx
import { PencilSquare, Trash, XCircle, CheckCircle } from "@medusajs/icons";
import { Badge, Container, Heading, StatusBadge, toast, usePrompt } from "@medusajs/ui";
import { useTranslation } from "react-i18next";
import { useNavigate } from "react-router-dom";
import { jsx, jsxs } from "react/jsx-runtime";
var CommissionRateGeneralSection = ({
  commissionRate
}) => {
  const formatValue = () => {
    if (commissionRate.type === "percentage") {
      return `${commissionRate.value}%`;
    }
    return commissionRate.currency_code ? `${commissionRate.value} ${commissionRate.currency_code.toUpperCase()}` : `${commissionRate.value}`;
  };
  return /* @__PURE__ */ jsxs(Container, { className: "divide-y p-0", children: [
    /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between px-6 py-4", children: [
      /* @__PURE__ */ jsx(Heading, { children: commissionRate.name }),
      /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-4", children: [
        /* @__PURE__ */ jsx(StatusBadge, { color: commissionRate.is_enabled ? "green" : "grey", children: commissionRate.is_enabled ? "Enabled" : "Disabled" }),
        /* @__PURE__ */ jsx(CommissionRateActions, { commissionRate })
      ] })
    ] }),
    /* @__PURE__ */ jsx(
      SectionRow,
      {
        title: "Code",
        value: /* @__PURE__ */ jsx(Badge, { size: "2xsmall", className: "uppercase", children: commissionRate.code })
      }
    ),
    /* @__PURE__ */ jsx(
      SectionRow,
      {
        title: "Type",
        value: /* @__PURE__ */ jsx(
          Badge,
          {
            size: "2xsmall",
            color: commissionRate.type === "percentage" ? "blue" : "grey",
            children: commissionRate.type === "percentage" ? "Percentage" : "Fixed"
          }
        )
      }
    ),
    /* @__PURE__ */ jsx(SectionRow, { title: "Value", value: formatValue() }),
    /* @__PURE__ */ jsx(
      SectionRow,
      {
        title: "Target",
        value: commissionRate.target === "item" ? "Item" : "Shipping"
      }
    ),
    /* @__PURE__ */ jsx(
      SectionRow,
      {
        title: "Include Tax",
        value: commissionRate.include_tax ? "Yes" : "No"
      }
    ),
    /* @__PURE__ */ jsx(SectionRow, { title: "Priority", value: String(commissionRate.priority) }),
    commissionRate.min_amount != null && /* @__PURE__ */ jsx(
      SectionRow,
      {
        title: "Minimum Amount",
        value: commissionRate.currency_code ? `${commissionRate.min_amount} ${commissionRate.currency_code.toUpperCase()}` : String(commissionRate.min_amount)
      }
    )
  ] });
};
var CommissionRateActions = ({
  commissionRate
}) => {
  const navigate = useNavigate();
  const { t } = useTranslation();
  const { mutateAsync } = useDeleteCommissionRate(commissionRate.id);
  const { mutateAsync: updateCommissionRate } = useUpdateCommissionRate(commissionRate.id);
  const prompt = usePrompt();
  const handleToggleEnabled = async () => {
    const newEnabled = !commissionRate.is_enabled;
    await updateCommissionRate(
      { is_enabled: newEnabled },
      {
        onSuccess: () => {
          toast.success(
            newEnabled ? "Commission rate enabled successfully" : "Commission rate disabled successfully"
          );
        },
        onError: (e) => {
          toast.error(e.message);
        }
      }
    );
  };
  const handleDelete = async () => {
    const res = await prompt({
      title: t("general.areYouSure"),
      description: `Are you sure you want to delete the commission rate "${commissionRate.name}"?`,
      confirmText: t("actions.delete"),
      cancelText: t("actions.cancel")
    });
    if (!res) {
      return;
    }
    await mutateAsync(void 0, {
      onSuccess: () => {
        toast.success("Commission rate deleted successfully");
        navigate("/settings/commission-rates", { replace: true });
      },
      onError: (e) => {
        toast.error(e.message);
      }
    });
  };
  return /* @__PURE__ */ jsx(
    ActionMenu,
    {
      groups: [
        {
          actions: [
            {
              icon: /* @__PURE__ */ jsx(PencilSquare, {}),
              label: t("actions.edit"),
              to: `/settings/commission-rates/${commissionRate.id}/edit`
            },
            {
              icon: commissionRate.is_enabled ? /* @__PURE__ */ jsx(XCircle, {}) : /* @__PURE__ */ jsx(CheckCircle, {}),
              label: commissionRate.is_enabled ? t("actions.disable") : t("actions.enable"),
              onClick: handleToggleEnabled
            }
          ]
        },
        {
          actions: [
            {
              icon: /* @__PURE__ */ jsx(Trash, {}),
              label: t("actions.delete"),
              onClick: handleDelete
            }
          ]
        }
      ]
    }
  );
};

// src/pages/commission-rates/commission-rate-detail/components/commission-rate-rules-section/commission-rate-rules-section.tsx
import { ArrowDownRightMini } from "@medusajs/icons";
import {
  Badge as Badge2,
  Container as Container2,
  Heading as Heading2,
  Text,
  Tooltip
} from "@medusajs/ui";
import { useTranslation as useTranslation2 } from "react-i18next";
import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
var CommissionRateRulesSection = ({
  commissionRate
}) => {
  const { t } = useTranslation2();
  const rules = commissionRate.rules || [];
  const groupedRules = rules.reduce(
    (acc, rule) => {
      if (!acc[rule.reference]) {
        acc[rule.reference] = [];
      }
      acc[rule.reference].push(rule.reference_id);
      return acc;
    },
    {}
  );
  const entries = Object.entries(groupedRules);
  return /* @__PURE__ */ jsxs2(Container2, { className: "divide-y p-0", children: [
    /* @__PURE__ */ jsx2("div", { className: "flex items-center justify-between px-6 py-4", children: /* @__PURE__ */ jsx2(Heading2, { level: "h2", children: t("taxRegions.fields.targets.label") }) }),
    entries.length === 0 ? /* @__PURE__ */ jsx2("div", { className: "flex items-center justify-center px-6 py-8", children: /* @__PURE__ */ jsx2(Text, { size: "small", className: "text-ui-fg-subtle", children: "No rules configured" }) }) : /* @__PURE__ */ jsx2("div", { className: "px-6 py-4", children: /* @__PURE__ */ jsxs2("div", { className: "flex items-center gap-x-3", children: [
      /* @__PURE__ */ jsx2("div", { className: "text-ui-fg-muted flex size-5 items-center justify-center", children: /* @__PURE__ */ jsx2(ArrowDownRightMini, {}) }),
      /* @__PURE__ */ jsxs2("div", { className: "flex flex-wrap items-center gap-x-1.5 gap-y-2", children: [
        /* @__PURE__ */ jsx2(
          Text,
          {
            size: "small",
            leading: "compact",
            className: "text-ui-fg-subtle",
            children: t("taxRegions.fields.targets.operators.on")
          }
        ),
        entries.map(([reference, ids], index) => {
          return /* @__PURE__ */ jsxs2(
            "div",
            {
              className: "flex items-center gap-x-1.5",
              children: [
                /* @__PURE__ */ jsx2(
                  Reference,
                  {
                    reference,
                    ids
                  }
                ),
                index < entries.length - 1 && /* @__PURE__ */ jsx2(
                  Text,
                  {
                    size: "small",
                    leading: "compact",
                    className: "text-ui-fg-subtle",
                    children: t("taxRegions.fields.targets.operators.and")
                  }
                )
              ]
            },
            reference
          );
        })
      ] })
    ] }) })
  ] });
};
var Reference = ({
  reference,
  ids
}) => {
  return /* @__PURE__ */ jsxs2("div", { className: "flex items-center gap-x-1.5", children: [
    /* @__PURE__ */ jsx2(ReferenceBadge, { reference }),
    /* @__PURE__ */ jsx2(ReferenceValues, { type: reference, ids })
  ] });
};
var ReferenceBadge = ({
  reference
}) => {
  const { t } = useTranslation2();
  let label = null;
  switch (reference) {
    case "product" /* PRODUCT */:
      label = t("taxRegions.fields.targets.tags.product");
      break;
    case "product_type" /* PRODUCT_TYPE */:
      label = t("taxRegions.fields.targets.tags.productType");
      break;
    case "shipping_option" /* SHIPPING_OPTION */:
      label = t("taxRegions.fields.targets.tags.shippingOption");
      break;
  }
  if (!label) {
    return null;
  }
  return /* @__PURE__ */ jsx2(Badge2, { size: "2xsmall", children: label });
};
var ReferenceValues = ({
  type,
  ids
}) => {
  const { t } = useTranslation2();
  const { isPending, additional, labels, isError, error } = useReferenceValues(
    type,
    ids
  );
  if (isError) {
    throw error;
  }
  if (isPending) {
    return /* @__PURE__ */ jsx2("div", { className: "bg-ui-tag-neutral-bg border-ui-tag-neutral-border h-5 w-14 animate-pulse rounded-md" });
  }
  return /* @__PURE__ */ jsx2(
    Tooltip,
    {
      content: /* @__PURE__ */ jsxs2("ul", { children: [
        labels?.map((label, index) => /* @__PURE__ */ jsx2("li", { children: label }, index)),
        additional > 0 && /* @__PURE__ */ jsx2("li", { children: t("taxRegions.fields.targets.additionalValues", {
          count: additional
        }) })
      ] }),
      children: /* @__PURE__ */ jsx2(Badge2, { size: "2xsmall", children: t("taxRegions.fields.targets.values", {
        count: ids.length
      }) })
    }
  );
};
var useReferenceValues = (type, ids) => {
  const products = useProducts(
    { id: ids, limit: 10 },
    { enabled: !!ids.length && type === "product" /* PRODUCT */ }
  );
  const productTypes = useProductTypes(
    { id: ids, limit: 10 },
    { enabled: !!ids.length && type === "product_type" /* PRODUCT_TYPE */ }
  );
  const shippingOptions = useShippingOptions(
    { id: ids, limit: 10 },
    {
      enabled: !!ids.length && type === "shipping_option" /* SHIPPING_OPTION */
    }
  );
  switch (type) {
    case "product" /* PRODUCT */:
      return {
        labels: products.products?.map((product) => product.title),
        isPending: products.isPending,
        additional: products.products && products.count ? products.count - products.products.length : 0,
        isError: products.isError,
        error: products.error
      };
    case "product_type" /* PRODUCT_TYPE */:
      return {
        labels: productTypes.product_types?.map((type2) => type2.value),
        isPending: productTypes.isPending,
        additional: productTypes.product_types && productTypes.count ? productTypes.count - productTypes.product_types.length : 0,
        isError: productTypes.isError,
        error: productTypes.error
      };
    case "shipping_option" /* SHIPPING_OPTION */:
      return {
        labels: shippingOptions.shipping_options?.map((option) => option.name),
        isPending: shippingOptions.isPending,
        additional: shippingOptions.count ? shippingOptions.count - (shippingOptions.shipping_options?.length || 0) : 0,
        isError: shippingOptions.isError,
        error: shippingOptions.error
      };
  }
};

// src/pages/commission-rates/commission-rate-detail/commission-rate-detail.tsx
import { jsx as jsx3, jsxs as jsxs3 } from "react/jsx-runtime";
var Root = ({ children }) => {
  const initialData = useLoaderData();
  const { id } = useParams();
  const {
    commission_rate,
    isPending: isLoading,
    isError,
    error
  } = useCommissionRate(id, { fields: "*rules" }, { initialData });
  if (isLoading || !commission_rate) {
    return /* @__PURE__ */ jsx3(SingleColumnPageSkeleton, { sections: 2, showJSON: true, showMetadata: true });
  }
  if (isError) {
    throw error;
  }
  return Children.count(children) > 0 ? /* @__PURE__ */ jsx3(SingleColumnPage, { data: commission_rate, showJSON: true, showMetadata: true, children }) : /* @__PURE__ */ jsxs3(SingleColumnPage, { data: commission_rate, showJSON: true, showMetadata: true, children: [
    /* @__PURE__ */ jsx3(CommissionRateGeneralSection, { commissionRate: commission_rate }),
    /* @__PURE__ */ jsx3(CommissionRateRulesSection, { commissionRate: commission_rate })
  ] });
};
var CommissionRateDetailPage = Object.assign(Root, {
  GeneralSection: CommissionRateGeneralSection,
  RulesSection: CommissionRateRulesSection
});

export {
  CommissionRateDetailPage
};
