import { jsx } from 'react/jsx-runtime';
import { lazy } from 'react';
import { defineClientPlugin, createApiClient, runClientHookWithShim } from '@btst/stack/plugins/client';
import { createRoute } from '@btst/yar';
import { createCMSQueryKeys } from '../../../../../../plugins/cms/query-keys.mjs';
import { UI_BUILDER_TYPE_SLUG } from '../schemas.mjs';

const PageListPageComponent = lazy(
  () => import('./components/pages/page-list-page.mjs').then((m) => ({
    default: m.PageListPage
  }))
);
const PageBuilderPageComponent = lazy(
  () => import('./components/pages/page-builder-page.mjs').then((m) => ({
    default: m.PageBuilderPage
  }))
);
function createPageListLoader(config) {
  return async () => {
    if (typeof window === "undefined") {
      const { queryClient, apiBasePath, apiBaseURL, headers, hooks } = config;
      const typeSlug = UI_BUILDER_TYPE_SLUG;
      const context = {
        path: "/ui-builder",
        isSSR: true,
        apiBaseURL,
        apiBasePath,
        headers
      };
      try {
        if (hooks?.beforeLoadPageList) {
          await runClientHookWithShim(
            () => hooks.beforeLoadPageList(context),
            "Load prevented by beforeLoadPageList hook"
          );
        }
        const client = createApiClient({
          baseURL: apiBaseURL,
          basePath: apiBasePath
        });
        const queries = createCMSQueryKeys(client, headers);
        const limit = 20;
        const listQuery = queries.cmsContent.list({
          typeSlug,
          limit,
          offset: 0
        });
        await queryClient.prefetchInfiniteQuery({
          queryKey: [...listQuery.queryKey, "ui-builder"],
          queryFn: async ({ pageParam = 0 }) => {
            const response = await client("/content/:typeSlug", {
              method: "GET",
              params: { typeSlug },
              query: { limit, offset: pageParam },
              headers
            });
            if (typeof response === "object" && response !== null && "error" in response && response.error) {
              throw new Error(String(response.error));
            }
            return response.data;
          },
          initialPageParam: 0
        });
        if (hooks?.afterLoadPageList) {
          await hooks.afterLoadPageList(context);
        }
        const queryState = queryClient.getQueryState([
          ...listQuery.queryKey,
          "ui-builder"
        ]);
        if (queryState?.error && hooks?.onLoadError) {
          const error = queryState.error instanceof Error ? queryState.error : new Error(String(queryState.error));
          await hooks.onLoadError(error, context);
        }
      } catch (error) {
        if (hooks?.onLoadError) {
          await hooks.onLoadError(error, context);
        }
      }
    }
  };
}
function createPageBuilderLoader(id, config) {
  return async () => {
    if (typeof window === "undefined") {
      const { queryClient, apiBasePath, apiBaseURL, headers, hooks } = config;
      const typeSlug = UI_BUILDER_TYPE_SLUG;
      const context = {
        path: id ? `/ui-builder/${id}/edit` : "/ui-builder/new",
        params: id ? { id } : {},
        isSSR: true,
        apiBaseURL,
        apiBasePath,
        headers
      };
      try {
        if (hooks?.beforeLoadPageBuilder) {
          await runClientHookWithShim(
            () => hooks.beforeLoadPageBuilder(id, context),
            "Load prevented by beforeLoadPageBuilder hook"
          );
        }
        const client = createApiClient({
          baseURL: apiBaseURL,
          basePath: apiBasePath
        });
        const queries = createCMSQueryKeys(client, headers);
        if (id) {
          await queryClient.prefetchQuery(
            queries.cmsContent.detail(typeSlug, id)
          );
        }
        if (hooks?.afterLoadPageBuilder) {
          await hooks.afterLoadPageBuilder(id, context);
        }
        if (id) {
          const queryState = queryClient.getQueryState(
            queries.cmsContent.detail(typeSlug, id).queryKey
          );
          if (queryState?.error && hooks?.onLoadError) {
            const error = queryState.error instanceof Error ? queryState.error : new Error(String(queryState.error));
            await hooks.onLoadError(error, context);
          }
        }
      } catch (error) {
        if (hooks?.onLoadError) {
          await hooks.onLoadError(error, context);
        }
      }
    }
  };
}
function createPageListMeta() {
  return () => {
    const title = "UI Builder Pages";
    return [
      { title },
      { name: "title", content: title },
      { name: "robots", content: "noindex" }
    ];
  };
}
function createPageBuilderMeta(id, config) {
  return () => {
    const { queryClient, apiBasePath, apiBaseURL, headers } = config;
    const typeSlug = UI_BUILDER_TYPE_SLUG;
    let pageSlug = "";
    if (id) {
      const client = createApiClient({
        baseURL: apiBaseURL,
        basePath: apiBasePath
      });
      const queries = createCMSQueryKeys(client, headers);
      const page = queryClient.getQueryData(
        queries.cmsContent.detail(typeSlug, id).queryKey
      );
      pageSlug = page?.slug || "";
    }
    const title = id ? `Edit ${pageSlug || "Page"}` : "New Page";
    return [
      { title },
      { name: "title", content: title },
      { name: "robots", content: "noindex" }
    ];
  };
}
const uiBuilderClientPlugin = (config) => defineClientPlugin({
  name: "ui-builder",
  routes: () => ({
    pageList: createRoute("/ui-builder", () => ({
      PageComponent: () => /* @__PURE__ */ jsx(PageListPageComponent, {}),
      loader: createPageListLoader(config),
      meta: createPageListMeta()
    })),
    newPage: createRoute("/ui-builder/new", () => ({
      PageComponent: () => /* @__PURE__ */ jsx(PageBuilderPageComponent, {}),
      loader: createPageBuilderLoader(void 0, config),
      meta: createPageBuilderMeta(void 0, config)
    })),
    editPage: createRoute("/ui-builder/:id/edit", ({ params }) => ({
      PageComponent: () => /* @__PURE__ */ jsx(PageBuilderPageComponent, { id: params.id }),
      loader: createPageBuilderLoader(params.id, config),
      meta: createPageBuilderMeta(params.id, config)
    }))
  }),
  sitemap: async () => {
    return [];
  }
});

export { uiBuilderClientPlugin };
