import {
  CreateCampaignFormFields
} from "./chunk-YTPCWCA3.js";
import {
  useComboboxData
} from "./chunk-AEFDAU3Y.js";
import {
  Combobox
} from "./chunk-AW77UWCZ.js";
import {
  KeyboundForm
} from "./chunk-U2ZFCAPX.js";
import {
  useDocumentDirection
} from "./chunk-Y7QKP6QU.js";
import {
  RouteDrawer,
  useRouteModal
} from "./chunk-OV7R2AH5.js";
import {
  Form
} from "./chunk-3QSRE5LS.js";
import {
  useCampaign,
  useUpdatePromotion
} from "./chunk-HAFZQK53.js";
import {
  sdk
} from "./chunk-RIN4CBRB.js";

// src/pages/promotions/promotion-add-campaign/components/add-campaign-promotion-form/add-campaign-promotion-form.tsx
import { zodResolver } from "@hookform/resolvers/zod";
import { Button, RadioGroup, toast } from "@medusajs/ui";
import { useEffect } from "react";
import { useForm, useWatch } from "react-hook-form";
import { useTranslation as useTranslation2 } from "react-i18next";
import * as zod from "zod";

// src/pages/promotions/promotion-add-campaign/components/add-campaign-promotion-form/campaign-details.tsx
import { Heading, Text } from "@medusajs/ui";
import { Fragment } from "react";
import { useTranslation } from "react-i18next";
import { jsx, jsxs } from "react/jsx-runtime";
var translationKeyMap = {
  spend: "spend",
  usage: "usage",
  use_by_attribute: "useByAttribute"
};
var CampaignDetails = ({ campaign }) => {
  const { t } = useTranslation();
  if (!campaign) {
    return;
  }
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsxs("div", { children: [
      /* @__PURE__ */ jsx(Heading, { level: "h2", className: "mb-4", children: t("campaigns.details") }),
      /* @__PURE__ */ jsxs("div", { className: "text-ui-fg-subtle grid grid-cols-2 items-center py-1", children: [
        /* @__PURE__ */ jsx(Text, { className: "txt-small-plus font-", children: t("campaigns.fields.identifier") }),
        /* @__PURE__ */ jsx("div", { className: "flex items-center gap-1", children: /* @__PURE__ */ jsx(Text, { className: "txt-small", children: campaign.campaign_identifier || "-" }) })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "text-ui-fg-subtle grid grid-cols-2 items-center py-1", children: [
        /* @__PURE__ */ jsx(Text, { className: "txt-small-plus", children: t("fields.description") }),
        /* @__PURE__ */ jsx("div", { className: "flex items-center gap-1", children: /* @__PURE__ */ jsx(Text, { className: "txt-small", children: campaign.description || "-" }) })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "text-ui-fg-subtle grid grid-cols-2 items-center py-1", children: [
        /* @__PURE__ */ jsx(Text, { className: "txt-small-plus", children: t("campaigns.fields.start_date") }),
        /* @__PURE__ */ jsx("div", { className: "flex items-center gap-1", children: /* @__PURE__ */ jsx(Text, { className: "txt-small", children: campaign.starts_at?.toString() || "-" }) })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "text-ui-fg-subtle grid grid-cols-2 items-center py-1", children: [
        /* @__PURE__ */ jsx(Text, { className: "txt-small-plus", children: t("campaigns.fields.end_date") }),
        /* @__PURE__ */ jsx("div", { className: "flex items-center gap-1", children: /* @__PURE__ */ jsx(Text, { className: "txt-small", children: campaign.ends_at?.toString() || "-" }) })
      ] })
    ] }),
    /* @__PURE__ */ jsxs("div", { children: [
      /* @__PURE__ */ jsx(Heading, { level: "h2", className: "mb-4", children: t("campaigns.budget.details") }),
      /* @__PURE__ */ jsxs("div", { className: "text-ui-fg-subtle grid grid-cols-2 items-center py-1", children: [
        /* @__PURE__ */ jsx(Text, { className: "txt-small-plus font-", children: t("campaigns.budget.fields.type") }),
        /* @__PURE__ */ jsx("div", { className: "flex items-center gap-1", children: /* @__PURE__ */ jsx(Text, { className: "txt-small truncate", children: t(
          `campaigns.budget.type.${translationKeyMap[campaign.budget?.type]}.title`,
          {
            defaultValue: "-"
          }
        ) }) })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "text-ui-fg-subtle grid grid-cols-2 items-center py-1", children: [
        /* @__PURE__ */ jsx(Text, { className: "txt-small-plus", children: t("campaigns.budget.fields.currency") }),
        /* @__PURE__ */ jsx("div", { className: "flex items-center gap-1", children: /* @__PURE__ */ jsx(Text, { className: "txt-small", children: campaign?.budget?.currency_code || "-" }) })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "text-ui-fg-subtle grid grid-cols-2 items-center py-1", children: [
        /* @__PURE__ */ jsx(Text, { className: "txt-small-plus", children: t("campaigns.budget.fields.limit") }),
        /* @__PURE__ */ jsx("div", { className: "flex items-center gap-1", children: /* @__PURE__ */ jsx(Text, { className: "txt-small", children: campaign.budget?.limit || "-" }) })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "text-ui-fg-subtle grid grid-cols-2 items-center py-1", children: [
        /* @__PURE__ */ jsx(Text, { className: "txt-small-plus", children: campaign.budget?.type === "use_by_attribute" ? t("campaigns.fields.totalUsedByAttribute") : t("campaigns.budget.fields.used") }),
        /* @__PURE__ */ jsx("div", { className: "flex items-center gap-1", children: /* @__PURE__ */ jsx(Text, { className: "txt-small", children: campaign.budget?.used || "-" }) })
      ] })
    ] })
  ] });
};

// src/pages/promotions/promotion-add-campaign/components/add-campaign-promotion-form/add-campaign-promotion-form.tsx
import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
var EditPromotionSchema = zod.object({
  campaign_id: zod.string().optional().nullable(),
  campaign_choice: zod.enum(["none", "existing"]).optional()
});
var AddCampaignPromotionFields = ({
  form,
  withNewCampaign = true,
  promotionCurrencyCode
}) => {
  const { t } = useTranslation2();
  const direction = useDocumentDirection();
  const watchCampaignId = useWatch({
    control: form.control,
    name: "campaign_id"
  });
  const watchCampaignChoice = useWatch({
    control: form.control,
    name: "campaign_choice"
  });
  const campaignsCombobox = useComboboxData({
    queryFn: (params) => sdk.admin.campaigns.query({
      ...params
    }),
    queryKey: ["campaigns"],
    getOptions: (data) => data.campaigns.map((campaign) => ({
      label: campaign.name.toUpperCase(),
      value: campaign.id,
      disabled: campaign.budget?.currency_code && campaign.budget?.currency_code?.toLowerCase() !== promotionCurrencyCode?.toLowerCase()
      // also cannot add promotion which doesn't have currency defined to a campaign with a currency amount budget
    }))
  });
  const { campaign: selectedCampaign } = useCampaign(
    watchCampaignId,
    void 0,
    {
      enabled: !!watchCampaignId
    }
  );
  return /* @__PURE__ */ jsxs2("div", { className: "flex flex-col gap-y-8", "data-testid": "promotion-add-campaign-fields", children: [
    /* @__PURE__ */ jsx2(
      Form.Field,
      {
        control: form.control,
        name: "campaign_choice",
        render: ({ field }) => {
          return /* @__PURE__ */ jsxs2(Form.Item, { "data-testid": "promotion-add-campaign-form-campaign-choice-item", children: [
            /* @__PURE__ */ jsx2(Form.Label, { "data-testid": "promotion-add-campaign-form-campaign-choice-label", children: t("promotions.fields.campaign") }),
            /* @__PURE__ */ jsx2(Form.Control, { "data-testid": "promotion-add-campaign-form-campaign-choice-control", children: /* @__PURE__ */ jsxs2(
              RadioGroup,
              {
                dir: direction,
                className: "grid grid-cols-1 gap-3",
                ...field,
                value: field.value,
                onValueChange: field.onChange,
                "data-testid": "promotion-add-campaign-form-campaign-choice-radio-group",
                children: [
                  /* @__PURE__ */ jsx2(
                    RadioGroup.ChoiceBox,
                    {
                      value: "none",
                      label: t("promotions.form.campaign.none.title"),
                      description: t("promotions.form.campaign.none.description"),
                      "data-testid": "promotion-add-campaign-form-campaign-choice-option-none"
                    }
                  ),
                  /* @__PURE__ */ jsx2(
                    RadioGroup.ChoiceBox,
                    {
                      value: "existing",
                      label: t("promotions.form.campaign.existing.title"),
                      description: t(
                        "promotions.form.campaign.existing.description"
                      ),
                      "data-testid": "promotion-add-campaign-form-campaign-choice-option-existing"
                    }
                  ),
                  withNewCampaign && /* @__PURE__ */ jsx2(
                    RadioGroup.ChoiceBox,
                    {
                      value: "new",
                      label: t("promotions.form.campaign.new.title"),
                      description: t(
                        "promotions.form.campaign.new.description"
                      ),
                      "data-testid": "promotion-add-campaign-form-campaign-choice-option-new"
                    }
                  )
                ]
              }
            ) }),
            /* @__PURE__ */ jsx2(Form.ErrorMessage, { "data-testid": "promotion-add-campaign-form-campaign-choice-error" })
          ] });
        }
      }
    ),
    watchCampaignChoice === "existing" && /* @__PURE__ */ jsx2(
      Form.Field,
      {
        control: form.control,
        name: "campaign_id",
        render: ({ field: { onChange, ...field } }) => {
          return /* @__PURE__ */ jsxs2(Form.Item, { "data-testid": "promotion-add-campaign-form-campaign-id-item", children: [
            /* @__PURE__ */ jsx2(Form.Label, { tooltip: t("campaigns.fields.campaign_id.hint"), "data-testid": "promotion-add-campaign-form-campaign-id-label", children: t("promotions.form.campaign.existing.title") }),
            /* @__PURE__ */ jsx2(Form.Control, { "data-testid": "promotion-add-campaign-form-campaign-id-control", children: /* @__PURE__ */ jsx2(
              Combobox,
              {
                dir: direction,
                options: campaignsCombobox.options,
                searchValue: campaignsCombobox.searchValue,
                onSearchValueChange: campaignsCombobox.onSearchValueChange,
                onChange,
                ...field,
                "data-testid": "promotion-add-campaign-form-campaign-id-combobox"
              }
            ) }),
            !promotionCurrencyCode && /* @__PURE__ */ jsx2(Form.Hint, { "data-testid": "promotion-add-campaign-form-campaign-id-hint", children: t("promotions.form.campaign.existing.currencyHint") }),
            /* @__PURE__ */ jsx2(Form.ErrorMessage, { "data-testid": "promotion-add-campaign-form-campaign-id-error" })
          ] });
        }
      }
    ),
    watchCampaignChoice === "new" && /* @__PURE__ */ jsx2(CreateCampaignFormFields, { form, fieldScope: "campaign." }),
    /* @__PURE__ */ jsx2(CampaignDetails, { campaign: selectedCampaign })
  ] });
};
var AddCampaignPromotionForm = ({
  promotion
}) => {
  const { t } = useTranslation2();
  const { handleSuccess } = useRouteModal();
  const { campaign } = promotion;
  const originalId = campaign?.id;
  const form = useForm({
    defaultValues: {
      campaign_id: campaign?.id,
      campaign_choice: campaign?.id ? "existing" : "none"
    },
    resolver: zodResolver(EditPromotionSchema)
  });
  const { setValue } = form;
  const { mutateAsync, isPending } = useUpdatePromotion(promotion.id);
  const handleSubmit = form.handleSubmit(async (data) => {
    await mutateAsync(
      { campaign_id: data.campaign_id },
      {
        onSuccess: () => {
          toast.success(t("promotions.campaign.edit.successToast"));
          handleSuccess();
        },
        onError: (e) => {
          toast.error(e.message);
        }
      }
    );
  });
  const watchCampaignChoice = useWatch({
    control: form.control,
    name: "campaign_choice"
  });
  useEffect(() => {
    if (watchCampaignChoice === "none") {
      setValue("campaign_id", null);
    }
    if (watchCampaignChoice === "existing") {
      setValue("campaign_id", originalId);
    }
  }, [watchCampaignChoice, setValue, originalId]);
  return /* @__PURE__ */ jsx2(RouteDrawer.Form, { form, "data-testid": "promotion-add-campaign-form", children: /* @__PURE__ */ jsxs2(
    KeyboundForm,
    {
      onSubmit: handleSubmit,
      className: "flex size-full flex-col overflow-hidden",
      children: [
        /* @__PURE__ */ jsx2(RouteDrawer.Body, { className: "size-full overflow-auto", "data-testid": "promotion-add-campaign-form-body", children: /* @__PURE__ */ jsx2(
          AddCampaignPromotionFields,
          {
            form,
            withNewCampaign: false,
            promotionCurrencyCode: promotion.application_method?.currency_code
          }
        ) }),
        /* @__PURE__ */ jsx2(RouteDrawer.Footer, { "data-testid": "promotion-add-campaign-form-footer", children: /* @__PURE__ */ jsxs2("div", { className: "flex items-center justify-end gap-x-2", children: [
          /* @__PURE__ */ jsx2(RouteDrawer.Close, { asChild: true, children: /* @__PURE__ */ jsx2(Button, { size: "small", variant: "secondary", "data-testid": "promotion-add-campaign-form-cancel-button", children: t("actions.cancel") }) }),
          /* @__PURE__ */ jsx2(Button, { size: "small", type: "submit", isLoading: isPending, "data-testid": "promotion-add-campaign-form-save-button", children: t("actions.save") })
        ] }) })
      ]
    }
  ) });
};

export {
  AddCampaignPromotionFields,
  AddCampaignPromotionForm
};
