"use client";
'use strict';

const jsxRuntime = require('react/jsx-runtime');
const React = require('react');
const LucideIcons = require('lucide-react');
const button = require('../../../../../../../ui/src/components/button.cjs');
const context = require('@btst/stack/context');
const contentForm = require('../forms/content-form.cjs');
const inverseRelationsPanel = require('../inverse-relations-panel.cjs');
const emptyState = require('../shared/empty-state.cjs');
const pageWrapper = require('../shared/page-wrapper.cjs');
const editorSkeleton = require('../loading/editor-skeleton.cjs');
const index = require('../../localization/index.cjs');
const useRouteLifecycle = require('../../../../../../../ui/src/hooks/use-route-lifecycle.cjs');
const cmsHooks = require('../../hooks/cms-hooks.cjs');

function usePrefillParams() {
  const [prefillData, setPrefillData] = React.useState({});
  React.useEffect(() => {
    if (typeof window === "undefined") {
      return;
    }
    const parseAndSetPrefillData = () => {
      const params = new URLSearchParams(window.location.search);
      const data = {};
      for (const [key, value] of params.entries()) {
        if (key.startsWith("prefill_")) {
          const fieldName = key.slice("prefill_".length);
          if (fieldName) {
            data[fieldName] = value;
          }
        }
      }
      setPrefillData(data);
    };
    parseAndSetPrefillData();
    window.addEventListener("popstate", parseAndSetPrefillData);
    return () => {
      window.removeEventListener("popstate", parseAndSetPrefillData);
    };
  }, []);
  return prefillData;
}
function convertPrefillToFormData(prefillParams, jsonSchema) {
  const properties = jsonSchema.properties;
  if (!properties) {
    return prefillParams;
  }
  const result = {};
  for (const [fieldName, value] of Object.entries(prefillParams)) {
    const fieldSchema = properties[fieldName];
    if (fieldSchema?.fieldType === "relation" && fieldSchema.relation) {
      if (fieldSchema.relation.type === "belongsTo") {
        result[fieldName] = { id: value };
      } else {
        result[fieldName] = [{ id: value }];
      }
    } else {
      result[fieldName] = value;
    }
  }
  return result;
}
function ContentEditorPage({ typeSlug, id }) {
  const overrides = context.usePluginOverrides("cms");
  const { navigate } = overrides;
  const localization = { ...index.CMS_LOCALIZATION, ...overrides.localization };
  const basePath = context.useBasePath();
  const prefillParams = usePrefillParams();
  useRouteLifecycle.useRouteLifecycle({
    routeName: "contentEditor",
    context: {
      path: id ? `/cms/${typeSlug}/${id}` : `/cms/${typeSlug}/new`,
      params: id ? { typeSlug, id } : { typeSlug },
      isSSR: typeof window === "undefined"
    },
    overrides,
    beforeRenderHook: (overrides2, context) => {
      if (overrides2.onBeforeEditorRendered) {
        return overrides2.onBeforeEditorRendered(typeSlug, id ?? null, context);
      }
      return true;
    }
  });
  const { contentTypes } = cmsHooks.useSuspenseContentTypes();
  const contentType = contentTypes.find((ct) => ct.slug === typeSlug);
  const isEditing = !!id;
  const { item, isLoading: isLoadingItem } = cmsHooks.useContentItem(typeSlug, id ?? "");
  const createContent = cmsHooks.useCreateContent(typeSlug);
  const updateContent = cmsHooks.useUpdateContent(typeSlug);
  if (!contentType) {
    return /* @__PURE__ */ jsxRuntime.jsx(pageWrapper.PageWrapper, { testId: "cms-editor-page", children: /* @__PURE__ */ jsxRuntime.jsx("div", { className: "w-full max-w-2xl", children: /* @__PURE__ */ jsxRuntime.jsx(
      emptyState.EmptyState,
      {
        title: localization.CMS_ERROR_NOT_FOUND,
        description: "Content type not found"
      }
    ) }) });
  }
  if (isEditing && isLoadingItem) {
    return /* @__PURE__ */ jsxRuntime.jsx(pageWrapper.PageWrapper, { testId: "cms-editor-page", children: /* @__PURE__ */ jsxRuntime.jsx("div", { className: "w-full max-w-2xl", children: /* @__PURE__ */ jsxRuntime.jsx(editorSkeleton.EditorSkeleton, {}) }) });
  }
  if (isEditing && !item) {
    return /* @__PURE__ */ jsxRuntime.jsx(pageWrapper.PageWrapper, { testId: "cms-editor-page", children: /* @__PURE__ */ jsxRuntime.jsx("div", { className: "w-full max-w-2xl", children: /* @__PURE__ */ jsxRuntime.jsx(
      emptyState.EmptyState,
      {
        title: localization.CMS_ERROR_NOT_FOUND,
        description: "Content item not found"
      }
    ) }) });
  }
  const handleSubmit = async (data) => {
    if (isEditing && id) {
      await updateContent.mutateAsync({ id, data });
    } else {
      await createContent.mutateAsync(data);
    }
    navigate(`${basePath}/cms/${typeSlug}`);
  };
  const title = isEditing ? localization.CMS_EDITOR_TITLE_EDIT.replace("{typeName}", contentType.name) : localization.CMS_EDITOR_TITLE_NEW.replace("{typeName}", contentType.name);
  return /* @__PURE__ */ jsxRuntime.jsx(pageWrapper.PageWrapper, { testId: "cms-editor-page", children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "w-full max-w-2xl space-y-6", children: [
    /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-4", children: [
      /* @__PURE__ */ jsxRuntime.jsx(
        button.Button,
        {
          variant: "ghost",
          size: "icon",
          onClick: () => navigate(`${basePath}/cms/${typeSlug}`),
          children: /* @__PURE__ */ jsxRuntime.jsx(LucideIcons.ArrowLeft, { className: "h-4 w-4" })
        }
      ),
      /* @__PURE__ */ jsxRuntime.jsx("h1", { className: "text-2xl font-bold tracking-tight", children: title })
    ] }),
    /* @__PURE__ */ jsxRuntime.jsx(
      contentForm.ContentForm,
      {
        contentType,
        initialData: isEditing ? item?.parsedData : Object.keys(prefillParams).length > 0 ? convertPrefillToFormData(
          prefillParams,
          JSON.parse(contentType.jsonSchema)
        ) : void 0,
        initialSlug: item?.slug,
        isEditing,
        onSubmit: handleSubmit,
        onCancel: () => navigate(`${basePath}/cms/${typeSlug}`)
      },
      isEditing ? `edit-${id}` : "create"
    ),
    isEditing && id && /* @__PURE__ */ jsxRuntime.jsx(inverseRelationsPanel.InverseRelationsPanel, { contentTypeSlug: typeSlug, itemId: id })
  ] }) });
}

exports.ContentEditorPage = ContentEditorPage;
