import {
  require_dist
} from "./chunk-ZZO3INVE.js";
import {
  MediaSchema
} from "./chunk-UBS6VEGB.js";
import "./chunk-UXD3VNBO.js";
import "./chunk-SMQT3ZNO.js";
import {
  SwitchBox
} from "./chunk-YVCBMOJG.js";
import "./chunk-ZMDE5HEV.js";
import "./chunk-TKGWSUEI.js";
import {
  KeyboundForm
} from "./chunk-U2ZFCAPX.js";
import {
  FileUpload
} from "./chunk-S2Q7PO7I.js";
import {
  RouteDrawer,
  useRouteModal
} from "./chunk-OV7R2AH5.js";
import {
  Form
} from "./chunk-3QSRE5LS.js";
import {
  useSeller,
  useUpdateSeller
} from "./chunk-M3YP3NX4.js";
import "./chunk-RHKRREUU.js";
import "./chunk-ZA2KFUFR.js";
import {
  uploadFilesQuery
} from "./chunk-RIN4CBRB.js";
import {
  __toESM
} from "./chunk-NBMM2TZK.js";

// src/pages/stores/store-edit/store-edit.tsx
import { Heading } 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 { Button, Input, Select, 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({
  name: zod.string().min(1),
  handle: zod.string().min(1),
  email: zod.string().email().optional().or(zod.literal("")),
  description: zod.string().optional().or(zod.literal("")),
  website_url: zod.string().url().optional().or(zod.literal("")),
  status: zod.nativeEnum(import_types.SellerStatus),
  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 StoreEditForm = ({ seller }) => {
  const { t } = useTranslation();
  const { handleSuccess } = useRouteModal();
  const form = useForm({
    defaultValues: {
      name: seller.name ?? "",
      handle: seller.handle ?? "",
      email: seller.email ?? "",
      description: seller.description ?? "",
      website_url: seller.website_url ?? "",
      status: seller.status ?? import_types.SellerStatus.PENDING_APPROVAL,
      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(
      {
        name: values.name,
        handle: values.handle,
        email: values.email || void 0,
        description: values.description || null,
        website_url: values.website_url || null,
        status: values.status,
        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 }]);
  };
  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: "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: "handle",
                render: ({ field }) => /* @__PURE__ */ jsxs(Form.Item, { children: [
                  /* @__PURE__ */ jsx(Form.Label, { children: t("fields.handle") }),
                  /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsx(Input, { ...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: "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: "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(Input, { ...field }) }),
                  /* @__PURE__ */ jsx(Form.ErrorMessage, {})
                ] })
              }
            ),
            /* @__PURE__ */ jsx(
              Form.Field,
              {
                control: form.control,
                name: "status",
                render: ({ field: { onChange, ref, ...field } }) => /* @__PURE__ */ jsxs(Form.Item, { children: [
                  /* @__PURE__ */ jsx(Form.Label, { children: t("fields.status") }),
                  /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsxs(Select, { onValueChange: onChange, ...field, children: [
                    /* @__PURE__ */ jsx(Select.Trigger, { ref, children: /* @__PURE__ */ jsx(Select.Value, {}) }),
                    /* @__PURE__ */ jsx(Select.Content, { children: Object.values(import_types.SellerStatus).map((status) => /* @__PURE__ */ jsx(Select.Item, { value: status, children: t(`stores.status.${status}`) }, status)) })
                  ] }) }),
                  /* @__PURE__ */ jsx(Form.ErrorMessage, {})
                ] })
              }
            )
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-y-4", children: [
            /* @__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,
                        fileSize: logoFile?.file?.size,
                        multiple: false,
                        label: t("products.media.uploadImagesLabel"),
                        hint: t("products.media.uploadImagesHint"),
                        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,
                        fileSize: bannerFile?.file?.size,
                        multiple: false,
                        label: t("products.media.uploadImagesLabel"),
                        hint: t("products.media.uploadImagesHint"),
                        hasError: !!form.formState.errors.bannerMedia,
                        formats: SUPPORTED_FORMATS,
                        onUploaded: onBannerUploaded,
                        onRemove: () => form.setValue("bannerMedia", [])
                      }
                    ) }),
                    /* @__PURE__ */ jsx(Form.ErrorMessage, {})
                  ] });
                }
              }
            )
          ] }),
          /* @__PURE__ */ jsx(
            SwitchBox,
            {
              control: form.control,
              name: "is_premium",
              label: t("fields.premium"),
              description: t("stores.premium.description")
            }
          )
        ] }),
        /* @__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(Heading, { className: "capitalize", children: t("stores.edit.header") }) }),
    !isLoading && seller && /* @__PURE__ */ jsx2(StoreEditForm, { seller })
  ] });
};
export {
  StoreEdit as Component
};
