import { Fragment } from "react/jsx-runtime";

import { AssetGroupModel } from "@/contracts/client.schemas";

import { useAllAssetsCardContext } from "../contexts/useAllAssetsCardContext";
import { GroupView } from "../GroupView/GroupView";

interface Props {
	parentId?: string;
	depth?: number;
}

export function GroupListView(props: Props) {
	const context = useAllAssetsCardContext();

	let viewGroups: AssetGroupModel[] = [];
	if (!props.parentId) {
		viewGroups = context.groups.filter((x) => !x.parentId);
	} else {
		viewGroups = context.groups.filter(
			(x) => x.parentId === props.parentId,
		);
	}

	const depth = props.depth !== undefined ? props.depth + 1 : 0;

	return (
		<Fragment key={"group-list-" + props.parentId}>
			{viewGroups.map((group) => (
				<Fragment key={"group-list-inner-" + group.id}>
					<GroupView
						key={group.id}
						id={group.id}
						label={group.name}
						depth={depth}
					/>

					{context.isActiveGroup(group.id) && (
						<GroupListView
							depth={depth}
							parentId={group.id}
							key={"list-" + group.id}
						/>
					)}
				</Fragment>
			))}
		</Fragment>
	);
}
