import { PropsWithChildren, useState } from "react";

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

import { context } from "./context";

export interface Context {
	activeAssetId?: string;
	setActiveAssetId: (id?: string) => void;

	isActiveGroup: (groupId: string) => boolean;
	activateGroup: (groupId: string) => void;
	deactivateGroup: (groupId: string) => void;

	groups: AssetGroupModel[];
	assets: AssetModel[];
}

export function AllAssetsCardContextProvider(props: PropsWithChildren) {
	const [activeAssetId, setActiveAssetId] = useState<string>();
	const [activeGroupIdList, setActiveGroupIdList] = useState(
		new Set<string>(),
	);

	const groups = useWatcherStore((x) => x.groups).sort((a, b) =>
		a.name.localeCompare(b.name),
	);
	const assets = useWatcherStore((x) => x.assets).sort((a, b) =>
		a.name.localeCompare(b.name),
	);

	function isActiveGroup(groupId: string) {
		return activeGroupIdList.has(groupId);
	}

	function activateGroup(groupId: string) {
		const newSet = new Set<string>();
		let id: string | undefined | null = groupId;
		while (id) {
			newSet.add(id);
			id = groups.find((x) => x.id === id)?.parentId;
		}

		for (const groupId of activeGroupIdList) {
			activeGroupIdList.add(groupId);
		}

		setActiveGroupIdList(newSet);
	}

	function deactivateGroup(groupId: string) {
		activeGroupIdList.delete(groupId);
	}

	return (
		<context.Provider
			value={{
				activeAssetId,
				setActiveAssetId,
				isActiveGroup,
				activateGroup,
				deactivateGroup,
				groups,
				assets,
			}}
		>
			{props.children}
		</context.Provider>
	);
}
