import "./chunk-IUCDCPJU.mjs";
import {
  KeyboundForm
} from "./chunk-6HTZNHPT.mjs";
import "./chunk-OV6YUU3D.mjs";
import {
  RouteFocusModal,
  useRouteModal
} from "./chunk-ULMMKZ3U.mjs";
import {
  Form
} from "./chunk-OBQI23QM.mjs";
import "./chunk-OW2UL5FI.mjs";
import "./chunk-5DUV4AET.mjs";
import "./chunk-FAB3VINY.mjs";
import "./chunk-Q7YBE4IP.mjs";
import "./chunk-HI6URQ7H.mjs";
import "./chunk-6CLQKVAU.mjs";
import "./chunk-KI7TOXBR.mjs";
import "./chunk-QBIQEVTU.mjs";
import "./chunk-WAXMT4IY.mjs";
import "./chunk-DYDGGABK.mjs";
import "./chunk-LGNTHZ5Y.mjs";
import "./chunk-CN7JXSGW.mjs";
import "./chunk-AO2USOOE.mjs";
import "./chunk-KWWLGCSY.mjs";
import "./chunk-5AFMB7XQ.mjs";
import "./chunk-5U6AZEO7.mjs";
import "./chunk-A63RZVX6.mjs";
import "./chunk-HBXV7ENS.mjs";
import {
  useCreateOrderShipment,
  useOrder
} from "./chunk-ZBMENGLV.mjs";
import "./chunk-LGLPAUIO.mjs";
import "./chunk-CDORR33H.mjs";
import "./chunk-DE44HCDH.mjs";
import "./chunk-MUOBXNL6.mjs";
import "./chunk-BEQ5XTWH.mjs";
import "./chunk-HP2JH45P.mjs";
import "./chunk-VCSSQVPD.mjs";
import "./chunk-SQDIZZDW.mjs";
import "./chunk-LA2ILUXH.mjs";
import "./chunk-7AXHHXCX.mjs";
import "./chunk-FXYH54JP.mjs";
import "./chunk-774WSTCC.mjs";
import "./chunk-NFEK63OE.mjs";
import "./chunk-QZ7TP4HQ.mjs";

// src/routes/orders/order-create-shipment/order-create-shipment.tsx
import { useParams } from "react-router-dom";

// src/routes/orders/order-create-shipment/components/order-create-shipment-form/order-create-shipment-form.tsx
import { zodResolver } from "@hookform/resolvers/zod";
import { useTranslation } from "react-i18next";
import { Button, clx, Heading, Input, Switch, toast } from "@medusajs/ui";
import { useFieldArray, useForm } from "react-hook-form";

// src/routes/orders/order-create-shipment/components/order-create-shipment-form/constants.ts
import { z } from "zod";
var CreateShipmentSchema = z.object({
  labels: z.array(
    z.object({
      tracking_number: z.string(),
      // TODO: this 2 are not optional in the API
      tracking_url: z.string().optional(),
      label_url: z.string().optional()
    })
  ),
  send_notification: z.boolean().optional()
});

// src/routes/orders/order-create-shipment/components/order-create-shipment-form/order-create-shipment-form.tsx
import { jsx, jsxs } from "react/jsx-runtime";
function OrderCreateShipmentForm({
  order,
  fulfillment
}) {
  const { t } = useTranslation();
  const { handleSuccess } = useRouteModal();
  const { mutateAsync: createShipment, isPending: isMutating } = useCreateOrderShipment(order.id, fulfillment?.id ?? "");
  const form = useForm({
    defaultValues: {
      send_notification: !order.no_notification
    },
    resolver: zodResolver(CreateShipmentSchema)
  });
  const { fields: labels, append } = useFieldArray({
    name: "labels",
    control: form.control
  });
  const handleSubmit = form.handleSubmit(async (data) => {
    const addedLabels = data.labels.filter((l) => !!l.tracking_number || !!l.tracking_url || !!l.label_url).map((l) => ({
      tracking_number: l.tracking_number,
      tracking_url: l.tracking_url || "#",
      label_url: l.label_url || "#"
    }));
    await createShipment(
      {
        items: fulfillment?.items?.filter((i) => !!i.line_item_id).map((i) => ({
          id: i.line_item_id,
          quantity: i.quantity
        })) || [],
        labels: [...addedLabels, ...fulfillment?.labels || []],
        no_notification: !data.send_notification
      },
      {
        onSuccess: () => {
          toast.success(t("orders.shipment.toastCreated"));
          handleSuccess(`/orders/${order.id}`);
        },
        onError: (e) => {
          toast.error(e.message);
        }
      }
    );
  });
  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, {}),
        /* @__PURE__ */ jsx(RouteFocusModal.Body, { className: "flex h-full w-full flex-col items-center divide-y overflow-y-auto", children: /* @__PURE__ */ jsx("div", { className: "flex size-full flex-col items-center overflow-auto p-16", children: /* @__PURE__ */ jsx("div", { className: "flex w-full max-w-[736px] flex-col justify-center px-2 pb-2", children: /* @__PURE__ */ jsxs("div", { className: "flex flex-col divide-y", children: [
          /* @__PURE__ */ jsxs("div", { className: "flex flex-1 flex-col", children: [
            /* @__PURE__ */ jsx(Heading, { className: "mb-4", children: t("orders.shipment.title") }),
            /* @__PURE__ */ jsx("div", { className: "flex flex-col max-md:gap-y-2 max-md:divide-y", children: labels.map((label, index) => /* @__PURE__ */ jsxs(
              "div",
              {
                className: clx(
                  "grid grid-cols-1 gap-x-4 md:grid-cols-3",
                  { "max-md:pt-4": index > 0 }
                ),
                children: [
                  /* @__PURE__ */ jsx(
                    Form.Field,
                    {
                      control: form.control,
                      name: `labels.${index}.tracking_number`,
                      render: ({ field }) => {
                        return /* @__PURE__ */ jsxs(Form.Item, { className: "mb-2", children: [
                          /* @__PURE__ */ jsx(
                            Form.Label,
                            {
                              className: clx({ "md:hidden": index > 0 }),
                              children: t("orders.shipment.trackingNumber")
                            }
                          ),
                          /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsx(Input, { ...field, placeholder: "123-456-789" }) }),
                          /* @__PURE__ */ jsx(Form.ErrorMessage, {})
                        ] });
                      }
                    }
                  ),
                  /* @__PURE__ */ jsx(
                    Form.Field,
                    {
                      control: form.control,
                      name: `labels.${index}.tracking_url`,
                      render: ({ field }) => {
                        return /* @__PURE__ */ jsxs(Form.Item, { className: "mb-2", children: [
                          /* @__PURE__ */ jsx(
                            Form.Label,
                            {
                              className: clx({ "md:hidden": index > 0 }),
                              children: t("orders.shipment.trackingUrl")
                            }
                          ),
                          /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsx(
                            Input,
                            {
                              ...field,
                              placeholder: "https://example.com/tracking/123"
                            }
                          ) }),
                          /* @__PURE__ */ jsx(Form.ErrorMessage, {})
                        ] });
                      }
                    }
                  ),
                  /* @__PURE__ */ jsx(
                    Form.Field,
                    {
                      control: form.control,
                      name: `labels.${index}.label_url`,
                      render: ({ field }) => {
                        return /* @__PURE__ */ jsxs(Form.Item, { className: "mb-2", children: [
                          /* @__PURE__ */ jsx(
                            Form.Label,
                            {
                              className: clx({ "md:hidden": index > 0 }),
                              children: t("orders.shipment.labelUrl")
                            }
                          ),
                          /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsx(
                            Input,
                            {
                              ...field,
                              placeholder: "https://example.com/label/123"
                            }
                          ) }),
                          /* @__PURE__ */ jsx(Form.ErrorMessage, {})
                        ] });
                      }
                    }
                  )
                ]
              },
              label.id
            )) }),
            /* @__PURE__ */ jsx(
              Button,
              {
                type: "button",
                onClick: () => append({
                  tracking_number: "",
                  label_url: "",
                  tracking_url: ""
                }),
                className: "mt-2 self-end",
                variant: "secondary",
                children: t("orders.shipment.addTracking")
              }
            )
          ] }),
          /* @__PURE__ */ jsx("div", { className: "mt-8 pt-8 ", children: /* @__PURE__ */ jsx(
            Form.Field,
            {
              control: form.control,
              name: "send_notification",
              render: ({ field: { onChange, value, ...field } }) => {
                return /* @__PURE__ */ jsxs(Form.Item, { children: [
                  /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
                    /* @__PURE__ */ jsx(Form.Label, { children: t("orders.shipment.sendNotification") }),
                    /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsx(
                      Switch,
                      {
                        dir: "ltr",
                        className: "rtl:rotate-180",
                        checked: !!value,
                        onCheckedChange: onChange,
                        ...field
                      }
                    ) }) })
                  ] }),
                  /* @__PURE__ */ jsx(Form.Hint, { className: "!mt-1", children: t("orders.shipment.sendNotificationHint") }),
                  /* @__PURE__ */ jsx(Form.ErrorMessage, {})
                ] });
              }
            }
          ) })
        ] }) }) }) }),
        /* @__PURE__ */ jsxs(RouteFocusModal.Footer, { 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: isMutating, children: t("actions.save") })
        ] })
      ]
    }
  ) });
}

// src/routes/orders/order-create-shipment/order-create-shipment.tsx
import { jsx as jsx2 } from "react/jsx-runtime";
function OrderCreateShipment() {
  const { id, f_id } = useParams();
  const { order, isLoading, isError, error } = useOrder(id, {
    fields: "*fulfillments,*fulfillments.items,*fulfillments.labels,no_notification"
  });
  if (isError) {
    throw error;
  }
  const ready = !isLoading && order;
  const extendedOrder = order;
  return /* @__PURE__ */ jsx2(RouteFocusModal, { children: ready && /* @__PURE__ */ jsx2(
    OrderCreateShipmentForm,
    {
      order: extendedOrder,
      fulfillment: extendedOrder.fulfillments?.find((f) => f.id === f_id)
    }
  ) });
}
export {
  OrderCreateShipment as Component
};
