import { useEffect, useRef } from "react";
import { useDispatch } from "react-redux";

import { useManualHistory } from "@hooks/apis/manual/useManualHistory";
import { useAccounts } from "@hooks/useAccounts";
import { resetManualHistory } from "@store/globalSlice";

export const useHistoryCleanup = () => {
	const { accounts } = useAccounts();
	const dispatch = useDispatch();
	const { allData: data, addressDataMap } = useManualHistory({
		userAddresses: accounts
			.map((account) => account.address)
			.filter((address) => address !== undefined),
		pageNumber: 1,
		pageSize: 5,
	});

	const firstRender = useRef(true);

	useEffect(() => {
		if (!data?.length || !firstRender.current || !accounts) return;
		// const oneWeekAgo = Math.floor(Date.now() / 1000) - 7 * 24 * 60 * 60; // Convert to seconds

		for (const account of accounts) {
			if (!account.address) continue;
			const data = addressDataMap[account.address.toLowerCase()];
			const filtered = [...data].reverse().slice(0, 10); // reversing the data as the latest items are pushed to the array
			dispatch(
				resetManualHistory({
					address: account.address,
					data: filtered.reverse(),
				}),
			); // reversing again before updating store
		}
		firstRender.current = false;
	}, [accounts, addressDataMap, data, dispatch]);
};
