import {
  HandleInput
} from "./chunk-HJ56YXBU.js";
import {
  currencies
} from "./chunk-IQPN4PZJ.js";
import {
  MediaSchema
} from "./chunk-MXGDKEU5.js";
import "./chunk-UXD3VNBO.js";
import "./chunk-SMQT3ZNO.js";
import {
  SwitchBox
} from "./chunk-2EME4AWX.js";
import "./chunk-VGM5UQRA.js";
import "./chunk-TKGWSUEI.js";
import {
  KeyboundForm
} from "./chunk-U2ZFCAPX.js";
import {
  FileUpload
} from "./chunk-4KX6CBJ4.js";
import {
  require_dist
} from "./chunk-ZZO3INVE.js";
import {
  RouteDrawer,
  useRouteModal
} from "./chunk-FWJLS7XD.js";
import {
  Form
} from "./chunk-3QSRE5LS.js";
import {
  useSeller,
  useUpdateSeller
} from "./chunk-LEG67A2R.js";
import "./chunk-RHKRREUU.js";
import "./chunk-ZA2KFUFR.js";
import {
  uploadFilesQuery
} from "./chunk-ZBWL72TB.js";
import {
  __toESM
} from "./chunk-NBMM2TZK.js";

// src/pages/stores/store-edit/store-edit.tsx
import { Heading as Heading2 } from "@medusajs/ui";
import { useTranslation as useTranslation2 } from "react-i18next";
import { useParams } from "react-router-dom";

// src/pages/stores/store-edit/components/store-edit-form.tsx
import { zodResolver } from "@hookform/resolvers/zod";
import i18n from "i18next";
import { InformationCircleSolid } from "@medusajs/icons";
import {
  Button,
  Heading,
  Input,
  Select,
  Text,
  Textarea,
  toast
} from "@medusajs/ui";
import { useFieldArray, useForm } from "react-hook-form";
import { useTranslation } from "react-i18next";
import * as zod from "zod";
import { useCallback } from "react";
var import_types = __toESM(require_dist(), 1);
import { jsx, jsxs } from "react/jsx-runtime";
var EditStoreSchema = zod.object({
  status: zod.nativeEnum(import_types.SellerStatus),
  name: zod.string().min(1, { message: i18n.t("stores.create.validation.nameRequired") }),
  description: zod.string().optional().or(zod.literal("")),
  handle: zod.string().optional().or(zod.literal("")),
  email: zod.string().min(1, { message: i18n.t("stores.create.validation.emailRequired") }).email({ message: i18n.t("stores.create.validation.emailInvalid") }),
  phone: zod.string().optional().or(zod.literal("")),
  website_url: zod.string().optional().or(zod.literal("")),
  is_premium: zod.boolean(),
  media: zod.array(MediaSchema).optional(),
  bannerMedia: zod.array(MediaSchema).optional()
});
var SUPPORTED_FORMATS = [
  "image/jpeg",
  "image/png",
  "image/gif",
  "image/webp",
  "image/heic",
  "image/svg+xml"
];
var SUPPORTED_FORMATS_FILE_EXTENSIONS = [
  ".jpeg",
  ".png",
  ".gif",
  ".webp",
  ".heic",
  ".svg"
];
var stripWebsiteProtocol = (url) => url ? url.replace(/^https?:\/\//i, "") : "";
var getFileNameFromUrl = (url) => {
  if (!url || url.startsWith("blob:")) return void 0;
  try {
    const pathname = new URL(url).pathname;
    const last = pathname.split("/").filter(Boolean).pop();
    return last ? decodeURIComponent(last) : void 0;
  } catch {
    const last = url.split("?")[0].split("/").filter(Boolean).pop();
    return last ? decodeURIComponent(last) : void 0;
  }
};
var ensureWebsiteProtocol = (url) => {
  const trimmed = url.trim();
  if (!trimmed) return null;
  if (/^https?:\/\//i.test(trimmed)) return trimmed;
  return `https://${trimmed}`;
};
var StoreEditForm = ({ seller }) => {
  const { t } = useTranslation();
  const { handleSuccess } = useRouteModal();
  const form = useForm({
    defaultValues: {
      status: seller.status ?? import_types.SellerStatus.OPEN,
      name: seller.name ?? "",
      description: seller.description ?? "",
      handle: seller.handle ?? "",
      email: seller.email ?? "",
      phone: seller.phone ?? "",
      website_url: stripWebsiteProtocol(seller.website_url),
      is_premium: seller.is_premium ?? false,
      media: seller.logo ? [{ id: "existing-logo", url: seller.logo, isThumbnail: false, file: null }] : [],
      bannerMedia: seller.banner ? [{ id: "existing-banner", url: seller.banner, isThumbnail: false, file: null }] : []
    },
    resolver: zodResolver(EditStoreSchema)
  });
  const { fields: logoFields } = useFieldArray({
    name: "media",
    control: form.control,
    keyName: "field_id"
  });
  const { fields: bannerFields } = useFieldArray({
    name: "bannerMedia",
    control: form.control,
    keyName: "field_id"
  });
  const { mutateAsync, isPending } = useUpdateSeller(seller.id);
  const handleSubmit = form.handleSubmit(async (values) => {
    let logoUrl = null;
    let bannerUrl = null;
    const newLogoFile = values.media?.find((m) => m.file);
    const newBannerFile = values.bannerMedia?.find((m) => m.file);
    try {
      if (newLogoFile) {
        const uploaded = await uploadFilesQuery([newLogoFile]);
        logoUrl = uploaded.files?.[0]?.url || null;
      } else if (values.media?.length) {
        logoUrl = values.media[0].url;
      }
      if (newBannerFile) {
        const uploaded = await uploadFilesQuery([newBannerFile]);
        bannerUrl = uploaded.files?.[0]?.url || null;
      } else if (values.bannerMedia?.length) {
        bannerUrl = values.bannerMedia[0].url;
      }
    } catch (error) {
      if (error instanceof Error) {
        toast.error(error.message);
      }
      return;
    }
    await mutateAsync(
      {
        status: values.status,
        name: values.name,
        handle: values.handle || void 0,
        email: values.email || void 0,
        phone: values.phone || null,
        description: values.description || null,
        website_url: ensureWebsiteProtocol(values.website_url ?? ""),
        is_premium: values.is_premium,
        logo: logoUrl,
        banner: bannerUrl
      },
      {
        onSuccess: () => {
          toast.success(
            t("stores.edit.successToast", { name: values.name ?? values.email })
          );
          handleSuccess();
        },
        onError: (error) => {
          toast.error(error.message);
        }
      }
    );
  });
  const hasInvalidFiles = useCallback(
    (fileList, fieldName) => {
      const invalidFile = fileList.find(
        (f) => !SUPPORTED_FORMATS.includes(f.file.type)
      );
      if (invalidFile) {
        form.setError(fieldName, {
          type: "invalid_file",
          message: t("products.media.invalidFileType", {
            name: invalidFile.file.name,
            types: SUPPORTED_FORMATS_FILE_EXTENSIONS.join(", ")
          })
        });
        return true;
      }
      return false;
    },
    [form, t]
  );
  const onLogoUploaded = (files) => {
    form.clearErrors("media");
    if (hasInvalidFiles(files, "media")) {
      return;
    }
    form.setValue("media", [{ ...files[0], isThumbnail: false }]);
  };
  const onBannerUploaded = (files) => {
    form.clearErrors("bannerMedia");
    if (hasInvalidFiles(files, "bannerMedia")) {
      return;
    }
    form.setValue("bannerMedia", [{ ...files[0], isThumbnail: false }]);
  };
  const currencyCode = seller.currency_code?.toUpperCase() ?? "";
  const currencyName = currencies[currencyCode]?.name ?? currencyCode;
  return /* @__PURE__ */ jsx(RouteDrawer.Form, { form, children: /* @__PURE__ */ jsxs(
    KeyboundForm,
    {
      onSubmit: handleSubmit,
      className: "flex flex-1 flex-col overflow-hidden",
      children: [
        /* @__PURE__ */ jsxs(RouteDrawer.Body, { className: "flex flex-col gap-y-8 overflow-y-auto", children: [
          /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-y-4", children: [
            /* @__PURE__ */ jsx(
              Form.Field,
              {
                control: form.control,
                name: "status",
                render: ({ field: { onChange, value, ref: _ref, ...field } }) => /* @__PURE__ */ jsxs(Form.Item, { children: [
                  /* @__PURE__ */ jsx(Form.Label, { children: t("fields.status") }),
                  /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsxs(Select, { ...field, value, onValueChange: onChange, children: [
                    /* @__PURE__ */ jsx(Select.Trigger, { children: /* @__PURE__ */ jsx(Select.Value, {}) }),
                    /* @__PURE__ */ jsxs(Select.Content, { children: [
                      /* @__PURE__ */ jsx(Select.Item, { value: import_types.SellerStatus.OPEN, children: t("stores.status.open") }),
                      /* @__PURE__ */ jsx(Select.Item, { value: import_types.SellerStatus.PENDING_APPROVAL, children: t("stores.status.pendingApproval") }),
                      /* @__PURE__ */ jsx(Select.Item, { value: import_types.SellerStatus.SUSPENDED, children: t("stores.status.suspended") })
                    ] })
                  ] }) }),
                  /* @__PURE__ */ jsx(Form.ErrorMessage, {})
                ] })
              }
            ),
            /* @__PURE__ */ jsx(
              Form.Field,
              {
                control: form.control,
                name: "name",
                render: ({ field }) => /* @__PURE__ */ jsxs(Form.Item, { children: [
                  /* @__PURE__ */ jsx(Form.Label, { children: t("fields.name") }),
                  /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsx(Input, { ...field }) }),
                  /* @__PURE__ */ jsx(Form.ErrorMessage, {})
                ] })
              }
            ),
            /* @__PURE__ */ jsx(
              Form.Field,
              {
                control: form.control,
                name: "description",
                render: ({ field }) => /* @__PURE__ */ jsxs(Form.Item, { children: [
                  /* @__PURE__ */ jsx(Form.Label, { optional: true, children: t("fields.description") }),
                  /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsx(Textarea, { ...field }) }),
                  /* @__PURE__ */ jsx(Form.ErrorMessage, {})
                ] })
              }
            ),
            /* @__PURE__ */ jsx(
              Form.Field,
              {
                control: form.control,
                name: "handle",
                render: ({ field }) => /* @__PURE__ */ jsxs(Form.Item, { children: [
                  /* @__PURE__ */ jsx(Form.Label, { optional: true, tooltip: t("stores.handleTooltip"), children: t("fields.handle") }),
                  /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsx(HandleInput, { ...field }) }),
                  /* @__PURE__ */ jsx(Form.ErrorMessage, {})
                ] })
              }
            ),
            /* @__PURE__ */ jsx(
              Form.Field,
              {
                control: form.control,
                name: "email",
                render: ({ field }) => /* @__PURE__ */ jsxs(Form.Item, { children: [
                  /* @__PURE__ */ jsx(Form.Label, { children: t("fields.email") }),
                  /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsx(Input, { type: "email", ...field }) }),
                  /* @__PURE__ */ jsx(Form.ErrorMessage, {})
                ] })
              }
            ),
            /* @__PURE__ */ jsx(
              Form.Field,
              {
                control: form.control,
                name: "phone",
                render: ({ field }) => /* @__PURE__ */ jsxs(Form.Item, { children: [
                  /* @__PURE__ */ jsx(Form.Label, { optional: true, children: t("fields.phone") }),
                  /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsx(Input, { type: "tel", ...field }) }),
                  /* @__PURE__ */ jsx(Form.ErrorMessage, {})
                ] })
              }
            ),
            /* @__PURE__ */ jsx(
              Form.Field,
              {
                control: form.control,
                name: "website_url",
                render: ({ field }) => /* @__PURE__ */ jsxs(Form.Item, { children: [
                  /* @__PURE__ */ jsx(Form.Label, { optional: true, children: t("fields.website") }),
                  /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsx(HandleInput, { prefix: "https://", ...field }) }),
                  /* @__PURE__ */ jsx(Form.ErrorMessage, {})
                ] })
              }
            ),
            /* @__PURE__ */ jsxs(Form.Item, { children: [
              /* @__PURE__ */ jsx(Form.Label, { children: t("fields.currency") }),
              /* @__PURE__ */ jsxs(Select, { value: currencyCode, disabled: true, children: [
                /* @__PURE__ */ jsx(Select.Trigger, { children: /* @__PURE__ */ jsx(Select.Value, { placeholder: currencyName, children: currencyName }) }),
                /* @__PURE__ */ jsx(Select.Content, { children: /* @__PURE__ */ jsx(Select.Item, { value: currencyCode, children: currencyName }) })
              ] })
            ] })
          ] }),
          /* @__PURE__ */ jsx(
            SwitchBox,
            {
              control: form.control,
              name: "is_premium",
              label: t("fields.premium"),
              description: t("stores.premium.description")
            }
          ),
          /* @__PURE__ */ jsx("div", { className: "border-ui-border-base border-t" }),
          /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-y-4", children: [
            /* @__PURE__ */ jsx(Heading, { level: "h2", children: t("stores.edit.mediaHeading") }),
            /* @__PURE__ */ jsx(
              Form.Field,
              {
                name: "media",
                control: form.control,
                render: () => {
                  const logoFile = logoFields[0];
                  const previewUrl = logoFile?.url || null;
                  return /* @__PURE__ */ jsxs(Form.Item, { children: [
                    /* @__PURE__ */ jsx(Form.Label, { optional: true, children: t("store.logo") }),
                    /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsx(
                      FileUpload,
                      {
                        uploadedImage: previewUrl,
                        fileName: logoFile?.file?.name ?? getFileNameFromUrl(logoFile?.url),
                        fileSize: logoFile?.file?.size,
                        multiple: false,
                        label: t("stores.edit.uploadLogoLabel"),
                        hint: t("stores.edit.uploadLogoHint"),
                        hasError: !!form.formState.errors.media,
                        formats: SUPPORTED_FORMATS,
                        onUploaded: onLogoUploaded,
                        onRemove: () => form.setValue("media", [])
                      }
                    ) }),
                    /* @__PURE__ */ jsx(Form.ErrorMessage, {})
                  ] });
                }
              }
            ),
            /* @__PURE__ */ jsx(
              Form.Field,
              {
                name: "bannerMedia",
                control: form.control,
                render: () => {
                  const bannerFile = bannerFields[0];
                  const previewUrl = bannerFile?.url || null;
                  return /* @__PURE__ */ jsxs(Form.Item, { children: [
                    /* @__PURE__ */ jsx(Form.Label, { optional: true, children: t("store.banner") }),
                    /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsx(
                      FileUpload,
                      {
                        uploadedImage: previewUrl,
                        fileName: bannerFile?.file?.name ?? getFileNameFromUrl(bannerFile?.url),
                        fileSize: bannerFile?.file?.size,
                        multiple: false,
                        label: t("stores.edit.uploadBannerLabel"),
                        hint: t("stores.edit.uploadBannerHint"),
                        hasError: !!form.formState.errors.bannerMedia,
                        formats: SUPPORTED_FORMATS,
                        onUploaded: onBannerUploaded,
                        onRemove: () => form.setValue("bannerMedia", [])
                      }
                    ) }),
                    /* @__PURE__ */ jsx(Form.ErrorMessage, {})
                  ] });
                }
              }
            ),
            /* @__PURE__ */ jsxs("div", { className: "bg-ui-bg-component shadow-elevation-card-rest flex items-start gap-x-2 rounded-lg px-4 py-3", children: [
              /* @__PURE__ */ jsx(InformationCircleSolid, { className: "text-ui-fg-interactive mt-[2px]" }),
              /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-y-0.5", children: [
                /* @__PURE__ */ jsx(Text, { size: "small", weight: "plus", className: "text-ui-fg-base", children: t("stores.edit.mediaTipLabel") }),
                /* @__PURE__ */ jsx(Text, { size: "small", className: "text-ui-fg-subtle", children: t("stores.edit.mediaTipBody") })
              ] })
            ] })
          ] })
        ] }),
        /* @__PURE__ */ jsx(RouteDrawer.Footer, { children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-end gap-x-2", children: [
          /* @__PURE__ */ jsx(RouteDrawer.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") })
        ] }) })
      ]
    }
  ) });
};

// src/pages/stores/store-edit/store-edit.tsx
import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
var StoreEdit = () => {
  const { id } = useParams();
  const { t } = useTranslation2();
  const { seller, isLoading, isError, error } = useSeller(id);
  if (isError) {
    throw error;
  }
  return /* @__PURE__ */ jsxs2(RouteDrawer, { children: [
    /* @__PURE__ */ jsx2(RouteDrawer.Header, { children: /* @__PURE__ */ jsx2(Heading2, { className: "capitalize", children: t("stores.edit.header") }) }),
    !isLoading && seller && /* @__PURE__ */ jsx2(StoreEditForm, { seller })
  ] });
};
export {
  StoreEdit as Component
};
