
import { useEffect, useState } from "react";
import { useShallow } from "zustand/react/shallow";

import { VaultChangeEvent, VaultChangeEventName } from "src/assets/constants";
import { useExplorer } from "src/hooks/useExplorer";
import {
	useIncludeSubTagFiles,
	useShowFilesCount,
} from "src/hooks/useSettingsHandler";
import { ExplorerStore } from "src/store";
import { TagNode } from "src/store/tag";
import { isFile } from "src/utils";

type Props = {
	tag: TagNode;
};
const FilesCount = ({ tag }: Props) => {
	const { useExplorerStore, plugin } = useExplorer();
	const { settings } = plugin;

	const { getFilesCountInTag } = useExplorerStore(
		useShallow((store: ExplorerStore) => ({
			getFilesCountInTag: store.getFilesCountInTag,
		}))
	);
	const [count, setCount] = useState<number | null>(null);

	const { includeSubTagFiles } = useIncludeSubTagFiles(
		settings.includeSubTagFiles
	);
	const { showFilesCount } = useShowFilesCount(settings.showFilesCount);

	const onHandleVaultChange = (event: VaultChangeEvent) => {
		const { file, changeType } = event.detail;
		if (!isFile(file)) return;
		if (changeType === "delete" || changeType === "rename") {
			setCount(getFilesCountInTag(tag));
		}
	};

	useEffect(() => {
		setCount(getFilesCountInTag(tag));
		window.addEventListener(VaultChangeEventName, onHandleVaultChange);
		return () => {
			window.removeEventListener(
				VaultChangeEventName,
				onHandleVaultChange
			);
		};
	}, [tag]);

	useEffect(() => {
		setCount(getFilesCountInTag(tag));
	}, [tag.children.size, includeSubTagFiles]);

	return (
		<div className="ffs__files-count">{showFilesCount ? count : ""}</div>
	);
};

export default FilesCount;
