"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { Page, PageBody } from "@open-mercato/ui/backend/Page";
import { CrudForm } from "@open-mercato/ui/backend/CrudForm";
import { ErrorMessage, RecordNotFoundState } from "@open-mercato/ui/backend/detail";
import { collectCustomFieldValues } from "@open-mercato/ui/backend/utils/customFieldValues";
import { updateCrud, deleteCrud } from "@open-mercato/ui/backend/utils/crud";
import { readApiResultOrThrow } from "@open-mercato/ui/backend/utils/apiCall";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { extractCustomFieldEntries } from "@open-mercato/shared/lib/crud/custom-fields-client";
import { useChannelFields, buildChannelPayload } from "@open-mercato/core/modules/sales/components/channels/channelFormFields";
import { E } from "../../../../../../../generated/entities.ids.generated.js";
import { SalesChannelOffersPanel } from "@open-mercato/core/modules/sales/components/channels/SalesChannelOffersPanel";
import { SendObjectMessageDialog } from "@open-mercato/ui/backend/messages";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("sales");
function EditChannelPage({ params }) {
  const channelId = params?.channelId ?? "";
  const router = useRouter();
  const searchParams = useSearchParams();
  const t = useT();
  const { fields, groups } = useChannelFields();
  const [initialValues, setInitialValues] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState(null);
  const [isNotFound, setIsNotFound] = React.useState(false);
  const [activeTab, setActiveTab] = React.useState("settings");
  React.useEffect(() => {
    const tabParam = (searchParams?.get("tab") ?? "").toLowerCase();
    if (tabParam === "offers") {
      setActiveTab("offers");
    } else if (tabParam === "settings") {
      setActiveTab("settings");
    }
  }, [searchParams]);
  React.useEffect(() => {
    if (!channelId) return;
    let cancelled = false;
    async function loadChannel() {
      setLoading(true);
      setError(null);
      setIsNotFound(false);
      try {
        const payload = await readApiResultOrThrow(
          `/api/sales/channels?id=${encodeURIComponent(channelId)}&pageSize=1`,
          void 0,
          { errorMessage: t("sales.channels.form.errors.load", "Failed to load channel.") }
        );
        const item = Array.isArray(payload.items) ? payload.items[0] : null;
        if (!item) {
          if (!cancelled) setIsNotFound(true);
          return;
        }
        if (!cancelled) {
          setInitialValues(mapChannelToFormValues(item));
        }
      } catch (err) {
        logger.error("sales.channels.load", { err });
        if (!cancelled) {
          if (err.status === 404) {
            setIsNotFound(true);
          } else {
            setError(t("sales.channels.form.errors.load", "Failed to load channel."));
          }
        }
      } finally {
        if (!cancelled) setLoading(false);
      }
    }
    void loadChannel();
    return () => {
      cancelled = true;
    };
  }, [channelId, t]);
  const handleSubmit = React.useCallback(async (values) => {
    if (!channelId) return;
    const payload = { id: channelId, ...buildChannelPayload(values) };
    const customFields = collectCustomFieldValues(values);
    if (Object.keys(customFields).length) payload.customFields = customFields;
    await updateCrud("sales/channels", payload, {
      errorMessage: t("sales.channels.form.errors.update", "Failed to save channel.")
    });
    flash(t("sales.channels.form.messages.updated", "Channel updated."), "success");
    router.push("/backend/sales/channels");
  }, [channelId, router, t]);
  const handleDelete = React.useCallback(async () => {
    if (!channelId) return;
    await deleteCrud("sales/channels", channelId, {
      errorMessage: t("sales.channels.form.errors.delete", "Failed to delete channel.")
    });
    flash(t("sales.channels.form.messages.deleted", "Channel deleted."), "success");
    router.push("/backend/sales/channels");
  }, [channelId, router, t]);
  const handleTabSelect = React.useCallback((value) => {
    setActiveTab(value);
    if (!channelId) return;
    const basePath = `/backend/sales/channels/${channelId}/edit`;
    const nextUrl = value === "offers" ? `${basePath}?tab=offers` : basePath;
    router.replace(nextUrl);
  }, [channelId, router]);
  const tabButton = React.useCallback((value, label) => /* @__PURE__ */ jsx(
    "button",
    {
      type: "button",
      className: `px-4 py-2 text-sm font-medium border-b-2 ${activeTab === value ? "border-accent-indigo text-foreground" : "border-transparent text-muted-foreground"}`,
      onClick: () => handleTabSelect(value),
      children: label
    },
    value
  ), [activeTab, handleTabSelect]);
  const renderTabs = React.useCallback(() => /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 border-b mb-6", children: [
    tabButton("settings", t("sales.channels.form.tabs.settings", "Settings")),
    tabButton("offers", t("sales.channels.form.tabs.offers", "Offers"))
  ] }), [tabButton, t]);
  if (isNotFound) {
    return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(
      RecordNotFoundState,
      {
        label: t("sales.channels.form.errors.notFound", "Channel not found."),
        backHref: "/backend/sales/channels",
        backLabel: t("sales.channels.actions.backToList", "Back to channels")
      }
    ) }) });
  }
  if (error && !loading && !initialValues) {
    return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(ErrorMessage, { label: error }) }) });
  }
  return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: activeTab === "settings" ? /* @__PURE__ */ jsx(
    CrudForm,
    {
      title: t("sales.channels.form.editTitle", "Edit channel"),
      versionHistory: { resourceKind: "sales.channel", resourceId: channelId ? String(channelId) : "" },
      extraActions: channelId ? /* @__PURE__ */ jsx(
        SendObjectMessageDialog,
        {
          object: {
            entityModule: "sales",
            entityType: "channel",
            entityId: channelId,
            previewData: {
              title: initialValues?.name ?? "",
              metadata: {
                [t("sales.channels.form.contactEmail")]: initialValues?.contactEmail ?? "-",
                [t("sales.channels.form.websiteUrl")]: initialValues?.websiteUrl ?? "-"
              }
            }
          },
          viewHref: `/backend/sales/channels/${channelId}/edit`
        }
      ) : void 0,
      entityId: E.sales.sales_channel,
      fields,
      groups: [
        ...groups,
        { id: "custom", title: t("entities.customFields.title", "Custom Attributes"), column: 2, kind: "customFields" }
      ],
      initialValues: initialValues ?? void 0,
      optimisticLockUpdatedAt: typeof initialValues?.updatedAt === "string" ? initialValues.updatedAt : null,
      isLoading: loading,
      loadingMessage: t("sales.channels.form.loading", "Loading channel\u2026"),
      submitLabel: t("sales.channels.form.updateSubmit", "Save changes"),
      cancelHref: "/backend/sales/channels",
      backHref: "/backend/sales/channels",
      contentHeader: renderTabs(),
      onSubmit: handleSubmit,
      onDelete: handleDelete,
      deleteVisible: true,
      deleteRedirect: "/backend/sales/channels"
    }
  ) : /* @__PURE__ */ jsxs(Fragment, { children: [
    renderTabs(),
    /* @__PURE__ */ jsx(SalesChannelOffersPanel, { channelId, channelName: initialValues?.name ?? "" })
  ] }) }) });
}
function mapChannelToFormValues(item) {
  const values = {
    name: typeof item.name === "string" ? item.name : "",
    code: typeof item.code === "string" ? item.code : null,
    description: typeof item.description === "string" ? item.description : null,
    websiteUrl: typeof item.websiteUrl === "string" ? item.websiteUrl : typeof item.website_url === "string" ? item.website_url : null,
    contactEmail: typeof item.contactEmail === "string" ? item.contactEmail : typeof item.contact_email === "string" ? item.contact_email : null,
    contactPhone: typeof item.contactPhone === "string" ? item.contactPhone : typeof item.contact_phone === "string" ? item.contact_phone : null,
    addressLine1: typeof item.addressLine1 === "string" ? item.addressLine1 : typeof item.address_line1 === "string" ? item.address_line1 : null,
    addressLine2: typeof item.addressLine2 === "string" ? item.addressLine2 : typeof item.address_line2 === "string" ? item.address_line2 : null,
    city: typeof item.city === "string" ? item.city : null,
    region: typeof item.region === "string" ? item.region : null,
    postalCode: typeof item.postalCode === "string" ? item.postalCode : typeof item.postal_code === "string" ? item.postal_code : null,
    country: typeof item.country === "string" ? item.country : null,
    latitude: typeof item.latitude === "number" ? item.latitude : typeof item.latitude === "string" ? item.latitude : null,
    longitude: typeof item.longitude === "number" ? item.longitude : typeof item.longitude === "string" ? item.longitude : null,
    statusEntryId: typeof item.statusEntryId === "string" ? item.statusEntryId : typeof item.status_entry_id === "string" ? item.status_entry_id : null,
    isActive: item.isActive === true || item.is_active === true,
    updatedAt: typeof item.updatedAt === "string" ? item.updatedAt : typeof item.updated_at === "string" ? item.updated_at : null
  };
  return { ...values, ...extractCustomFieldEntries(item) };
}
export {
  EditChannelPage as default
};
//# sourceMappingURL=page.js.map
