import { PropsWithChildren } from "react";

import { AssetGroupModel, AssetModel } from "@/contracts/client.schemas";
import { useWatcherStore } from "@/modules/watcher/store/watcher.store";

import { context } from "./context";

export interface Context {
	groups: AssetGroupModel[];
	assets: AssetModel[];
	commonCount: number;
}

export function AlarmAssetsCardContextProvider(props: PropsWithChildren) {
	const allGroups = useWatcherStore((x) => x.groups).sort((a, b) =>
		a.name.localeCompare(b.name),
	);
	const allAssets = useWatcherStore((x) => x.assets).sort((a, b) =>
		a.name.localeCompare(b.name),
	);
	const alarmScopes = useWatcherStore((x) => x.commonAlarmScopes);
	const alarmAssetIdList = new Set(alarmScopes.map((x) => x.assetId));
	const commonCount = alarmAssetIdList.size;

	const assets = allAssets.filter((x) => alarmAssetIdList.has(x.id));

	const groupSet = new Set<string>();
	for (const asset of assets) {
		for (const groupId of asset.groupIds) {
			let tempGroupId: string | undefined = groupId;
			while (tempGroupId) {
				groupSet.add(tempGroupId);
				tempGroupId =
					allGroups.find((x) => x.id === tempGroupId)?.parentId ??
					undefined;
			}
		}
	}

	const groups = allGroups.filter((x) => groupSet.has(x.id));

	return (
		<context.Provider
			value={{
				groups,
				assets,
				commonCount,
			}}
		>
			{props.children}
		</context.Provider>
	);
}
