"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { useRouter } from "next/navigation";
import { Page, PageBody } from "@open-mercato/ui/backend/Page";
import { CrudForm } from "@open-mercato/ui/backend/CrudForm";
import { createCrud } from "@open-mercato/ui/backend/utils/crud";
import { createCrudFormError } from "@open-mercato/ui/backend/utils/serverErrors";
import { collectCustomFieldValues } from "@open-mercato/ui/backend/utils/customFieldValues";
import { apiCall, readApiResultOrThrow } from "@open-mercato/ui/backend/utils/apiCall";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { ErrorMessage, RecordNotFoundState } from "@open-mercato/ui/backend/detail";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { E } from "../../../../../../../../generated/entities.ids.generated.js";
import {
  createVariantInitialValues,
  normalizeOptionSchema,
  findInvalidVariantPriceKinds
} from "@open-mercato/core/modules/catalog/components/products/variantForm";
import {
  normalizePriceKindSummary
} from "@open-mercato/core/modules/catalog/components/products/productForm";
import { parseNumericInput } from "@open-mercato/core/modules/catalog/components/products/productFormUtils";
import {
  VariantBasicsSection,
  VariantOptionValuesSection,
  VariantDimensionsSection,
  VariantMetadataSection,
  VariantPricesSection,
  VariantMediaSection
} from "@open-mercato/core/modules/catalog/components/products/VariantBuilder";
import { buildAttachmentImageUrl, slugifyAttachmentFileName } from "@open-mercato/core/modules/attachments/lib/imageUrls";
import { fetchOptionSchemaTemplate } from "../../../optionSchemaClient.js";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("catalog");
function CreateVariantPage({ params }) {
  const productId = params?.productId ? String(params.productId) : null;
  const t = useT();
  const router = useRouter();
  const [optionDefinitions, setOptionDefinitions] = React.useState([]);
  const [priceKinds, setPriceKinds] = React.useState([]);
  const [taxRates, setTaxRates] = React.useState([]);
  const [initialValues, setInitialValues] = React.useState(null);
  const [productTitle, setProductTitle] = React.useState("");
  const [productTaxRateId, setProductTaxRateId] = React.useState(null);
  const [productTaxRate, setProductTaxRate] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState(null);
  const [isNotFound, setIsNotFound] = React.useState(false);
  React.useEffect(() => {
    const loadPriceKinds = async () => {
      try {
        const payload = await readApiResultOrThrow(
          "/api/catalog/price-kinds?pageSize=100",
          void 0,
          { errorMessage: t("catalog.priceKinds.errors.load", "Failed to load price kinds.") }
        );
        const items = Array.isArray(payload.items) ? payload.items : [];
        setPriceKinds(items.map((item) => normalizePriceKindSummary(item)).filter((item) => !!item));
      } catch (err) {
        logger.error("catalog.price-kinds.fetch failed", { err });
        setPriceKinds([]);
      }
    };
    loadPriceKinds().catch(() => {
    });
  }, [t]);
  React.useEffect(() => {
    const loadTaxRates = async () => {
      try {
        const payload = await readApiResultOrThrow(
          "/api/sales/tax-rates?pageSize=200",
          void 0,
          { errorMessage: t("catalog.products.create.taxRates.error", "Failed to load tax rates."), fallback: { items: [] } }
        );
        const items = Array.isArray(payload.items) ? payload.items : [];
        setTaxRates(
          items.map((item) => {
            const rawRate = typeof item.rate === "number" ? item.rate : Number(item.rate ?? Number.NaN);
            return {
              id: String(item.id),
              name: typeof item.name === "string" && item.name.trim().length ? item.name : t("catalog.products.create.taxRates.unnamed", "Untitled tax rate"),
              code: typeof item.code === "string" && item.code.trim().length ? item.code : null,
              rate: Number.isFinite(rawRate) ? rawRate : null,
              isDefault: Boolean(
                typeof item.isDefault === "boolean" ? item.isDefault : typeof item.is_default === "boolean" ? item.is_default : false
              )
            };
          })
        );
      } catch (err) {
        logger.error("sales.tax-rates.fetch failed", { err });
        setTaxRates([]);
      }
    };
    loadTaxRates().catch(() => {
    });
  }, [t]);
  React.useEffect(() => {
    if (!productId) return;
    let cancelled = false;
    async function load() {
      setLoading(true);
      setError(null);
      setIsNotFound(false);
      try {
        const res = await apiCall(
          `/api/catalog/products?id=${encodeURIComponent(productId)}&page=1&pageSize=1`
        );
        if (!res.ok) throw new Error(t("catalog.variants.form.errors.load", "Failed to load product context."));
        const record = Array.isArray(res.result?.items) ? res.result?.items?.[0] : void 0;
        if (!record) {
          if (!cancelled) setIsNotFound(true);
          return;
        }
        const metadata = record.metadata ?? {};
        const taxRateId = typeof record.tax_rate_id === "string" ? record.tax_rate_id : typeof record.taxRateId === "string" ? record.taxRateId : null;
        const taxRateValueRaw = typeof record.tax_rate === "number" ? record.tax_rate : typeof record.tax_rate === "string" ? Number(record.tax_rate) : typeof record.taxRate === "number" ? record.taxRate : typeof record.taxRate === "string" ? Number(record.taxRate) : null;
        const taxRateValue = Number.isFinite(taxRateValueRaw) ? Number(taxRateValueRaw) : null;
        const optionSchemaId = typeof record.option_schema_id === "string" ? record.option_schema_id : typeof record.optionSchemaId === "string" ? record.optionSchemaId : null;
        let schemaSource = metadata.optionSchema ?? metadata.option_schema;
        if (optionSchemaId) {
          const template = await fetchOptionSchemaTemplate(optionSchemaId);
          if (template?.schema?.options) {
            schemaSource = template.schema.options.map((option) => ({
              code: option.code,
              label: option.label,
              values: Array.isArray(option.choices) ? option.choices.map((choice) => ({ id: choice.code ?? void 0, label: choice.label ?? choice.code ?? "" })) : []
            }));
          }
        }
        if (!cancelled) {
          setOptionDefinitions(normalizeOptionSchema(schemaSource));
          setProductTitle(typeof record.title === "string" ? record.title : "");
          setProductTaxRateId(taxRateId);
          setProductTaxRate(taxRateValue);
          const base = createVariantInitialValues();
          setInitialValues(base);
        }
      } catch (err) {
        logger.error("catalog.variants.loadProduct failed", { err });
        if (!cancelled) {
          const message = err instanceof Error && err.message ? err.message : t("catalog.variants.form.errors.load", "Failed to load product context.");
          setError(message);
        }
      } finally {
        if (!cancelled) setLoading(false);
      }
    }
    load();
    return () => {
      cancelled = true;
    };
  }, [productId, t]);
  const groups = React.useMemo(() => {
    const list = [
      {
        id: "general",
        column: 1,
        title: t("catalog.variants.form.general", "General"),
        component: ({ values, setValue, errors }) => /* @__PURE__ */ jsx(VariantBasicsSection, { values, setValue, errors })
      },
      {
        id: "metadata",
        column: 1,
        title: t("catalog.products.edit.metadata.title", "Metadata"),
        description: t("catalog.products.edit.metadata.hint", "Attach structured key/value pairs for integrations."),
        component: ({ values, setValue }) => /* @__PURE__ */ jsx(VariantMetadataSection, { values, setValue, showIntro: false, embedded: true })
      },
      {
        id: "prices",
        column: 1,
        title: t("catalog.variants.form.pricesLabel", "Prices"),
        description: t("catalog.variants.form.pricesHint", "Populate list prices per price kind."),
        component: ({ values, setValue }) => /* @__PURE__ */ jsx(
          VariantPricesSection,
          {
            values,
            setValue,
            priceKinds,
            taxRates,
            showHeader: false,
            embedded: true
          }
        )
      },
      {
        id: "media",
        column: 1,
        title: t("catalog.variants.form.media", "Media"),
        component: ({ values, setValue }) => /* @__PURE__ */ jsx(VariantMediaSection, { values, setValue, showLabel: false })
      }
    ];
    if (optionDefinitions.length) {
      list.push({
        id: "options",
        column: 2,
        title: t("catalog.variants.form.options", "Option values"),
        component: ({ values, setValue }) => /* @__PURE__ */ jsx(
          VariantOptionValuesSection,
          {
            values,
            setValue,
            optionDefinitions,
            showHeading: false
          }
        )
      });
    }
    list.push({
      id: "dimensions",
      column: 2,
      title: t("catalog.variants.form.dimensions", "Dimensions & weight"),
      component: ({ values, setValue }) => /* @__PURE__ */ jsx(VariantDimensionsSection, { values, setValue, showHeading: false })
    });
    list.push({
      id: "custom",
      column: 2,
      title: t("catalog.variants.form.customFields", "Custom attributes"),
      kind: "customFields"
    });
    return list;
  }, [optionDefinitions, priceKinds, t, taxRates]);
  if (!productId) {
    return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(ErrorMessage, { label: t("catalog.variants.form.errors.productMissing", "Product identifier is missing.") }) }) });
  }
  if (isNotFound) {
    return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(
      RecordNotFoundState,
      {
        label: t("catalog.products.edit.errors.notFound", "Product not found."),
        backHref: "/backend/catalog/products",
        backLabel: t("catalog.products.edit.actions.backToList", "Back to products")
      }
    ) }) });
  }
  const formTitle = productTitle ? t("catalog.variants.form.createTitleFor", "Create variant for {{title}}").replace("{{title}}", productTitle) : t("catalog.variants.form.createTitle", "Create variant");
  return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsxs(PageBody, { children: [
    error ? /* @__PURE__ */ jsx(ErrorMessage, { label: error, className: "mb-4" }) : null,
    /* @__PURE__ */ jsx(
      CrudForm,
      {
        title: formTitle,
        backHref: `/backend/catalog/products/${productId}`,
        fields: [],
        groups,
        entityId: E.catalog.catalog_product_variant,
        customFieldsetBindings: { [E.catalog.catalog_product_variant]: { valueKey: "customFieldsetCode" } },
        initialValues: initialValues ?? void 0,
        isLoading: loading,
        loadingMessage: t("catalog.variants.form.loading", "Loading form..."),
        submitLabel: t("catalog.variants.form.createAction", "Create variant"),
        cancelHref: `/backend/catalog/products/${productId}`,
        onSubmit: async (values) => {
          const name = values.name?.trim();
          if (!name) {
            const message = t("catalog.variants.form.errors.nameRequired", "Provide the variant name.");
            throw createCrudFormError(message, { name: message });
          }
          const invalidPriceKinds = findInvalidVariantPriceKinds(priceKinds, values.prices);
          if (invalidPriceKinds.length) {
            const message = t("catalog.variants.form.errors.invalidPrice", "Provide a valid non-negative price.");
            throw createCrudFormError(message, { prices: message });
          }
          const resolveTaxRateValue = (taxRateId) => {
            if (!taxRateId) return null;
            const match = taxRates.find((rate) => rate.id === taxRateId);
            return typeof match?.rate === "number" && Number.isFinite(match.rate) ? match.rate : null;
          };
          const resolvedTaxRateId = values.taxRateId ?? productTaxRateId ?? null;
          const resolvedTaxRateValue = values.taxRateId && resolvedTaxRateId ? resolveTaxRateValue(resolvedTaxRateId) : productTaxRateId ? resolveTaxRateValue(productTaxRateId) ?? productTaxRate : productTaxRate ?? null;
          const metadata = typeof values.metadata === "object" && values.metadata ? { ...values.metadata } : {};
          const defaultMediaEntry = values.defaultMediaId ? (Array.isArray(values.mediaItems) ? values.mediaItems : []).find((item) => item.id === values.defaultMediaId) : null;
          const defaultMediaUrl = defaultMediaEntry ? buildAttachmentImageUrl(defaultMediaEntry.id, {
            slug: slugifyAttachmentFileName(defaultMediaEntry.fileName)
          }) : null;
          const payload = {
            productId,
            name,
            sku: values.sku?.trim() || void 0,
            barcode: values.barcode?.trim() || void 0,
            gtinType: values.gtinType ?? null,
            hsCode: values.hsCode?.trim() || null,
            isDefault: Boolean(values.isDefault),
            isActive: values.isActive !== false,
            optionValues: Object.keys(values.optionValues ?? {}).length ? values.optionValues : void 0,
            metadata,
            defaultMediaId: values.defaultMediaId ?? void 0,
            defaultMediaUrl: defaultMediaUrl ?? void 0,
            customFieldsetCode: values.customFieldsetCode?.trim().length ? values.customFieldsetCode : void 0,
            taxRateId: resolvedTaxRateId,
            taxRate: resolvedTaxRateValue
          };
          Reflect.deleteProperty(payload, "id");
          const customFields = collectCustomFieldValues(values);
          if (Object.keys(customFields).length) payload.customFields = customFields;
          const { result } = await createCrud("catalog/variants", payload);
          const variantId = result?.variantId ?? result?.id;
          if (!variantId) {
            throw createCrudFormError(t("catalog.variants.form.errors.idMissing", "Variant id missing after create."));
          }
          await transferVariantMedia({
            draftId: values.mediaDraftId,
            variantId,
            mediaItems: Array.isArray(values.mediaItems) ? values.mediaItems : []
          });
          await syncVariantPrices({
            priceKinds,
            priceDrafts: values.prices ?? {},
            productId,
            variantId,
            taxRates,
            taxRateId: values.taxRateId,
            productTaxRateId,
            productTaxRate
          });
          flash(t("catalog.variants.form.createSuccess", "Variant created."), "success");
          router.push(`/backend/catalog/products/${productId}#variants`);
        }
      }
    )
  ] }) });
}
async function transferVariantMedia({
  draftId,
  variantId,
  mediaItems
}) {
  if (!draftId || !variantId) return;
  const attachmentIds = mediaItems.map((item) => item.id).filter((id) => typeof id === "string" && id.length > 0);
  if (!attachmentIds.length) return;
  await apiCall(
    "/api/attachments/transfer",
    {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({
        entityId: E.catalog.catalog_product_variant,
        attachmentIds,
        fromRecordId: draftId,
        toRecordId: variantId
      })
    },
    { fallback: null }
  );
}
async function syncVariantPrices({
  priceKinds,
  priceDrafts,
  productId,
  variantId,
  taxRates,
  taxRateId,
  productTaxRateId,
  productTaxRate
}) {
  const selectedTaxRate = taxRates.find((rate) => rate.id === taxRateId) ?? null;
  const fallbackProductTaxRate = !selectedTaxRate && productTaxRateId ? taxRates.find((rate) => rate.id === productTaxRateId) ?? null : null;
  const resolvedTaxRateValue = selectedTaxRate?.rate ?? fallbackProductTaxRate?.rate ?? (Number.isFinite(productTaxRate ?? null) ? productTaxRate ?? null : null);
  const resolvedTaxRateId = (selectedTaxRate ?? fallbackProductTaxRate)?.id ?? null;
  for (const kind of priceKinds) {
    const draft = priceDrafts?.[kind.id];
    const amount = typeof draft?.amount === "string" ? draft.amount.trim() : "";
    if (!amount) continue;
    const numeric = parseNumericInput(amount);
    if (!Number.isFinite(numeric) || numeric < 0) continue;
    const payload = {
      productId,
      variantId,
      priceKindId: kind.id,
      currencyCode: kind.currencyCode ?? void 0
    };
    if (resolvedTaxRateId) {
      payload.taxRateId = resolvedTaxRateId;
    } else if (typeof resolvedTaxRateValue === "number" && Number.isFinite(resolvedTaxRateValue)) {
      payload.taxRate = resolvedTaxRateValue;
    }
    if (kind.displayMode === "including-tax") payload.unitPriceGross = numeric;
    else payload.unitPriceNet = numeric;
    await createCrud("catalog/prices", payload);
  }
}
export {
  CreateVariantPage as default
};
//# sourceMappingURL=page.js.map
