import type { BaseContext } from "koa";
import { TempstreamJSX } from "tempstream";
import type { ComponentArgument, List } from "@sealcode/jdd";
import type { JDDPageState } from "./jdd-page.js";
import type { StatefulPage } from "@sealcode/sealgen";
import { ComponentInput } from "./component-input.js";
import type { ComponentPreviewActions } from "./component-preview-actions.js";

export async function ComponentInputList<
	State extends JDDPageState,
	T extends ComponentArgument<unknown>
>({
	state,
	ctx,
	arg_path,
	arg,
	value,
	page,
}: {
	state: State;
	ctx: BaseContext;
	arg_path: string[];
	// eslint-disable-next-line @typescript-eslint/no-explicit-any
	arg: List<T, any>;
	value: T[];
	page: StatefulPage<JDDPageState, typeof ComponentPreviewActions>;
}): Promise<string> {
	if (!value) {
		value = [];
	}
	return (
		<fieldset>
			<legend>{arg_path.at(-1)}</legend>
			{value.map((value, i) => (
				<div style="display: flex">
					<ComponentInput
						{...{
							ctx,
							state,
							arg_path: [...arg_path, i.toString()],
							arg: arg.item_type,
							value,
							page,
						}}
					/>
					{page.makeActionButton(
						state,
						{ action: "remove_array_item", label: "❌" },
						arg_path,
						i
					)}
				</div>
			))}
			{page.makeActionButton(
				state,
				{
					action: "add_array_item",
					label: "➕",
				},
				arg_path
			)}
		</fieldset>
	);
}
