"use client";
import { jsx, jsxs } from 'react/jsx-runtime';
import { useState, useEffect } from 'react';
import { ArrowLeft } from 'lucide-react';
import { Button } from '../../../../../../../ui/src/components/button.mjs';
import { usePluginOverrides, useBasePath } from '@btst/stack/context';
import { ContentForm } from '../forms/content-form.mjs';
import { InverseRelationsPanel } from '../inverse-relations-panel.mjs';
import { EmptyState } from '../shared/empty-state.mjs';
import { PageWrapper } from '../shared/page-wrapper.mjs';
import { EditorSkeleton } from '../loading/editor-skeleton.mjs';
import { CMS_LOCALIZATION } from '../../localization/index.mjs';
import { useRouteLifecycle } from '../../../../../../../ui/src/hooks/use-route-lifecycle.mjs';
import { useSuspenseContentTypes, useContentItem, useCreateContent, useUpdateContent } from '../../hooks/cms-hooks.mjs';

function usePrefillParams() {
  const [prefillData, setPrefillData] = useState({});
  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 = usePluginOverrides("cms");
  const { navigate } = overrides;
  const localization = { ...CMS_LOCALIZATION, ...overrides.localization };
  const basePath = useBasePath();
  const prefillParams = usePrefillParams();
  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 } = useSuspenseContentTypes();
  const contentType = contentTypes.find((ct) => ct.slug === typeSlug);
  const isEditing = !!id;
  const { item, isLoading: isLoadingItem } = useContentItem(typeSlug, id ?? "");
  const createContent = useCreateContent(typeSlug);
  const updateContent = useUpdateContent(typeSlug);
  if (!contentType) {
    return /* @__PURE__ */ jsx(PageWrapper, { testId: "cms-editor-page", children: /* @__PURE__ */ jsx("div", { className: "w-full max-w-2xl", children: /* @__PURE__ */ jsx(
      EmptyState,
      {
        title: localization.CMS_ERROR_NOT_FOUND,
        description: "Content type not found"
      }
    ) }) });
  }
  if (isEditing && isLoadingItem) {
    return /* @__PURE__ */ jsx(PageWrapper, { testId: "cms-editor-page", children: /* @__PURE__ */ jsx("div", { className: "w-full max-w-2xl", children: /* @__PURE__ */ jsx(EditorSkeleton, {}) }) });
  }
  if (isEditing && !item) {
    return /* @__PURE__ */ jsx(PageWrapper, { testId: "cms-editor-page", children: /* @__PURE__ */ jsx("div", { className: "w-full max-w-2xl", children: /* @__PURE__ */ jsx(
      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__ */ jsx(PageWrapper, { testId: "cms-editor-page", children: /* @__PURE__ */ jsxs("div", { className: "w-full max-w-2xl space-y-6", children: [
    /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-4", children: [
      /* @__PURE__ */ jsx(
        Button,
        {
          variant: "ghost",
          size: "icon",
          onClick: () => navigate(`${basePath}/cms/${typeSlug}`),
          children: /* @__PURE__ */ jsx(ArrowLeft, { className: "h-4 w-4" })
        }
      ),
      /* @__PURE__ */ jsx("h1", { className: "text-2xl font-bold tracking-tight", children: title })
    ] }),
    /* @__PURE__ */ jsx(
      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__ */ jsx(InverseRelationsPanel, { contentTypeSlug: typeSlug, itemId: id })
  ] }) });
}

export { ContentEditorPage };
