import type { Context } from "koa";
import { tempstream, TempstreamJSX } from "tempstream";
import { Page } from "@sealcode/sealgen";
import html, { defaultHead } from "../html.js";
import { registry } from "../jdd-components/components.js";
import { documentContainerFromParsed, render, renderEarlyAssets } from "@sealcode/jdd";
import { shuffle } from "../util.js";
import { makeJDDContext } from "../jdd-context.js";

export const actionName = "AllComponents";

export default new (class AllComponentsPage extends Page {
	// eslint-disable-next-line @typescript-eslint/no-unused-vars
	async canAccess(_: Context) {
		return { canAccess: true, message: "" };
	}

	async render(ctx: Context) {
		const components = registry.getAll();
		const jdd_context = makeJDDContext(ctx);
		const document = await Promise.all(
			shuffle(Object.entries(components)).map(
				async ([component_name, component]) => {
					return {
						component_name,
						args: await component.getExampleValues(jdd_context),
					};
				}
			)
		);
		return html(
			ctx,
			"AllComponents",
			<div>
				{render(registry, documentContainerFromParsed(document), jdd_context)}
			</div>,
			{},
			(...args) =>
				tempstream`${defaultHead(...args)}${renderEarlyAssets(
					registry,
					documentContainerFromParsed(document),
					jdd_context
				)}`
		);
	}
})();
